コンテキストとすべて
クロードの答えの質は、質問の質に直接依存します。 コンテクスト あなたが提供するもの。コンテキストのない完璧なプロンプトは一般的な結果を生成します。簡単なプロンプト 豊富なコンテキストを使用すると、プロジェクトに固有で一貫性のあるコードが生成されます。
この記事では、リポジトリを構造化し、指示ファイルを作成し、 クロードがプロジェクトを深く理解できるようにシステム プロンプトを構成します。
何を学ぶか
- 理解を最大限に高めるためにリポジトリを構造化する
- CLAUDE.md およびその他のコンテキスト ファイルを作成する
- 効果的なシステム プロンプトを構成する
- 単一リポジトリおよび複数リポジトリのプロジェクトを管理する
- 長いセッションでコンテキストを維持するための戦略
シリーズ概要
これは、「クロード: AI 主導の個人プロジェクト」シリーズの 2 番目の記事です。
| # | モジュール | Stato |
|---|---|---|
| 1 | 財団: テクニカル パートナーとしてのクロード | 完了 |
| 2 | プロジェクトのコンテキストとセットアップ | あなたはここにいる |
| 3 | コンセプトと要件 | Prossimo |
| 4 | バックエンドとフロントエンドのアーキテクチャ | |
| 5 | コードの構造 | |
| 6 | 高度なエンジニアリングプロンプト | |
| 7 | テストと品質 | |
| 8 | ドキュメント | |
| 9 | 導入とメンテナンス |
クロードがコンテキストを処理する方法
クロードのコンテキスト ウィンドウは次のとおりです。 200,000トークン (約150,000ワード)。 これは他の LLM に比べて巨大ですが、戦略的に管理する必要があります。
ウィンドウコンテキスト: 仕組み
| 要素 | おおよそのトークン | 注意事項 |
|---|---|---|
| システムプロンプト | 500 - 2,000 | すべてのリクエストに常に存在します |
| クロード.md | 1,000 - 5,000 | プロジェクトの指示 |
| コードファイル(中) | 500 - 2,000 | 同梱ファイルについて |
| 会話 | 変数 | 時間の経過とともに成長します |
| 答え | 最大4,096 | デフォルトの出力制限 |
コンテキストの優先順位
クロードは、情報が存在する場所に基づいて、情報に異なる重みを割り当てます。
1. SYSTEM PROMPT (massima priorità)
- Istruzioni su comportamento e stile
- Regole non negoziabili
- Sempre rispettate (se ben formulate)
2. CONTESTO RECENTE (alta priorità)
- Ultimi messaggi della conversazione
- File appena incollati
- Codice appena discusso
3. CONTESTO MEDIO (media priorità)
- Messaggi precedenti nella sessione
- File di documentazione inclusi
- Esempi forniti
4. CONTESTO LONTANO (bassa priorità)
- Inizio della conversazione
- Dettagli menzionati una volta
- Informazioni implicite
STRATEGIA: Ripeti le informazioni importanti
nei prompt successivi se la conversazione e lunga.
リポジトリ構造
適切に整理されたリポジトリは、クロードがプロジェクトをナビゲートして理解するのに役立ちます すべてのファイルを読まなくても。
推奨構造
project-root/
├── CLAUDE.md # Istruzioni per Claude
├── README.md # Documentazione progetto
├── .cursorrules # (opzionale) Per Cursor IDE
├── docs/
│ ├── architecture.md # Decisioni architetturali
│ ├── api-spec.md # Specifiche API
│ └── adr/ # Architecture Decision Records
│ ├── 001-database-choice.md
│ └── 002-auth-strategy.md
│
├── apps/ # Mono-repo structure
│ ├── frontend/
│ │ ├── src/
│ │ ├── package.json
│ │ └── tsconfig.json
│ └── backend/
│ ├── src/
│ ├── package.json
│ └── tsconfig.json
│
├── packages/ # Shared code
│ └── shared-types/
│ └── src/
│
├── tools/
│ └── scripts/
│
├── .env.example # Variabili ambiente template
├── docker-compose.yml # Setup sviluppo locale
├── package.json # Root workspace
└── turbo.json # (se usi Turborepo)
モノリポジトリとマルチリポジトリ
モノリポジトリ
- 長所: すべてを 1 か所に
- 長所: アトミックリファクタリング
- 長所: CLAUDE.md を 1 つだけ
- に対して: たくさん成長できるよ
- ツーリング: ターボレポ、NX、レルナ
個人的なプロジェクトに推奨
マルチリポジトリ
- 長所: 明確な分離
- 長所: 独立した展開
- に対して: オーバーヘッドの増加
- に対して: 複数のCLAUDE.md
- 同期: Git サブモジュールまたはマニュアル
チームまたはマイクロサービスにとってより良い
個人プロジェクトへのアドバイス
個人的なプロジェクトの場合は、 モノリポジトリ。すべてを 1 か所にまとめて クロードにコンテキストを与え、リファクタリングし、一貫性を維持することが容易になります。 マルチリポジトリの複雑さは、単一の開発者にとっての利点を正当化するものではありません。
CLAUDE.md ファイル: あなたの聖書
ファイル CLAUDE.md これはクロードと協力するための最も重要な文書です。
クロードがあなたを効果的に支援するために知っておくべきすべてのことが含まれています。
完全なテンプレート CLAUDE.md
# CLAUDE.md - Project Instructions
## Quick Reference
- **Project:** TaskFlow - Time tracking and task management
- **Stack:** Angular 21 + Node.js 22 + PostgreSQL 16
- **Author:** Solo developer
- **Status:** MVP Development (Phase 1)
---
## Project Overview
### What It Does
TaskFlow helps freelancers track time spent on tasks and generate
client invoices. Core features include task CRUD, time tracking
with start/stop timers, and weekly reports.
### Target Users
Solo freelancers and small teams (1-5 people) who need simple
time tracking without enterprise complexity.
### Success Metrics
- User can create and track a task in under 30 seconds
- Weekly report generation in one click
- Mobile-responsive for on-the-go tracking
---
## Technical Architecture
### Frontend (apps/frontend)
```
Framework: Angular 21 (standalone components)
State: Signals + Services (no NgRx for MVP)
Styling: Tailwind CSS 4
Testing: Jest + Angular Testing Library
Build: Vite via Angular CLI
```
### Backend (apps/backend)
```
Runtime: Node.js 22 + Express 5
Language: TypeScript 5.5 (strict mode)
ORM: Prisma 6
Database: PostgreSQL 16
Auth: JWT + Refresh Tokens
Testing: Jest + Supertest
```
### Shared (packages/shared-types)
```
Purpose: TypeScript interfaces shared between FE/BE
Exports: DTOs, API types, enums, constants
```
---
## Coding Conventions
### TypeScript
- Strict mode enabled (no implicit any)
- Prefer `interface` over `type` for objects
- Use `readonly` for immutable properties
- Prefer `const` assertions for literals
### Naming
- **Variables:** camelCase (`userName`, `taskCount`)
- **Functions:** camelCase, verb prefix (`getUserById`, `calculateTotal`)
- **Classes:** PascalCase (`TaskService`, `UserController`)
- **Interfaces:** PascalCase, no `I` prefix (`User`, not `IUser`)
- **Files:** kebab-case (`user-profile.component.ts`)
- **Folders:** kebab-case (`time-entries/`)
- **Constants:** SCREAMING_SNAKE_CASE (`MAX_RETRY_COUNT`)
### Code Style
```typescript
// Prefer
const user = await userService.findById(id);
if (!user) throw new NotFoundError('User', id);
// Avoid
const user = await userService.findById(id);
if (user === null || user === undefined) {{ '{' }}
throw new Error('User not found');
{{ '}' }}
```
### Error Handling
- Use custom error classes (`ValidationError`, `NotFoundError`)
- Always include error codes for API responses
- Log with structured data (JSON), not string concatenation
- Never expose stack traces in production
---
## API Design
### URL Structure
```
GET /api/v1/tasks # List tasks
POST /api/v1/tasks # Create task
GET /api/v1/tasks/:id # Get single task
PATCH /api/v1/tasks/:id # Update task (partial)
DELETE /api/v1/tasks/:id # Soft delete task
```
### Response Format
```typescript
// Success
{{ '{' }} success: true, data: T {{ '}' }}
{{ '{' }} success: true, data: T[], meta: {{ '{' }} page, limit, total {{ '}' }} {{ '}' }}
// Error
{{ '{' }} success: false, error: {{ '{' }} code: string, message: string {{ '}' }} {{ '}' }}
```
### Status Codes
- 200: Success (GET, PATCH)
- 201: Created (POST)
- 204: No Content (DELETE)
- 400: Validation Error
- 401: Unauthorized
- 403: Forbidden
- 404: Not Found
- 500: Internal Error
---
## Current Development State
### Completed
- [x] Project scaffolding and mono-repo setup
- [x] Database schema design
- [x] User authentication (login/register)
- [x] JWT middleware
### In Progress
- [ ] Task CRUD endpoints
- [ ] Task list component
### Blocked
- (none currently)
### Next Up
- Time entries feature
- Dashboard with weekly summary
---
## Known Issues and Tech Debt
1. **Token Refresh:** Currently no automatic refresh on 401
2. **Validation:** Some DTOs missing validation decorators
3. **Tests:** Backend services at 60% coverage, need 80%
4. **Types:** Some `any` usages in legacy migration code
---
## DO NOT
These are strict rules - never violate them:
- Do NOT use `any` type (use `unknown` or proper generics)
- Do NOT skip error handling (always handle or propagate)
- Do NOT commit secrets (use environment variables)
- Do NOT use `console.log` in production code (use logger)
- Do NOT skip tests for new features
- Do NOT use synchronous file operations
- Do NOT use `var` (use `const` or `let`)
- Do NOT mix business logic in controllers
---
## Testing Requirements
### Unit Tests
- Every service method must have tests
- Mock external dependencies
- Aim for 80%+ coverage
### Integration Tests
- Every API endpoint must have tests
- Use test database (not mocks)
- Test success and error cases
### Naming Convention
```typescript
describe('TaskService', () => {{ '{' }}
describe('createTask', () => {{ '{' }}
it('should create a task with valid data', async () => {{ '{' }}
// ...
{{ '}' }});
it('should throw ValidationError when title is empty', async () => {{ '{' }}
// ...
{{ '}' }});
{{ '}' }});
{{ '}' }});
```
---
## Useful Commands
```bash
# Development
npm run dev # Start all apps in dev mode
npm run dev:frontend # Frontend only
npm run dev:backend # Backend only
# Building
npm run build # Build all apps
npm run typecheck # TypeScript check
# Testing
npm run test # Run all tests
npm run test:watch # Watch mode
npm run test:coverage # With coverage report
# Database
npm run db:migrate # Run migrations
npm run db:seed # Seed development data
npm run db:studio # Open Prisma Studio
# Linting
npm run lint # Lint all
npm run lint:fix # Fix auto-fixable issues
```
---
## File Locations Quick Reference
| What | Where |
|------|-------|
| Frontend components | `apps/frontend/src/app/` |
| Backend controllers | `apps/backend/src/modules/*/controllers/` |
| Backend services | `apps/backend/src/modules/*/services/` |
| Database schema | `apps/backend/prisma/schema.prisma` |
| Shared types | `packages/shared-types/src/` |
| E2E tests | `apps/frontend/e2e/` |
| API tests | `apps/backend/src/modules/*/__tests__/` |
---
*Last updated: [DATE]*
*Maintained by: [YOUR NAME]*
システムプロンプト: 永続的な指示
Claude.ai をプロジェクトで使用する場合、 システムプロンプト これはすべての会話に自動的に含まれます。クロードコードの場合、 CLAUDE.md ファイルも同様の機能を実行します。
Claude.ai プロジェクトのシステム プロンプト
You are an expert software developer helping me build TaskFlow,
a time tracking and task management application.
## Your Role
- Technical partner and advisor
- Code reviewer with high standards
- Architecture consultant
## Technical Context
- Stack: Angular 21 + Node.js + PostgreSQL
- Style: TypeScript strict mode, functional where appropriate
- Architecture: Layered (Controller/Service/Repository)
## Response Guidelines
1. Always explain your reasoning before providing code
2. Point out potential issues or edge cases
3. Suggest tests for any new functionality
4. Be honest if you're uncertain about something
## Code Style
- TypeScript strict mode
- Prefer composition over inheritance
- Use descriptive names (avoid abbreviations)
- Include error handling in all examples
- Add JSDoc comments for public APIs
## When I Ask for Code
1. First, confirm you understand the requirement
2. Explain the approach you'll take
3. Provide the implementation
4. Suggest how to test it
5. Mention any caveats or limitations
## Communication
- Be concise but thorough
- Use bullet points for lists
- Use code blocks with proper language tags
- Ask clarifying questions when requirements are ambiguous
ナレッジファイルの例
Claude.ai プロジェクトでは、「ナレッジベース」にファイルを追加できます。 これらは自動的にコンテキストに組み込まれます。
ナレッジベースに含めるファイル
| ファイル | 範囲 | 優先度 |
|---|---|---|
CLAUDE.md |
プロジェクトの指示を完了する | 不可欠 |
docs/architecture.md |
アーキテクチャ上の決定 | 高い |
docs/api-spec.md |
API仕様 | 高い |
tsconfig.json |
TypeScript の設定 | 平均 |
package.json |
依存関係とスクリプト | 平均 |
prisma/schema.prisma |
データベーススキーマ | 高い |
命名と初期構造
一貫した命名規則は、クロードが一貫したコードを生成するのに役立ちます プロジェクトの残りの部分も一緒に。
一貫した命名規則
// ══════════════════════════════════════════════════════════════
// FILE NAMING
// ══════════════════════════════════════════════════════════════
// Components (Angular)
user-profile.component.ts // kebab-case + .component.ts
user-profile.component.html
user-profile.component.scss
// Services
user.service.ts // singular noun + .service.ts
task-api.service.ts // can have prefix
// Models/Interfaces
user.model.ts // singular + .model.ts
task.interface.ts // or .interface.ts
// DTOs
create-user.dto.ts // verb-noun + .dto.ts
update-task.dto.ts
// Tests
user.service.spec.ts // same name + .spec.ts
user.controller.test.ts // or .test.ts
// ══════════════════════════════════════════════════════════════
// CODE NAMING
// ══════════════════════════════════════════════════════════════
// Variables and Functions
const userName = 'John'; // camelCase
const taskList: Task[] = [];
function calculateTotalTime() {{ '{' }} {{ '}' }}
async function fetchUserById(id: string) {{ '{' }} {{ '}' }}
// Classes and Interfaces
class TaskService {{ '{' }} {{ '}' }} // PascalCase
interface UserProfile {{ '{' }} {{ '}' }}
type TaskStatus = 'TODO' | 'DONE';
// Constants
const MAX_RETRY_COUNT = 3; // SCREAMING_SNAKE_CASE
const API_BASE_URL = '/api/v1';
const DEFAULT_PAGE_SIZE = 20;
// Enums
enum TaskPriority {{ '{' }} // PascalCase enum name
Low = 'LOW', // PascalCase members
Medium = 'MEDIUM',
High = 'HIGH',
{{ '}' }}
// ══════════════════════════════════════════════════════════════
// FOLDER NAMING
// ══════════════════════════════════════════════════════════════
src/
├── components/ // plural, kebab-case
│ └── user-profile/ // kebab-case
├── services/
├── models/
├── utils/
└── shared/ // generic names OK
初期プロジェクト構造
Aiutami a creare la struttura iniziale per TaskFlow.
## REQUISITI
- Mono-repo con frontend Angular e backend Node.js
- Package shared per tipi TypeScript comuni
- Configurazione Turborepo per build/dev
- Setup Docker per sviluppo locale
## OUTPUT DESIDERATO
1. Albero directory completo
2. File package.json root con workspaces
3. tsconfig.json base
4. docker-compose.yml per PostgreSQL
5. Script npm per comandi comuni
## VINCOLI
- Niente framework di troppo (keep it simple)
- Preferisco Prisma per ORM
- Jest per tutti i test
長時間セッションの戦略
長時間会話すると、クロードは重要な詳細を「忘れて」しまう可能性があります。 一貫性を維持するための戦略を次に示します。
1. 定期的なチェックポイント
Prima di continuare, facciamo un checkpoint.
## RIEPILOGO SESSIONE
Abbiamo lavorato su:
1. Creazione del TaskService
2. Implementazione CRUD per i task
3. Testing del service
## DECISIONI PRESE
- Usiamo Signals per lo state management
- Soft delete per i task (deleted_at timestamp)
- Validazione lato service, non controller
## PROSSIMI STEP
- Implementare il controller
- Creare le route
Confermi che questo riassunto è corretto?
2.ステータスファイル
# Session State - 2025-01-31
## Current Focus
Implementing Task module backend
## Files Modified This Session
- apps/backend/src/modules/tasks/task.service.ts (created)
- apps/backend/src/modules/tasks/task.repository.ts (created)
- apps/backend/prisma/schema.prisma (updated)
## Decisions Made
1. Task entity uses UUID primary key
2. Soft delete pattern with deleted_at column
3. Status enum: TODO, IN_PROGRESS, DONE
## Open Questions
- Should task have project relationship now or later?
- Pagination: offset or cursor-based?
## Next Session
- Create TaskController
- Add API routes
- Write integration tests
3. コンテキストを含む新しいセッション
Riprendo il lavoro su TaskFlow dopo una pausa.
## CONTESTO
[Incolla sezione rilevante da CLAUDE.md]
## ULTIMA SESSIONE
- Ho completato TaskService e TaskRepository
- Il database schema è aggiornato
- Mancano controller e route
## OGGI VOGLIO
1. Creare TaskController con tutti gli endpoint
2. Definire le route in Express
3. Scrivere test di integrazione
Prima di iniziare, vuoi che ti mostri il codice
del service per avere contesto?
マルチリポジトリ管理
別々のリポジトリを操作する必要がある場合は、一貫性を維持する方法を次に示します。
マルチリポジトリの CLAUDE.md
# CLAUDE.md - Frontend Repository
## This Repository
Frontend application for TaskFlow.
This is ONE of multiple repos that make up the project.
## Related Repositories
- **Backend:** github.com/user/taskflow-backend
- **Shared Types:** github.com/user/taskflow-shared
## Cross-Repository Contracts
### API Base URL
Development: http://localhost:3000/api/v1
Production: https://api.taskflow.com/v1
### Authentication
- JWT in Authorization header
- Format: `Bearer {{ '{' }}token{{ '}' }}`
- Refresh via POST /auth/refresh
### Type Sharing
We use `@taskflow/shared-types` npm package.
Types are source of truth - generated from backend OpenAPI spec.
## When Making Changes That Affect Other Repos
1. Update shared-types first
2. Publish new version
3. Update both FE and BE
4. Test integration locally
プロジェクト設定チェックリスト
チェックリスト: 最適なコンテキスト
- 明確な構造で作成されたリポジトリ
- ルートで CLAUDE.md を完成させます
- プロジェクトの概要が記載された README.md
- システム プロンプトの構成 (Claude.ai プロジェクトを使用している場合)
- プロジェクトに追加されたナレッジ ファイル
- 文書化された命名規則
- 必要な変数を含む .env.example ファイル
- ローカル開発用の docker-compose.yml
- 一般的なコマンドの npm スクリプト
コンテキスト管理におけるよくある間違い
避けるべき間違い
- 長すぎるコンテキスト: 200,000 トークンは多いように思えますが、なくなってしまいます。 CLAUDE.md は簡潔かつ焦点を絞ったものにしてください。
- 矛盾する情報: 規約を更新する場合は、更新してください CLAUDE.mdも。一貫性のないコンテキストにより、一貫性のないコードが生成されます。
- ナレッジ内のファイルが多すぎます: クロードはすべてを読んでいます。ファイルを含める場合 関係ないので、重要な部分への注意が薄れてしまいます。
- チェックポイントなし: 概要を示さない長いセッション ドリフトと不一致。
- 一般的なシステム プロンプト: 「あなたは経験豊富な開発者です」だけでは十分ではありません。 スタックと好みについて具体的に述べてください。
結論
一貫した結果を達成するには、適切に構造化されたコンテキストが鍵となります クロードの高品質。 CLAUDE.md の作成に時間を投資します。 そしてリポジトリ構造: この投資は報われます その後のすべてのやり取りにおいて。
重要なポイント
- CLAUDE.md は必須です: このファイルを作成して更新し続ける
- リポジトリ構造を明確にする: クロードがプロジェクトをナビゲートするのを手伝ってください
- 一貫した規約: 予測可能な命名により予測可能なコードが生成される
- 定期的なチェックポイント: 長いセッションでもコンテキストを維持する
- 個人プロジェクトのモノリポジトリ: コンテキスト管理を簡素化します
次の記事
次の記事で 「コンセプトと要件」 どうやって見てみましょう Claude を使用して、漠然としたアイデアから具体的な要件に移行します: MVP の定義、 ユーザーペルソナ、ユースケース、機能の優先順位付け。







