3.3 Path-Specific Rules for Conditional Convention Loading
Path-Specific Rules คืออะไร
Path-Specific Rules คือการกำหนดกฎ/conventions ที่ apply เฉพาะเมื่อ Claude ทำงานกับไฟล์ในบาง path — เช่น code ใน src/ ใช้กฎแบบหนึ่ง แต่ code ใน tests/ ใช้กฎอีกแบบ ทำให้ Claude ปรับ behavior ตาม context โดยอัตโนมัติ
Subdirectory CLAUDE.md
วิธีหลักคือใส่ CLAUDE.md ในแต่ละ directory:
project/
├── CLAUDE.md # Global project rules
├── src/
│ ├── CLAUDE.md # Source code conventions
│ ├── components/
│ │ └── CLAUDE.md # Component-specific rules
│ └── api/
│ └── CLAUDE.md # API-specific rules
└── tests/
└── CLAUDE.md # Testing conventions
src/CLAUDE.md
- Use TypeScript strict mode
- All functions must have JSDoc
- No `any` type — use `unknown` if needed
- Prefer composition over inheritance
tests/CLAUDE.md
- Use vitest for all tests
- Each test file matches source: src/foo.ts → tests/foo.test.ts
- Use `describe` + `it` pattern
- Mock external services, never hit real APIs
- `any` type is OK in tests for mocking
src/components/CLAUDE.md
- Use functional components only
- Props interface must be exported
- One component per file
- CSS modules for styling
Conditional Loading Behavior
Claude loads CLAUDE.md files based on which files it’s currently working with:
- Claude reads
src/api/handler.ts→ loads: Global +src/CLAUDE.md+src/api/CLAUDE.md - Claude reads
tests/handler.test.ts→ loads: Global +tests/CLAUDE.md - Claude reads both → loads all relevant CLAUDE.md files
Use Cases
- Language-specific rules —
rust/CLAUDE.mdvspython/CLAUDE.mdใน polyglot repo - Environment rules —
infra/CLAUDE.md(Terraform conventions) vsapp/CLAUDE.md - Safety rules —
migrations/CLAUDE.md(“always create backup before ALTER TABLE”)
Key Concepts
- Automatic loading — Claude detects which directories it’s touching and loads matching CLAUDE.md
- Additive — subdirectory rules ADD to parent rules, don’t replace
- Scope — rules only apply when Claude is working with files in that directory
- Performance — every CLAUDE.md file costs tokens, keep them concise
Exam Tips
- Subdirectory CLAUDE.md loads ONLY when Claude works with files in that directory
- Rules are additive/merge — ไม่ override parent CLAUDE.md
- ข้อสอบอาจให้ scenario: “Claude is editing src/api/route.ts” แล้วถามว่า CLAUDE.md ไหนบ้าง apply
- Keep CLAUDE.md concise — long files waste tokens every turn
- ใช้สำหรับ rules ที่ genuinely differ per directory — อย่า repeat global rules