CLAUDE.md 設計原則:プロジェクト憲法を構築する
優れた Claude Code プロジェクトを際立たせる 7 つの設計原則をマスターしましょう。CLAUDE.md は効果的な AI コラボレーションの基盤です。
CLAUDE.md は、Claude Code プロジェクトにおいて最も重要なファイルです。単なる設定ファイルではありません—これは Claude があなたのコードベースをどのように理解し、どのように作業するかを定義する憲法です。
適切に作成された CLAUDE.md は、Claude を汎用アシスタントから、あなたの基準を理解し、制約を尊重し、一貫した結果を生み出す専門チームメンバーへと変身させます。
このガイドでは、公式メモリシステムと、優れた CLAUDE.md ファイルを際立たせる 7 つの原則について説明します。
Claude Code のメモリシステムを理解する
4 層メモリ階層
公式 Claude Code ドキュメントによると、Claude Code は4 層メモリ階層を使用しており、より具体的な層がより一般的な層を上書きします:
┌─────────────────────────────────────────────────┐
│ Layer 1: Enterprise/Organization │
│ Location: /etc/claude-code/settings.json │
│ Scope: All users in organization │
│ Control: IT department │
│ Purpose: Security policies, MCP allowlists │
├─────────────────────────────────────────────────┤
│ Layer 2: User Global │
│ Location: ~/.claude/CLAUDE.md │
│ ~/.claude/settings.json │
│ Scope: All your projects │
│ Purpose: Personal preferences, global tools │
├─────────────────────────────────────────────────┤
│ Layer 3: Project │
│ Location: ./CLAUDE.md or ./.claude/CLAUDE.md │
│ ./.claude/settings.json │
│ Scope: Team-shared, version controlled │
│ Purpose: Project standards, conventions │
├─────────────────────────────────────────────────┤
│ Layer 4: Project Local │
│ Location: ./CLAUDE.local.md │
│ Scope: Personal only (gitignored) │
│ Purpose: Individual overrides │
└─────────────────────────────────────────────────┘
優先順位: Project Local > Project > User Global > Enterprise
各層が制御するもの
| 層 | CLAUDE.md | settings.json | 目的 |
|---|---|---|---|
| Enterprise | 組織ポリシー | MCP 許可リスト、ツール制限 | コンプライアンス |
| User Global | 個人スタイル | グローバル MCP、プラグイン | 好み |
| Project | チーム標準 | プロジェクト MCP、権限 | 一貫性 |
| Project Local | 個人オーバーライド | ローカルテスト | 柔軟性 |
設定ファイルの説明
CLAUDE.md - セッション開始時に Claude が読み取る自然言語の指示:
# Project Constitution
- All code must have tests
- Use TypeScript strict mode
- Follow existing patterns
settings.json - ツールと権限の構造化された設定:
{
"permissions": {
"allow": ["Read", "Write", "Edit", "Bash(npm:*)"],
"deny": ["Read(.env)"]
},
"enableAllProjectMcpServers": true,
"ignorePatterns": ["node_modules/**", ".git/**"]
}
パス固有設定によるモジュラールール
複雑なプロジェクトでは、.claude/rules/ ディレクトリを使用します(v2.0.20+):
your-project/
├── .claude/
│ ├── CLAUDE.md # Main constitution
│ ├── settings.json # Permissions, MCP
│ └── rules/
│ ├── code-style.md # Coding standards
│ ├── testing.md # Test requirements
│ ├── security.md # Security policies
│ └── api.md # API conventions
ルールは frontmatter を使用してパス固有にできます:
---
paths: src/api/**/*.ts
---
# API Development Rules
- All endpoints must validate inputs using Zod
- Use standardized error responses from src/lib/errors.ts
- Include OpenAPI documentation comments
これは、Claude が src/api/**/*.ts に一致するファイルで作業している場合にのみルールが適用されることを意味します。
7 つの設計原則
原則 1: 賢さより明確さ
明確で曖昧さのない指示を書きましょう。Claude は解釈なしに即座にあなたの意図を理解できるべきです。
こうしないでください:
# Code should be good
Write clean code. Follow best practices.
代わりにこうしてください:
# Code Standards
- Use TypeScript strict mode (no `any` types)
- Functions must have explicit return types
- Maximum function length: 50 lines
- Maximum file length: 300 lines
- Use early returns to reduce nesting
なぜ重要か: 曖昧な指示は一貫性のない結果につながります。「良いコード」は人によって異なる意味を持ちます。具体的な基準は再現可能な結果を生み出します。
原則 2: 権限の階層
設定を一般から具体へと階層化します。各層には明確な目的が必要です。
構造:
# CLAUDE.md
## Non-Negotiables (Cannot be overridden)
- All PRs require tests
- No credentials in code
- Security review for auth changes
## Project Defaults (Can be overridden per-task)
- Prefer functional programming style
- Use named exports over default exports
- Write documentation for public APIs
## Preferences (Suggestions, not requirements)
- Consider performance implications
- Prefer composition over inheritance
なぜ重要か: すべてのルールが同等ではありません。絶対的なもの(セキュリティ)もあれば、ガイドライン(スタイル)もあります。これを明示することで、Claude が重要なルールに違反することを防ぎながら、適切な場所で柔軟性を持たせることができます。
原則 3: 制限ではなく許可
Claude ができないことではなく、できることを定義します。常にブロックするのではなく、効率的な作業を可能にします。
こうしないでください:
# Restrictions
- Don't modify production files
- Don't run destructive commands
- Don't commit without asking
- Don't install packages without approval
代わりにこうしてください:
# Autonomous Operations (No confirmation needed)
- Read any file in the project
- Run tests and linting
- Create/modify files in src/ and tests/
- Install devDependencies
- Create local branches
# Requires Confirmation
- Modifying .env or config files
- Installing production dependencies
- Pushing to remote branches
- Deleting files
なぜ重要か: 制限的な CLAUDE.md は摩擦を生みます。Claude は常に許可を求め、フローを中断します。明確な境界を持つ許容的な CLAUDE.md は、重要なものを保護しながら自律的な作業を可能にします。
settings.json 権限構文
公式ドキュメントから:
{
"permissions": {
"allow": [
"Read",
"Write",
"Edit",
"Bash(npm run:*)",
"Bash(git:*)"
],
"deny": [
"Read(.env)",
"Read(secrets/**)"
]
}
}
パターン構文:
Bash(npm run:*)- すべての npm run コマンドを許可Bash(git:*)- すべての git コマンドを許可Read(.env)- .env ファイルの読み取りを拒否Read(secrets/**)- secrets/ 内のすべての読み取りを拒否
原則 4: コンテキストが王様
関連するコンテキストを前もって提供します。Claude が知っているほど、パフォーマンスが向上します。
含めるべき必須コンテキスト:
# Project Overview
A Next.js 14 e-commerce platform with:
- App Router architecture
- Prisma + PostgreSQL database
- Stripe for payments
- Resend for emails
# Directory Structure
src/
├── app/ # Next.js App Router pages
├── components/ # Shared React components
├── lib/ # Utility functions and configs
├── services/ # Business logic
└── types/ # TypeScript type definitions
# Key Files
- src/lib/db.ts - Database client (Prisma)
- src/lib/auth.ts - Authentication utilities (NextAuth)
- src/services/ - Domain-specific logic
# Commands
- npm run dev - Start development server (port 3000)
- npm test - Run tests (Vitest)
- npm run lint - Check code quality (ESLint)
- npm run build - Production build
詳細は他のファイルをインポート:
See @README.md for project overview.
See @docs/architecture.md for system design.
See @package.json for available scripts.
なぜ重要か: コンテキストは推測を排除します。Claude があなたの技術スタック、ファイル構造、規約を知っていると、プロジェクトに自然にフィットするコードを生成します。
原則 5: 実行可能な基準
すべてのガイドラインは実行可能であるべきです。Claude が直接適用できなければ、役に立ちません。
実行不可能:
- Write type-safe code
- Follow security best practices
- Make it performant
実行可能:
# Type Safety
- Enable TypeScript strict mode in tsconfig.json
- Never use `any` - use `unknown` and narrow with type guards
- Define interfaces for all API responses in src/types/
# Security
- Validate all user inputs using Zod schemas
- Sanitize data before database queries
- Use parameterized queries exclusively (Prisma handles this)
- Never log sensitive data (passwords, tokens, PII)
# Performance
- Lazy load components over 50KB using next/dynamic
- Use React.memo for components with expensive renders
- Add database indexes for queries taking >100ms
- Use React Server Components for data fetching
なぜ重要か: 「ベストプラクティス」は具体性がなければ意味がありません。実行可能な基準は、Claude が行うことができるコード決定に直接変換されます。
原則 6: 例外規定
ルールを破ることができる場合を定義します。厳格なルールはフラストレーションを引き起こします。明確な例外を持つ柔軟なルールは実用主義を可能にします。
# Testing Requirements
All features must have tests.
**Exceptions:**
- Prototypes and experiments (prefix with `_experimental`)
- One-time scripts in `scripts/`
- When explicitly told to skip tests
# Documentation Requirements
Public APIs must have JSDoc comments.
**Exceptions:**
- Internal utilities with obvious names
- Generated code
- Test files
なぜ重要か: 実際の開発には柔軟性が必要です。例外規定がなければ、自分自身のルールを常にオーバーライドすることになります。明示的な例外は暗黙的なルール違反よりも優れています。
原則 7: 生きたドキュメント
CLAUDE.md はプロジェクトとともに進化します。バージョン管理し、定期的にレビューし、何がうまくいくかに基づいて更新します。
# CLAUDE.md
Last updated: 2026-01-10
Version: 2.3
## Changelog
- 2.3: Added API error handling standards
- 2.2: Updated test coverage requirements (80% → 85%)
- 2.1: Added security review requirements for payment code
- 2.0: Major restructure for clarity
## Feedback
If these guidelines cause friction, document the issue
in `.claude/feedback.md` for review.
レビューのトリガー:
- 主要な機能を完了した後
- Claude が一貫して何かを誤解している場合
- チームメンバーが参加または離脱する場合
- 技術スタックが変更される場合
Agent 委任ルール
Claude が専門エージェントに委任するタイミングを定義します:
## Agent Delegation
### Automatic Triggers
- Files in auth/, payment/, admin/ → security-auditor
- New API endpoints → code-reviewer
- Performance-sensitive code → benchmark first
### Manual Triggers
- Complex refactoring → Parallel Explore agents
- Full codebase review → Multi-agent analysis
- Architecture decisions → Plan agent
### Agent Configuration
code-reviewer:
- Check for OWASP Top 10 vulnerabilities
- Verify error handling patterns
- Ensure consistent code style
security-auditor:
- Scan for hardcoded secrets
- Check authentication flows
- Verify input validation
Knowledge Graph Memory (MCP)
Claude Code は Memory MCP を通じて永続メモリをサポートしています:
# Add Memory MCP with project isolation
claude mcp add --scope project memory \
-e MEMORY_FILE_PATH=./.claude/memory.json \
-- npx -y @modelcontextprotocol/server-memory
重要: プロジェクト分離のために常に MEMORY_FILE_PATH を使用してください。これがないと、すべてのプロジェクトが同じメモリを共有します。
メモリコマンド:
/memory-save- 重要な決定を保存/memory-search- 保存された知識を検索/memory-list- すべてのエンティティをリスト/memory-audit- メモリの健全性をチェック
実用的なテンプレート
すべての原則を組み込んだ完全な CLAUDE.md テンプレートを以下に示します:
# Project Constitution
## Project Overview
[One paragraph describing what this project does]
## Tech Stack
- Framework: [e.g., Next.js 14, App Router]
- Language: [e.g., TypeScript 5.x, strict mode]
- Database: [e.g., PostgreSQL via Prisma]
- Testing: [e.g., Vitest + React Testing Library]
## Directory Structure
src/
├── app/ # [Purpose]
├── components/ # [Purpose]
├── lib/ # [Purpose]
└── services/ # [Purpose]
## Commands
- `npm run dev` - Start development
- `npm test` - Run tests
- `npm run lint` - Check code quality
## Code Standards
### TypeScript
- Strict mode enabled
- No `any` types (use `unknown`)
- Explicit return types on functions
### React
- Functional components only
- Use React Server Components by default
- Client components must be explicitly marked
### Testing
- All features require tests
- Minimum 80% coverage for new code
- Integration tests for API routes
## Autonomous Operations
Claude may freely:
- Read all project files
- Create/modify files in src/ and tests/
- Run tests and linting
- Create local git branches
## Requires Confirmation
- Installing production dependencies
- Modifying environment variables
- Pushing to remote
- Deleting files
## Agent Delegation
- Complex refactoring → Parallel Explore agents
- Security-sensitive changes → security-auditor
- API changes → code-reviewer
## Non-Negotiables
- All code must have tests
- No secrets in code
- Security review for auth/payment code
よくある間違い
間違い 1: 長すぎる
500 行の CLAUDE.md は目的を達成できません。スキャンしやすく保ちましょう。
修正: 詳細なガイドを .claude/rules/ に抽出してインポートします。
間違い 2: 曖昧すぎる
「良いコードを書く」は実行可能ではありません。
修正: すべてのガイドラインを具体的でチェック可能な要件に変換します。
間違い 3: 制限しすぎる
すべてに確認を要求すると摩擦が生じます。
修正: 本当にリスクのあるものを特定し、それ以外はすべて許可します。
間違い 4: 更新されない
古い CLAUDE.md は混乱を引き起こします。
修正: 月次レビューのリマインダーを設定します。主要な機能の後に更新します。
間違い 5: コピー&ペースト
他の人の CLAUDE.md を適応せずに使用する。
修正: テンプレートから始めますが、プロジェクト固有のニーズに合わせてカスタマイズします。
間違い 6: 層の階層を無視する
適切な層を使用する代わりに、すべてをプロジェクト CLAUDE.md に入れる。
修正: 個人的な好みは ~/.claude/CLAUDE.md に、プロジェクト標準はプロジェクト CLAUDE.md に、個別の調整は CLAUDE.local.md に。
はじめに
今日:
- プロジェクトで
/initを実行して基本的な CLAUDE.md を作成 - プロジェクト概要と技術スタックを追加
- 3-5 個の絶対的なルールを定義
今週:
- ディレクトリ構造とキーファイルを追加
- 自律的な操作と確認が必要な操作を定義
- 最も重要なコード標準を追加
今月:
- 実際の使用に基づいて改良
- エージェント委任ルールを追加
- 詳細なガイドを
.claude/rules/ディレクトリに抽出 - 永続的な知識のために Memory MCP をセットアップ
成功の測定
CLAUDE.md がうまく機能している場合:
- Claude が最初の試行であなたのスタイルに合ったコードを生成する
- 同じ間違いを二度修正する必要がほとんどない
- 新しいチームメンバーがより早くオンボーディングできる
- コードレビューでスタイルに関するコメントが少ない
CLAUDE.md に改善が必要な場合:
- Claude が明確化の質問を続ける
- 同じパターンを常に修正している
- セッション間で出力が一貫していない
- プロンプトでコンテキストを繰り返している
最高の CLAUDE.md ファイルは一日で書かれるものではありません—使用を通じて進化します。シンプルに始め、何がうまくいくかを観察し、反復しましょう。
出典: Claude Code Documentation, Claude Code GitHub, Memory MCP