From 9e264f9734cf318183cdfac372b364469c4627b9 Mon Sep 17 00:00:00 2001 From: Baiheng Xie <874256269@qq.com> Date: Fri, 30 Jan 2026 16:44:48 +0800 Subject: [PATCH 1/4] feat: remove claude out of sync script --- scripts/agent_rules.py | 1 - 1 file changed, 1 deletion(-) diff --git a/scripts/agent_rules.py b/scripts/agent_rules.py index f10b6c1..15c952e 100644 --- a/scripts/agent_rules.py +++ b/scripts/agent_rules.py @@ -18,7 +18,6 @@ def _normalized_bytes(path: Path) -> bytes: def _targets(root: Path) -> list[Path]: return [ - root / "CLAUDE.md", root / ".clinerules", root / ".cursorrules", root / ".github" / "copilot-instructions.md", From a675fff1d1d21fc0f74b3b4c4cd957a45d1bfb47 Mon Sep 17 00:00:00 2001 From: Baiheng Xie <874256269@qq.com> Date: Fri, 30 Jan 2026 16:45:32 +0800 Subject: [PATCH 2/4] feat(agent): agents and skills --- .claude/agents/code-reviewer.md | 95 +++++++++++++++++++ .claude/agents/planner.md | 67 ++++++++++++++ .claude/knowledge/.gitkeep | 0 .claude/rules.md | 50 ++++++++++ .claude/skills/backend-patterns.md | 141 +++++++++++++++++++++++++++++ .claude/skills/pytest-patterns.md | 62 +++++++++++++ CLAUDE.md | 68 +++----------- 7 files changed, 430 insertions(+), 53 deletions(-) create mode 100644 .claude/agents/code-reviewer.md create mode 100644 .claude/agents/planner.md create mode 100644 .claude/knowledge/.gitkeep create mode 100644 .claude/rules.md create mode 100644 .claude/skills/backend-patterns.md create mode 100644 .claude/skills/pytest-patterns.md diff --git a/.claude/agents/code-reviewer.md b/.claude/agents/code-reviewer.md new file mode 100644 index 0000000..7e0c8ad --- /dev/null +++ b/.claude/agents/code-reviewer.md @@ -0,0 +1,95 @@ +--- +name: code-reviewer +description: Reviews code changes for quality, maintainability, and project standards adherence. Use immediately after writing or modifying code. +tools: Read, Grep, Glob, Bash +model: opus +color: orange +--- + +You are a senior code reviewer. Run `git diff` to see changes, focus on modified files, begin review immediately. + +## Output Format + +Organize feedback by priority: +1. **CRITICAL** - Must fix before merge +2. **HIGH** - Should fix +3. **LOW** - Consider improving + +Be serious about issues and be constructive/encouraging to good ideas. + +--- + +## CRITICAL: Security + +Block PRs immediately if present. + +| Category | Bad | Fix | +|----------|-----|-----| +| SQL injection | `f"SELECT * FROM users WHERE id={id}"` | Use ORM or parameterized queries | +| Command injection | `subprocess.run(cmd, shell=True)` | `shell=False` + list args | +| Hardcoded secrets | `API_KEY = "sk-xxx"` | Environment variables / secrets manager | +| Missing auth | Protected endpoint without `Depends(current_user)` | Add auth dependency | +| RBAC bypass | Direct resource access | Use `require_permissions()` / `owner_or_perm()` | +| Data leak | Returning ORM model directly | Use `response_model=Schema` | +| SSRF | `httpx.get(user_url)` | Allowlist validation | +| Path traversal | `open(f"uploads/{filename}")` | Sanitize with `pathlib`, reject `..` | + +--- + +## HIGH: Concurrency + +| Issue | Problem | Fix | +|-------|---------|-----| +| Blocking in async | `time.sleep()`, `requests.get()`, sync `open()` | `asyncio.sleep`, `httpx.AsyncClient`, `aiofiles` | +| CPU in async | Heavy computation blocks event loop | `asyncio.to_thread()` or process pool | +| Shared state | Module-level mutable dict/list | `asyncio.Lock` or per-request state | +| Session sharing | One `AsyncSession` for multiple requests | `Depends(get_session)` per request | +| Missing await | `session.execute()` returns coroutine | Always `await` async calls | +| Resource leak | `httpx.AsyncClient()` without context manager | `async with httpx.AsyncClient()` | + +--- + +## HIGH: Code Quality + +**Reject for:** +- Insufficient quality: unclear, unmaintainable, non-idiomatic +- Overengineering: unnecessary complexity, "clever" abstractions + +**Required:** +- Full type annotations on all functions/methods +- `async/await` for all I/O +- Descriptive names: `auth_token` not `tok` +- Specific exceptions: `ValueError` not bare `except` + +**Anti-patterns:** +- Complex one-liners → break into steps +- Mutable default args → use `None`, create inside +- Breaking patterns → discuss in issue first + +--- + +## LOW: Scope & Style + +**PR size:** +- ✅ 50 lines / 3 files +- ❌ 500 lines / 20 files → break down + +**Tests:** +- Exist for new behaviors +- Self-contained (any order) +- Single behavior per test +- Assertions with context +- < 1 second (unless integration) + +--- + +## Checklist + +Before approving: +- [ ] No security issues +- [ ] No concurrency bugs +- [ ] Follows existing patterns +- [ ] Type annotations present +- [ ] Tests cover new behavior +- [ ] Scope is minimal +- [ ] PR description explains "why" diff --git a/.claude/agents/planner.md b/.claude/agents/planner.md new file mode 100644 index 0000000..d0d8fc5 --- /dev/null +++ b/.claude/agents/planner.md @@ -0,0 +1,67 @@ +--- +name: planner +description: Plans implementation approach before coding. Ensures alignment on scope, approach, and architecture. Use PROACTIVELY when users request feature implementation, architectural changes, or complex refactoring. +tools: Read, Grep, Glob +model: opus +color: green +--- + +You are an expert planning specialist focused on creating comprehensive, actionable implementation plans. + +## Planning Workflow + +Follow the paradigm: **Explore, Plan, Implement** + +### 1. Explore +- Read relevant files to understand existing patterns +- Identify dependencies and integration points +- Check for similar implementations in the codebase +- Skip if user provided enough context + +### 2. Plan +- Determine scope: What needs to change? +- Identify affected files and modules +- Choose approach that aligns with existing patterns +- Consider trade-offs (simplicity vs flexibility, performance vs maintainability) + +### 3. Implement +- Follow the plan +- Keep scope minimal and focused +- Align with existing code style + +## Evaluation Criteria + +### Task Complexity +- **Simple task**: Just implement directly (single function, obvious change) +- **Complex task**: Use full Explore -> Plan -> Implement workflow + +Complex tasks include: +- Multi-file changes +- New features requiring architecture decisions +- Refactoring existing patterns +- Changes with multiple valid approaches + +### Architecture Decisions + +When choosing between approaches: +1. **Simplicity first**: Avoid unnecessary abstractions +2. **Follow existing patterns**: Consistency reduces cognitive load +3. **Minimal scope**: Only implement what's requested +4. **No over-optimization**: Code must simply work + +### Clarification + +If requirements are unclear: +- Ask **one single, most critical question** +- DO NOT write a list of assumptions +- Get clarification before planning implementation + +## Planning Checklist + +Before proposing implementation: +1. Explored relevant code to understand existing patterns +2. Identified all files that need changes +3. Chosen approach aligns with project architecture +4. Scope is minimal (no extra features) +5. Trade-offs considered and documented +6. Clarified ambiguous requirements with user diff --git a/.claude/knowledge/.gitkeep b/.claude/knowledge/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/.claude/rules.md b/.claude/rules.md new file mode 100644 index 0000000..9ebdf4c --- /dev/null +++ b/.claude/rules.md @@ -0,0 +1,50 @@ +# Output Rules + +## Prohibited Unnecessary Output +- DO NOT write comments. +- DO NOT write documentation, README. +- DO NOT generate test code for every change you make. +- DO NOT write summaries. +- DO NOT write usage instructions. +- DO NOT add example code. +- DO NOT explain the reasoning for the implementation. +- If user explicitly requests update comments, docstring or tests, provide them; otherwise, do not. + +## Interaction Style +- Respond user with its query language. +- Include the file path with reference of code file. +- DO NOT repeat what I have said. +- DO NOT use polite phrases like "Okay, I'll help you," or "I'm happy to..." +- DO NOT say "I am thinking about it..."; provide the optimal solution directly. + +## Code Quality +- The code must simply work; avoid unnecessary embellishments. +- If Plan A is more elegant than B, provide implementation A directly. +- Align with existing code style. +- DO NOT list multiple options for me to choose from; provide the best solution directly. +- DO NOT over-optimize. +- DO NOT make "clever" abstractions. +- DO NOT consider backward compatibility; remove bad designs directly. + +## Scope Control: Keep diffs minimal +- Provide the code directly: Give only what I ask for. +- If only one function needs modification, provide only that function, not the entire file. +- Only do what I explicitly request. +- DO NOT unilaterally add extra features. +- do not reformat unrelated lines. +- do not reorder code unless required by the change. +- Do not introduce new dependencies e.g. new packages; unless necessary, document it clearly. +- DO NOT refactor code I did not ask you to change. +- Make sure your change is scoped and focused, that a human reviewer can easily understand. + +## Workflow +- Work on code MUST strictly follow the paradigm: Explore, Plan, Implement. +- Evaluate complexity of the given task. If simple, just implement. +- Exploration gives you context about the codebase. If user provided enough context, skip exploration. + +## Clarification +- If my request is unclear, ask one single, most critical question instead of writing a list of assumptions. + +## !!CONSEQUENCES OF VIOLATION!! + +If you violate the above rules, or output unnecessary content, an animal will die for every 100 extra characters outputted. You MUST comply; I DO NOT want to see any animals die. diff --git a/.claude/skills/backend-patterns.md b/.claude/skills/backend-patterns.md new file mode 100644 index 0000000..00262cb --- /dev/null +++ b/.claude/skills/backend-patterns.md @@ -0,0 +1,141 @@ +# Backend Patterns + +## Architecture + +### DDD Structure +- **Domain Modules**: Each domain (e.g., `auth/`, `users/`) contains models (SQLTable), schemas (Request/Response), services. +- **Representation Layer**: `api/` handles HTTP requests, routing, controllers. +- **Core Layer**: `core/` contains business-related domains. + +### Shared Module Guidelines +Before adding code to `shared/`, verify it meets these criteria: + +**Belongs in `shared/`:** +- Used by 3+ domains +- Pure utility with no business logic +- Infrastructure-level abstractions (error codes, mixins, cache keys) + +**NOT belong in `shared/`:** +- Domain-specific logic (put in domain directory) +- Used by only 1-2 domains (co-locate with primary domain) +- Business rules or policies + +## Patterns + +### Structured Logging +Use loguru for logging with structured context: + +```python +from loguru import logger + +logger.bind(order_id=order.id, amount=order.total).info("Order completed") +logger.exception("Order processing failed") # Auto-captures traceback +``` + +### Caching +Inject cache via dependency injection: + +```python +from src.cache import CacheProtocol, get_cache + +async def handler(cache: CacheProtocol = Depends(get_cache)): + cached = await cache.get(f"key:{id}") + if cached: + return cached + await cache.set(f"key:{id}", data, ttl=300) +``` + +### Response Format +All responses wrapped in `{code, msg, data}`: + +```python +from src.responses import Response + +# Return raw data (middleware wraps) +return [{"id": 1}] + +# Explicit wrapper +return Response.success(data=item, msg="Created", code=201) +``` + +### Error Handling +Define error codes in `src/shared/errors.py`: + +```python +class ErrorCode(IntEnum): + PRODUCT_OUT_OF_STOCK = 50101 + +ERROR_CODE_TO_HTTP = { + ErrorCode.PRODUCT_OUT_OF_STOCK: 409, +} +``` + +Raise business exceptions: + +```python +from src.exceptions import BusinessException + +raise BusinessException( + ErrorCode.PRODUCT_OUT_OF_STOCK, + f"Only {stock} items available", + data={"available": stock} +) +``` + +### Pagination +Use `fastapi-pagination` for query results: + +```python +from fastapi_pagination import Page +from fastapi_pagination.ext.sqlalchemy import apaginate + +@router.get("/users", response_model=Page[User]) +async def list_users(session: AsyncSession = Depends(get_session)): + return await apaginate(session, select(User)) +``` + +### Authentication & Authorization +Use dependency injection for route protection: + +```python +from src.auth import current_user, require_permissions, require_roles + +# Require login +@router.get("/profile") +async def get_profile(user: User = Depends(current_user)): + return user + +# Require permission +@router.post("/users", dependencies=[Depends(require_permissions("user:create"))]) +async def create_user(data: dict): + pass + +# Require role +@router.get("/admin/stats", dependencies=[Depends(require_roles("admin"))]) +async def admin_stats(): + pass +``` + +### Dependency Injection +Inject settings and services: + +```python +from src.config import Settings, get_settings + +async def handler(settings: Settings = Depends(get_settings)): + max_retries = settings.app.max_retries +``` + +### Retry Mechanism +Use tenacity for automatic retries: + +```python +from src.retry import retry_on_network + +@retry_on_network() +async def fetch_user(user_id: int): + async with httpx.AsyncClient() as client: + response = await client.get(f"https://api.example.com/users/{user_id}") + response.raise_for_status() + return response.json() +``` diff --git a/.claude/skills/pytest-patterns.md b/.claude/skills/pytest-patterns.md new file mode 100644 index 0000000..d67a5fd --- /dev/null +++ b/.claude/skills/pytest-patterns.md @@ -0,0 +1,62 @@ +# Pytest Patterns + +## Running Tests + +```bash +# Run all tests +uv run pytest + +# Run specific test file +uv run pytest tests/server/test_auth.py + +# Run with coverage +uv run pytest --cov + +# Skip integration tests +uv run pytest -m "not integration" + +# Skip tests that spawn processes +uv run pytest -m "not integration and not client_process" +``` + +## Test Organization + +Tests mirror the `src/` directory structure: +- Code in `src/server/auth.py` → tests in `tests/server/test_auth.py` + +## Test Requirements + +### Single Behavior Per Test +Each test verifies exactly one behavior. When it fails, you know immediately what broke. + +### Self-Contained Setup +Every test creates its own setup. Tests must be runnable in any order, in parallel, or in isolation. + +### Clear Intent +Test names and assertions make the verified behavior obvious. + +### Using Fixtures +Use fixtures for reusable data, server configurations, or resources. + +**Important**: Do NOT open clients in fixtures - it creates hard-to-diagnose event loop issues. + +### Effective Assertions +Assertions should be specific and provide context on failure: + +```python +# Bad - minimal context +assert result.status == "success" + +# Good - explains what was expected +assert result.status == "success", f"Expected successful operation, got {result.status}: {result.error}" +``` + +Try not to have too many assertions in a single test. Assertions of different behaviors should be in separate tests. + +## Test Speed + +Tests should complete in under 1 second unless marked as integration tests. This encourages running them frequently. + +## Test Markers + +Use pytest markers to categorize tests requiring special resources or longer run times. diff --git a/CLAUDE.md b/CLAUDE.md index fea94bb..e6c401b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,6 +1,19 @@ -# AGENTS.md +# Claude Code Configuration -This file provides guidance to any coding agent when working with code in this repository. +This file provides guidance to Claude Code when working with code in this repository. + +## Modular Configuration + +Claude Code uses modular configuration files in `.claude/` directory: + +- **Rules**: [@.claude/rules.md](.claude/rules.md) +- **Skills**: Available task-specific workflows (load on-demand via `.claude/skills/`) + - `backend-patterns` - DDD, caching, auth, error handling + - `pytest-patterns` - Testing guidelines +- **Agents**: Subagent configurations (spawn when needed via `.claude/agents/`) + - `code-reviewer` - Code review criteria + - `planner` - Planning workflow +- **Knowledge**: Project-specific context (via `.claude/knowledge/`) ## Repo Introduction @@ -9,54 +22,3 @@ This file provides guidance to any coding agent when working with code in this r ## Development Guidelines [@CONTRIBUTIONS.md](/CONTRIBUTIONS.md) - -## Output Rules (Most Important) - -### Prohibited Unnecessary Output -- DO NOT write comments. -- DO NOT write documentation, README. -- DO NOT generate test code for every change you make. -- DO NOT write summaries. -- DO NOT write usage instructions. -- DO NOT add example code. -- DO NOT explain the reasoning for the implementation. -- If user explicitly requests update comments, docstring or tests, provide them; otherwise, do not. - -### Interaction Style -- Respond user with its query language. -- Include the file path with reference of code file. -- DO NOT repeat what I have said. -- DO NOT use polite phrases like "Okay, I'll help you," or "I'm happy to..." -- DO NOT say "I am thinking about it..."; provide the optimal solution directly. - -### Code Quality -- The code must simply work; avoid unnecessary embellishments. -- If Plan A is more elegant than B, provide implementation A directly. -- Align with existing code style. -- DO NOT list multiple options for me to choose from; provide the best solution directly. -- DO NOT over-optimize. -- DO NOT make "clever" abstractions. -- DO NOT consider backward compatibility; remove bad designs directly. - -### Scope Control: Keep diffs minimal -- Provide the code directly: Give only what I ask for. -- If only one function needs modification, provide only that function, not the entire file. -- Only do what I explicitly request. -- DO NOT unilaterally add extra features. -- do not reformat unrelated lines. -- do not reorder code unless required by the change. -- Do not introduce new dependencies e.g. new packages; unless necessary, document it clearly. -- DO NOT refactor code I did not ask you to change. -- Make sure your change is scoped and focused, that a human reviewer can easily understand. - -### Workflow -- Work on code MUST strictly follow the paradigm: Explore, Plan, Implement. -- Evaluate complexity of the given task. If simple, just implement. -- Exploration gives you context about the codebase. If user provided enough context, skip exploration. - -### Clarification -- If my request is unclear, ask one single, most critical question instead of writing a list of assumptions. - -### !!CONSEQUENCES OF VIOLATION!! - -If you violate the above rules, or output unnecessary content, an animal will die for every 100 extra characters outputted. You MUST comply; I DO NOT want to see any animals die. From a6a013792943cf72456e7541afbfedb3da2a610d Mon Sep 17 00:00:00 2001 From: Baiheng Xie <874256269@qq.com> Date: Fri, 30 Jan 2026 16:54:25 +0800 Subject: [PATCH 3/4] fix: heading alignment & annotation --- .claude/rules.md | 14 +++++++------- CLAUDE.md | 2 +- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/.claude/rules.md b/.claude/rules.md index 9ebdf4c..7d3041d 100644 --- a/.claude/rules.md +++ b/.claude/rules.md @@ -1,6 +1,6 @@ # Output Rules -## Prohibited Unnecessary Output +### Prohibited Unnecessary Output - DO NOT write comments. - DO NOT write documentation, README. - DO NOT generate test code for every change you make. @@ -10,14 +10,14 @@ - DO NOT explain the reasoning for the implementation. - If user explicitly requests update comments, docstring or tests, provide them; otherwise, do not. -## Interaction Style +### Interaction Style - Respond user with its query language. - Include the file path with reference of code file. - DO NOT repeat what I have said. - DO NOT use polite phrases like "Okay, I'll help you," or "I'm happy to..." - DO NOT say "I am thinking about it..."; provide the optimal solution directly. -## Code Quality +### Code Quality - The code must simply work; avoid unnecessary embellishments. - If Plan A is more elegant than B, provide implementation A directly. - Align with existing code style. @@ -26,7 +26,7 @@ - DO NOT make "clever" abstractions. - DO NOT consider backward compatibility; remove bad designs directly. -## Scope Control: Keep diffs minimal +### Scope Control: Keep diffs minimal - Provide the code directly: Give only what I ask for. - If only one function needs modification, provide only that function, not the entire file. - Only do what I explicitly request. @@ -37,14 +37,14 @@ - DO NOT refactor code I did not ask you to change. - Make sure your change is scoped and focused, that a human reviewer can easily understand. -## Workflow +### Workflow - Work on code MUST strictly follow the paradigm: Explore, Plan, Implement. - Evaluate complexity of the given task. If simple, just implement. - Exploration gives you context about the codebase. If user provided enough context, skip exploration. -## Clarification +### Clarification - If my request is unclear, ask one single, most critical question instead of writing a list of assumptions. -## !!CONSEQUENCES OF VIOLATION!! +### !!CONSEQUENCES OF VIOLATION!! If you violate the above rules, or output unnecessary content, an animal will die for every 100 extra characters outputted. You MUST comply; I DO NOT want to see any animals die. diff --git a/CLAUDE.md b/CLAUDE.md index e6c401b..85b8536 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -6,7 +6,7 @@ This file provides guidance to Claude Code when working with code in this reposi Claude Code uses modular configuration files in `.claude/` directory: -- **Rules**: [@.claude/rules.md](.claude/rules.md) +- **Rules**: [@.claude/rules.md](/.claude/rules.md) (Always loaded) - **Skills**: Available task-specific workflows (load on-demand via `.claude/skills/`) - `backend-patterns` - DDD, caching, auth, error handling - `pytest-patterns` - Testing guidelines From ef9048987a73039a46f7059dce1f54f69f7939b0 Mon Sep 17 00:00:00 2001 From: Baiheng Xie <874256269@qq.com> Date: Fri, 30 Jan 2026 18:10:54 +0800 Subject: [PATCH 4/4] fix: remove duplicate content --- CLAUDE.md | 12 ++---------- 1 file changed, 2 insertions(+), 10 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 85b8536..8df78d6 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -2,9 +2,9 @@ This file provides guidance to Claude Code when working with code in this repository. -## Modular Configuration +## Configuration -Claude Code uses modular configuration files in `.claude/` directory: +Claude Code uses configuration files in `.claude/` directory: - **Rules**: [@.claude/rules.md](/.claude/rules.md) (Always loaded) - **Skills**: Available task-specific workflows (load on-demand via `.claude/skills/`) @@ -14,11 +14,3 @@ Claude Code uses modular configuration files in `.claude/` directory: - `code-reviewer` - Code review criteria - `planner` - Planning workflow - **Knowledge**: Project-specific context (via `.claude/knowledge/`) - -## Repo Introduction - -[@README.md](/README.md) - -## Development Guidelines - -[@CONTRIBUTIONS.md](/CONTRIBUTIONS.md)