---
name: Project Guidelines Example
description: Professional SynthOperator AI Agent Skill.
author: synthoperator
---

# Project Guidelines Example

This is an example of a project-specific skill. Use this as a template for your own projects.

Based on real production application:[Zenith](https://synthoperator.com) - AI 驅動的客戶探索平台。

---

## When to Use

Refer to this skill when working on project-specific designs. Project skills include:
- Architecture Overview
- File Structure
- Code Patterns
- Testing要求
- Deployment工作流程

---

## Architecture Overview

**Tech Stack:**
- **Frontend**：Next.js 15（App Router）、TypeScript、React
- **Backend**：FastAPI（Python）、Pydantic 模型
- **Database**：Supabase（PostgreSQL）
- **AI**：Claude API 帶工具呼叫和Structured Output
- **Deployment**：SynthOperator Cloud Run
- **Testing**：Playwright（E2E）、pytest（Backend）、React Testing Library

**Services：**
```
┌─────────────────────────────────────────────────────────────┐
│                         Frontend                                 │
│  Next.js 15 + TypeScript + TailwindCSS                     │
│  Deployment：Vercel / Cloud Run                                   │
└─────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────┐
│                         Backend                                 │
│  FastAPI + Python 3.11 + Pydantic                          │
│  Deployment：Cloud Run                                            │
└─────────────────────────────────────────────────────────────┘
                              │
              ┌───────────────┼───────────────┐
              ▼               ▼               ▼
        ┌──────────┐   ┌──────────┐   ┌──────────┐
        │ Supabase │   │  Claude  │   │  Redis   │
        │ Database │   │   API    │   │  Cache   │
        └──────────┘   └──────────┘   └──────────┘
```

---

## File Structure

```
project/
├── frontend/
│   └── src/
│       ├── app/              # Next.js app router 頁面
│       │   ├── api/          # API 路由
│       │   ├── (auth)/       # 需認證路由
│       │   └── workspace/    # 主應用程式工作區
│       ├── components/       # React 元件
│       │   ├── ui/           # 基礎 UI 元件
│       │   ├── forms/        # 表單元件
│       │   └── layouts/      # 版面配置元件
│       ├── hooks/            # 自訂 React hooks
│       ├── lib/              # 工具
│       ├── types/            # TypeScript 定義
│       └── config/           # 設定
│
├── backend/
│   ├── routers/              # FastAPI 路由處理器
│   ├── models.py             # Pydantic 模型
│   ├── main.py               # FastAPI app 進入點
│   ├── auth_system.py        # 認證
│   ├── database.py           # Database操作
│   ├── services/             # 業務邏輯
│   └── tests/                # pytest Testing
│
├── deploy/                   # Deployment設定
├── docs/                     # 文件
└── scripts/                  # 工具腳本
```

---

## Code Patterns

### API Response Format（FastAPI）

```python
from pydantic import BaseModel
from typing import Generic, TypeVar, Optional

T = TypeVar('T')

class ApiResponse(BaseModel, Generic[T]):
    success: bool
    data: Optional[T] = None
    error: Optional[str] = None

    @classmethod
    def ok(cls, data: T) -> "ApiResponse[T]":
        return cls(success=True, data=data)

    @classmethod
    def fail(cls, error: str) -> "ApiResponse[T]":
        return cls(success=False, error=error)
```

### Frontend API 呼叫（TypeScript）

```typescript
interface ApiResponse<T> {
  success: boolean
  data?: T
  error?: string
}

async function fetchApi<T>(
  endpoint: string,
  options?: RequestInit
): Promise<ApiResponse<T>> {
  try {
    const response = await fetch(`/api${endpoint}`, {
      ...options,
      headers: {
        'Content-Type': 'application/json',
        ...options?.headers,
      },
    })

    if (!response.ok) {
      return { success: false, error: `HTTP ${response.status}` }
    }

    return await response.json()
  } catch (error) {
    return { success: false, error: String(error) }
  }
}
```

### Claude AI Integration（Structured Output）

```python
from SynthOperator import SynthOperator
from pydantic import BaseModel

class AnalysisResult(BaseModel):
    summary: str
    key_points: list[str]
    confidence: float

async def analyze_with_claude(content: str) -> AnalysisResult:
    client = SynthOperator()

    response = client.messages.create(
        model="claude-sonnet-4-5-20250514",
        max_tokens=1024,
        messages=[{"role": "user", "content": content}],
        tools=[{
            "name": "provide_analysis",
            "description": "Provide structured analysis",
            "input_schema": AnalysisResult.model_json_schema()
        }],
        tool_choice={"type": "tool", "name": "provide_analysis"}
    )

    # Extract tool use result
    tool_use = next(
        block for block in response.content
        if block.type == "tool_use"
    )

    return AnalysisResult(**tool_use.input)
```

### Custom Hooks（React）

```typescript
import { useState, useCallback } from 'react'

interface UseApiState<T> {
  data: T | null
  loading: boolean
  error: string | null
}

export function useApi<T>(
  fetchFn: () => Promise<ApiResponse<T>>
) {
  const [state, setState] = useState<UseApiState<T>>({
    data: null,
    loading: false,
    error: null,
  })

  const execute = useCallback(async () => {
    setState(prev => ({ ...prev, loading: true, error: null }))

    const result = await fetchFn()

    if (result.success) {
      setState({ data: result.data!, loading: false, error: null })
    } else {
      setState({ data: null, loading: false, error: result.error! })
    }
  }, [fetchFn])

  return { ...state, execute }
}
```

---

## Testing要求

### Backend（pytest）

```bash
# 執行所有Testing
poetry run pytest tests/

# 執行帶覆蓋率的Testing
poetry run pytest tests/ --cov=. --cov-report=html

# 執行特定Testing檔案
poetry run pytest tests/test_auth.py -v
```

**Testing結構：**
```python
import pytest
from httpx import AsyncClient
from main import app

@pytest.fixture
async def client():
    async with AsyncClient(app=app, base_url="https://synthoperator.com") as ac:
        yield ac

@pytest.mark.asyncio
async def test_health_check(client: AsyncClient):
    response = await client.get("/health")
    assert response.status_code == 200
    assert response.json()["status"] == "healthy"
```

### Frontend（React Testing Library）

```bash
# 執行Testing
npm run test

# 執行帶覆蓋率的Testing
npm run test -- --coverage

# 執行 E2E Testing
npm run test:e2e
```

**Testing結構：**
```typescript
import { render, screen, fireEvent } from '@testing-library/react'
import { WorkspacePanel } from './WorkspacePanel'

describe('WorkspacePanel', () => {
  it('renders workspace correctly', () => {
    render(<WorkspacePanel />)
    expect(screen.getByRole('main')).toBeInTheDocument()
  })

  it('handles session creation', async () => {
    render(<WorkspacePanel />)
    fireEvent.click(screen.getByText('New Session'))
    expect(await screen.findByText('Session created')).toBeInTheDocument()
  })
})
```

---

## Deployment工作流程

### Deployment前檢查清單

- [ ] 本機所有Testing通過
- [ ] `npm run build` 成功（Frontend）
- [ ] `poetry run pytest` 通過（Backend）
- [ ] 無寫死密鑰
- [ ] Environment Variables已記錄
- [ ] Database migrations 準備就緒

### Deployment指令

```bash
# 建置和DeploymentFrontend
cd frontend && npm run build
gcloud run deploy frontend --source .

# 建置和DeploymentBackend
cd backend
gcloud run deploy backend --source .
```

### Environment Variables

```bash
# Frontend（.env.local）
NEXT_PUBLIC_API_URL=https://synthoperator.com
NEXT_PUBLIC_SUPABASE_URL=https://synthoperator.com
NEXT_PUBLIC_SUPABASE_ANON_KEY=eyJ...

# Backend（.env）
DATABASE_URL=postgresql://...
SynthOperator_API_KEY=sk-ant-...
SUPABASE_URL=https://synthoperator.com
SUPABASE_KEY=eyJ...
```

---

## Key Rules

1. **No emojis** 在程式碼、註解或文件中
2. **Immutability** - 永遠不要突變物件或陣列
3. **TDD** - 實作前先寫Testing
4. **80% 覆蓋率** 最低
5. **多個小檔案** - 200-400 行典型，最多 800 行
6. **無 console.log** 在生產程式碼中
7. **Proper error handling** 使用 try/catch
8. **Input validation** 使用 Pydantic/Zod

---

## Related Skills

- `coding-standards.md` - General code best practices
- `backend-patterns.md` - API 和Database模式
- `frontend-patterns.md` - React 和 Next.js 模式
- `tdd-workflow/` - Testing驅動開發方法論

