
Docs Ai Prd
- 181 installs
- 73 repo stars
- Updated July 13, 2026
- vasilyu1983/ai-agents-public
Helps with ai & agent building tasks.
About
docs-ai-prd is a Claude Code skill for ai & agent building. It helps solo builders move faster with AI-assisted development.
- docs-ai-prd
- AI & Agent Building
- AI-coding skill
Docs Ai Prd by the numbers
- 181 all-time installs (skills.sh)
- +9 installs in the week ending Aug 5, 2026 (Skillselion tracking)
- Ranked #3,045 of 16,546 AI & Agent Building skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/vasilyu1983/ai-agents-public --skill docs-ai-prdAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 181 |
|---|---|
| repo stars | ★ 73 |
| Last updated | July 13, 2026 |
| Repository | vasilyu1983/ai-agents-public ↗ |
What it does
Helps with ai & agent building tasks.
Files
PRDs & Project Context
Create product requirements and project context that humans and coding assistants can execute effectively.
Two capabilities: 1. PRDs & Specs - Requirements, specs, stories, acceptance criteria 2. Project Context - Architecture, conventions, tribal knowledge (CLAUDE.md)
Modern Best Practices (Jan 2026): Context engineering (right info, right format, right time), decision-first docs, testable requirements with acceptance criteria, metrics with formula + timeframe + data source, cross-tool portability.
Workflow (Use This Order)
1. Pick the deliverable (PRD, AI PRD, tech spec, story map, CLAUDE.md). 2. Gather inputs (problem evidence, users, constraints, dependencies, risks). 3. Fill the template (write decisions first; keep requirements testable). 4. Validate with checklists (requirements, edge cases, security/compliance as needed). 5. Hand off with next actions (implementation plan, owners, open questions).
Docs Folder + LLM Iteration Option (Any Repo)
Use this when a repository has a docs/ folder with:
- research docs prepared for LLM consumption
- feature docs/specs generated by LLMs during implementation
Run this flow before finalizing PRDs/specs: 1. Classify each file by purpose (Tutorial, How-to, Reference, Explanation) to prevent mixed doc types. 2. Tag each non-canonical file with lifecycle metadata (status, owner, last_verified, integrates_into, delete_by). 3. Pick one canonical doc per feature/decision; merge duplicate drafts into it. 4. Convert long research notes into short evidence-backed claims in canonical docs; keep links/dates for external facts. 5. Maintain a compact canonical library for LLMs with root anchors: AGENTS.md (agent instructions) and README.md (human + AI entrypoint), then link deeper specs from docs/. 6. Delete integrated drafts by delete_by date; do not keep .archive/ mirrors in docs/ unless compliance explicitly requires retention.
Quick Reference
PRDs & Specs
| Task | Template |
|---|---|
| PRD creation | assets/prd/prd-template.md |
| Tech spec | assets/spec/tech-spec-template.md |
| Planning checklist | assets/planning/planning-checklist.md |
| Story mapping | assets/stories/story-mapping-template.md |
| Gherkin/BDD | assets/stories/gherkin-example-template.md |
| AI PRD | assets/prd/ai-prd-template.md |
Project Context (CLAUDE.md)
| Context Type | Template | Priority |
|---|---|---|
| Architecture | assets/architecture-context.md | Critical |
| Conventions | assets/conventions-context.md | High |
| Key Files | assets/key-files-context.md | Critical |
| Minimal Start | assets/minimal-claudemd.md | 5-min |
| Cross-Tool | assets/cross-tool-context.md | Multi-tool |
---
Decision Tree
User needs:
├─► AI-Assisted Coding?
│ ├─ Non-trivial (>3 files)? → Planning checklist + agentic session
│ └─ Simple (<3 files)? → Direct implementation
│
├─► Repo has a docs folder with LLM-generated research/feature docs?
│ └─ Use Docs Folder + LLM Iteration Option, then validate with qa-docs-coverage
│
├─► Project Onboarding?
│ ├─ New to codebase? → Generate CLAUDE.md
│ └─ Quick context? → Minimal CLAUDE.md
│
└─► Traditional PRD?
├─ Product requirements? → PRD template
├─ AI feature? → AI PRD template
└─ Acceptance criteria? → Gherkin/BDD---
Cross-Tool Context Files
| Tool | Location | Notes |
|---|---|---|
| Claude Code | CLAUDE.md, .claude/ | Auto-loaded |
| Cursor | .cursor/rules/ | Project rules |
| Copilot | .github/copilot-instructions.md | Workspace context |
| Generic | AGENTS.md | Tool-agnostic |
---
CLAUDE.md / AGENTS.md Guidance
- Start minimal: assets/minimal-claudemd.md
- Add only what’s needed: assets/architecture-context.md, assets/conventions-context.md, assets/key-files-context.md, assets/dependencies-context.md, assets/tribal-knowledge-context.md
- Keep it executable: commands must run; include no secrets; prefer file paths over pasted code
---
Do / Avoid
Do
- Start with executive summary (decision, users, scope, success)
- Define acceptance criteria in testable language
- Keep requirements unambiguous (must/should/may)
- Link to supporting docs instead of pasting
Avoid
- Vague requirements ("fast", "easy") without definitions
- Mixing draft notes and final requirements
- Metrics without measurement plan
- Docs with no owner or review cadence
- Dual-state wording that mixes live behavior, target behavior, and migration behavior in one statement
---
LLM Ambiguity Gate (Required for planning docs)
- Label every behavior as exactly one of:
Live now,Target, orTransition(with owner + end condition). - Label every metric as either
Reference signalorRelease blocker. - Define one canonical feature-gating contract per feature; all other docs must link to it instead of restating variants.
- Keep assumptions/open questions separate from final decisions.
- If conflicts exist across docs, mark one canonical source and add follow-up tasks to resolve mirrors.
---
Context Extraction
Use:
- references/architecture-extraction.md for components/data flows
- references/convention-mining.md for naming/patterns
- references/tribal-knowledge-recovery.md for git-history “why”
- references/docs-audit-commands.md for audit commands and tool fallbacks
---
Quality Checklist
PRD Quality
- [ ] Clear problem statement
- [ ] Measurable success criteria
- [ ] Unambiguous acceptance criteria
- [ ] Edge cases documented
- [ ] AI can execute without clarification
- [ ] Every behavior is labeled
Live now,Target, orTransition - [ ] Metrics are labeled
Reference signalorRelease blocker - [ ] Each feature-gating rule has one canonical source (no conflicting duplicates)
CLAUDE.md Quality
- [ ] Architecture reflects actual structure
- [ ] Key files exist at listed locations
- [ ] Conventions match actual patterns
- [ ] Commands actually work
- [ ] No sensitive information
---
Resources
| Resource | Purpose |
|---|---|
| references/agentic-coding-best-practices.md | AI coding patterns |
| references/requirements-checklists.md | PRD validation |
| references/traditional-prd-writing.md | Classic PRD format |
| references/architecture-extraction.md | Mining architecture |
| references/convention-mining.md | Extracting conventions |
| references/tribal-knowledge-recovery.md | Git history analysis |
| references/docs-audit-commands.md | Audit shell commands |
| references/stakeholder-alignment.md | Stakeholder buy-in, RACI, conflict resolution |
| references/acceptance-criteria-patterns.md | Testable ACs, BDD, edge case coverage |
| references/prd-review-facilitation.md | Running PRD reviews, feedback categorization |
| data/sources.json | Curated external sources |
Templates
| Category | Templates |
|---|---|
| PRDs | prd-template, ai-prd-template, tech-spec-template |
| Planning | planning-checklist, agentic-session-template |
| Stories | story-mapping-template, gherkin-example-template |
| Context | architecture, conventions, key-files, minimal-claudemd |
| Stack-specific | nodejs-context, python-context, react-context, go-context |
Related Skills
| Skill | Purpose |
|---|---|
| docs-codebase | README, API docs, ADRs |
| qa-docs-coverage | Documentation gaps |
| product-management | Product strategy |
| software-architecture-design | System design |
Fact-Checking
- Use web search/web fetch to verify current external facts, versions, pricing, deadlines, regulations, or platform behavior before final answers.
- Prefer primary sources; report source links and dates for volatile information.
- If web access is unavailable, state the limitation and mark guidance as unverified.
API Service CLAUDE.md Template
Language-agnostic template for backend API services. Customize for your stack.
---
# [Service Name] API
[One-line description of what this API does]
## Tech Stack
- **Language**: [TypeScript / Python / Go / Java / Rust]
- **Framework**: [Express / FastAPI / Gin / Spring Boot / Actix]
- **Database**: [PostgreSQL / MySQL / MongoDB] via [ORM/Driver]
- **Cache**: [Redis / Memcached / None]
- **Auth**: [JWT / OAuth2 / API Keys / Session]
- **API Style**: [REST / GraphQL / gRPC]
## API Overview
### Base URL
Production: https://api.example.com/v1 Staging: https://api-staging.example.com/v1 Local: http://localhost:3000/v1
### Authentication
Authorization: Bearer <jwt_token>
or
X-API-Key: <api_key>
### Rate Limits
| Tier | Requests/min | Burst |
|------|-------------|-------|
| Free | 60 | 10 |
| Pro | 600 | 100 |
| Enterprise | Custom | Custom |
## Architecture
[2-3 sentences describing the service design]
### Directory Structure
src/ ├── api/ # HTTP layer │ ├── routes/ # Route definitions │ ├── handlers/ # Request handlers │ ├── middleware/ # Auth, validation, logging │ └── validators/ # Request validation schemas ├── services/ # Business logic ├── repositories/ # Data access ├── models/ # Domain entities ├── dto/ # Request/response objects ├── errors/ # Custom error types ├── config/ # Configuration └── utils/ # Shared utilities
### Request Flow
┌─────────────────────────────────────────────────────────────────┐ │ HTTP Layer │ ├──────────┬──────────┬──────────┬──────────┬─────────────────────┤ │ Router │ Auth │ Validate │ Rate │ Handler │ │ │ Middleware│ Middleware│ Limiter │ │ └──────────┴──────────┴──────────┴──────────┴──────────┬──────────┘ │ ▼ ┌─────────────────────────────────────────────────────────────────┐ │ Service Layer │ │ (Business logic, orchestration) │ └──────────────────────────────────────────┬──────────────────────┘ │ ▼ ┌─────────────────────────────────────────────────────────────────┐ │ Repository Layer │ │ (Database, cache, external APIs) │ └─────────────────────────────────────────────────────────────────┘
## Key Endpoints
### Users
| Method | Endpoint | Description | Auth |
|--------|----------|-------------|------|
| GET | `/users` | List users (paginated) | API Key |
| GET | `/users/:id` | Get user by ID | API Key |
| POST | `/users` | Create user | Admin |
| PATCH | `/users/:id` | Update user | Owner/Admin |
| DELETE | `/users/:id` | Delete user | Admin |
### [Other Resource]
| Method | Endpoint | Description | Auth |
|--------|----------|-------------|------|
| ... | ... | ... | ... |
## Request/Response Patterns
### Success Response
{ "data": { "id": "123", "name": "Example" }, "meta": { "requestId": "req_abc123" } }
### Paginated Response
{ "data": [...], "meta": { "page": 1, "perPage": 20, "total": 100, "totalPages": 5 } }
### Error Response (RFC 7807)
{ "type": "https://api.example.com/errors/validation", "title": "Validation Error", "status": 400, "detail": "Email is required", "instance": "/users", "errors": [ { "field": "email", "message": "Email is required" } ] }
## Key Files
| Purpose | Location | Notes |
|---------|----------|-------|
| Entry point | `src/index.ts` | Server bootstrap |
| Routes | `src/api/routes/index.ts` | Route registration |
| Auth middleware | `src/api/middleware/auth.ts` | JWT/API key validation |
| Error handler | `src/api/middleware/error.ts` | Global error handling |
| Database client | `src/db/client.ts` | Connection pool |
| Config | `src/config/index.ts` | Environment loading |
| OpenAPI spec | `docs/openapi.yaml` | API documentation |
## Configuration
### Environment Variables
.env.example
NODE_ENV=development PORT=3000 DATABASE_URL=postgresql://user:pass@localhost:5432/db REDIS_URL=redis://localhost:6379 JWT_SECRET=your-jwt-secret JWT_EXPIRES_IN=7d API_KEY_SALT=your-salt LOG_LEVEL=debug CORS_ORIGIN=http://localhost:3001
## Commands
Development
npm run dev # Start with hot reload
Database
npm run db:migrate # Run migrations npm run db:seed # Seed test data npm run db:reset # Reset database
Testing
npm test # All tests npm run test:unit # Unit tests only npm run test:integration # Integration tests npm run test:e2e # End-to-end API tests
Documentation
npm run docs:generate # Generate OpenAPI from code npm run docs:serve # Serve Swagger UI
Quality
npm run lint # ESLint npm run typecheck # Type checking
## Important Context
### Technical Decisions
#### [Why REST over GraphQL]
**Context**: Public API for external developers
**Decision**: REST for simplicity and cacheability
**Trade-off**: More endpoints, but easier to understand and cache
#### [Why JWT over sessions]
**Context**: Stateless API for horizontal scaling
**Decision**: JWT with short expiry + refresh tokens
**Trade-off**: Can't revoke instantly, but enables stateless auth
### Known Gotchas
- **Pagination cursor**: Use cursor-based pagination for large datasets, not offset
- **N+1 queries**: Always eager-load related entities in list endpoints
- **Timeout handling**: Set request timeout at 30s, database timeout at 10s
- **Idempotency**: POST requests with `Idempotency-Key` header for payment-like operations
### Historical Context
- [Any API version migrations, breaking changes, or legacy endpoints]
## Error Codes
| Code | HTTP Status | Description | Action |
|------|-------------|-------------|--------|
| `AUTH_INVALID_TOKEN` | 401 | JWT invalid or expired | Refresh token |
| `AUTH_FORBIDDEN` | 403 | Insufficient permissions | Check role |
| `RESOURCE_NOT_FOUND` | 404 | Resource doesn't exist | Verify ID |
| `VALIDATION_ERROR` | 400 | Invalid request body | Check errors[] |
| `RATE_LIMITED` | 429 | Too many requests | Wait and retry |
| `INTERNAL_ERROR` | 500 | Server error | Contact support |
## Testing
### API Test Example
describe('POST /users', () => { it('creates user with valid input', async () => { const res = await request(app) .post('/v1/users') .set('Authorization', Bearer ${adminToken}) .send({ email: 'test@example.com', name: 'Test' });
expect(res.status).toBe(201); expect(res.body.data).toMatchObject({ email: 'test@example.com', name: 'Test', }); });
it('returns 400 for invalid email', async () => { const res = await request(app) .post('/v1/users') .set('Authorization', Bearer ${adminToken}) .send({ email: 'invalid', name: 'Test' });
expect(res.status).toBe(400); expect(res.body.errors).toContainEqual( expect.objectContaining({ field: 'email' }) ); }); });
## For AI Assistants
### When modifying this API:
- Update OpenAPI spec for any endpoint changes
- Add request validation for all inputs
- Include error handling with appropriate error codes
- Write integration tests for new endpoints
- Follow existing response format patterns
### Patterns to follow:
- Validate all input at API boundary
- Use transactions for multi-step operations
- Log all requests with correlation ID
- Return consistent error format
- Version breaking changes (v1 → v2)
### Avoid:
- Business logic in handlers (use services)
- Direct database queries in handlers (use repositories)
- Exposing internal IDs (use UUIDs publicly)
- Silent failures (always log and respond)
- Breaking changes without version bump---
Quick Start Commands
Run these to gather API context:
# Find all routes
grep -rn "router\.\|app\.\(get\|post\|put\|patch\|delete\)" --include="*.ts" --include="*.js" --include="*.py" --include="*.go"
# Find OpenAPI spec
find . -name "openapi*" -o -name "swagger*"
# Check for validation
grep -rn "validate\|schema\|zod\|yup\|joi" --include="*.ts" --include="*.js"
# Find middleware
find . -name "*middleware*" -type f
# Check auth
grep -rn "jwt\|bearer\|apikey\|auth" -i --include="*.ts" --include="*.js" --include="*.py"Architecture Context Template
Template for documenting system architecture in CLAUDE.md.
---
## Architecture
[2-3 sentences describing the overall system design approach]
### System Type
- [ ] Monolith
- [ ] Modular Monolith
- [ ] Microservices
- [ ] Serverless
- [ ] Event-driven
- [ ] Hybrid
### High-Level Structure
┌─────────────────────────────────────────┐ │ Presentation │ │ (routes, controllers, middleware) │ ├─────────────────────────────────────────┤ │ Business Logic │ │ (services, use cases) │ ├─────────────────────────────────────────┤ │ Data Access │ │ (repositories, models, ORM) │ ├─────────────────────────────────────────┤ │ Infrastructure │ │ (database, cache, external APIs) │ └─────────────────────────────────────────┘
### Directory Structure
src/ ├── api/ # HTTP handlers, routes ├── services/ # Business logic ├── repositories/ # Data access layer ├── models/ # Database entities, DTOs ├── utils/ # Shared utilities ├── config/ # Configuration └── types/ # Type definitions
### Key Components
| Component | Location | Responsibility |
|-----------|----------|----------------|
| API Layer | `src/api/` | HTTP handling, routing, validation |
| Services | `src/services/` | Business logic, orchestration |
| Repositories | `src/repositories/` | Data access, queries |
| Models | `src/models/` | Data structures, entities |
### Data Flow
Request → Router → Middleware (auth, validate) → Handler ↓ Service ↓ Repository ↓ Database ↓ Response ← Handler ← Service ← Repository ←────────┘
### External Integrations
| Service | Purpose | Location |
|---------|---------|----------|
| Database | [PostgreSQL/MySQL/MongoDB] | `src/db/` |
| Cache | [Redis/Memcached] | `src/cache/` |
| Queue | [RabbitMQ/SQS/BullMQ] | `src/queue/` |
| Auth | [Auth0/Cognito/Custom] | `src/auth/` |
### Architectural Patterns
- **Pattern 1**: [e.g., Repository Pattern for data access]
- **Pattern 2**: [e.g., Service Layer for business logic]
- **Pattern 3**: [e.g., Dependency Injection via container]---
Usage
1. Copy the template above 2. Remove checkboxes and fill in actual values 3. Adjust directory structure to match your project 4. Add/remove sections as needed
When to Use
- Setting up CLAUDE.md for a new project
- Documenting existing project architecture
- Onboarding AI assistants to understand system design
CLI Tool CLAUDE.md Template
Template for command-line applications and developer tools.
---
# [CLI Name]
[One-line description of what this CLI tool does]
## Tech Stack
- **Language**: [TypeScript / Go / Rust / Python]
- **CLI Framework**: [Commander.js / yargs / oclif / cobra / clap / click]
- **Config**: [cosmiconfig / dotenv / viper / figment]
- **Output**: [chalk / ora / inquirer / lipgloss / rich]
- **Testing**: [Vitest / go test / cargo test / pytest]
## Installation
npm global install
npm install -g [package-name]
Or run via npx
npx [package-name] [command]
Or build from source
git clone [repo] cd [repo] npm install && npm run build npm link
## Architecture
[2-3 sentences describing the CLI architecture]
### Directory Structure
src/ ├── cli.ts # Entry point, command registration ├── commands/ # Command implementations │ ├── init.ts │ ├── build.ts │ └── deploy.ts ├── lib/ # Shared utilities │ ├── config.ts # Configuration loading │ ├── logger.ts # Logging utilities │ └── api.ts # API client (if applicable) ├── prompts/ # Interactive prompts ├── assets/ # File templates └── types/ # Type definitions
### Command Structure
[cli-name] <command> [subcommand] [options] [arguments]
Examples: [cli-name] init # Initialize project [cli-name] build --prod # Build for production [cli-name] deploy staging # Deploy to staging
## Commands Reference
| Command | Description | Example |
|---------|-------------|---------|
| `init` | Initialize new project | `cli init --template basic` |
| `build` | Build project | `cli build --prod` |
| `deploy` | Deploy to environment | `cli deploy production` |
| `config` | Manage configuration | `cli config set key value` |
| `help` | Show help | `cli help [command]` |
### Command Options
Global options (available on all commands)
--verbose, -v # Verbose output --quiet, -q # Suppress output --config, -c # Config file path --help, -h # Show help
Command-specific options
init: --template, -t # Template to use --force, -f # Overwrite existing
build: --prod # Production build --watch, -w # Watch mode --output, -o # Output directory
deploy: --dry-run # Preview changes --force # Skip confirmations
## Configuration
### Config File Locations
Searched in order:
1. `.clirc` in current directory
2. `.clirc` in home directory
3. `cli.config.js` in current directory
4. Environment variables with `CLI_` prefix
### Config Schema
// cli.config.js export default { // Project settings projectName: 'my-project', outputDir: './dist',
// Environment environment: 'development',
// API settings (if applicable) apiUrl: 'https://api.example.com', apiKey: process.env.CLI_API_KEY,
// Feature flags features: { experimentalFeature: false, }, };
### Environment Variables
CLI_CONFIG_PATH=/path/to/config # Custom config location CLI_API_KEY=your-api-key # API authentication CLI_VERBOSE=true # Enable verbose output CLI_NO_COLOR=true # Disable colored output
## Conventions
### Exit Codes
| Code | Meaning |
|------|---------|
| 0 | Success |
| 1 | General error |
| 2 | Invalid arguments |
| 3 | Configuration error |
| 4 | Network error |
| 5 | Permission denied |
### Output Formatting
// Use structured output for programmatic use if (options.json) { console.log(JSON.stringify(result, null, 2)); } else { console.log(chalk.green('[check]'), 'Operation successful'); }
### Error Handling
// User-friendly errors throw new UserError('Config file not found', { suggestion: 'Run cli init to create one', code: 'CONFIG_NOT_FOUND', });
## Key Files
| Purpose | Location | Notes |
|---------|----------|-------|
| Entry point | `src/cli.ts` | Command registration |
| Config loader | `src/lib/config.ts` | cosmiconfig setup |
| Logger | `src/lib/logger.ts` | Chalk + ora |
| API client | `src/lib/api.ts` | HTTP requests |
| Types | `src/types/index.ts` | Shared types |
## Development
Development with watch
npm run dev
Build
npm run build
Test locally
npm link cli --help
Run tests
npm test
Release
npm version patch npm publish
## Testing
### Unit Tests
describe('init command', () => { it('creates project structure', async () => { await runCommand(['init', '--template', 'basic']); expect(fs.existsSync('package.json')).toBe(true); }); });
### Integration Tests
Test CLI end-to-end
./tests/integration/run.sh
## Important Context
### Known Gotchas
- **Windows paths**: Use `path.resolve()` for cross-platform
- **TTY detection**: Check `process.stdout.isTTY` for interactive features
- **Signal handling**: Handle SIGINT for cleanup on Ctrl+C
### Performance
- Lazy-load heavy dependencies
- Use streaming for large files
- Cache config parsing
## For AI Assistants
### When modifying:
- Follow existing command structure
- Add help text for new options
- Update README with new commands
- Add tests for new functionality
### Avoid:
- Synchronous file operations for large files
- Hard-coded paths (use config)
- Console.log (use logger)---
Discovery Commands
# Find commands
find src -name "*.ts" -path "*/commands/*"
# Check CLI framework
cat package.json | jq '.dependencies' | grep -E "commander|yargs|oclif|meow"
# Find options/flags
grep -r "option\|flag\|argument" --include="*.ts" src/Conventions Context Template
Template for documenting project conventions in CLAUDE.md.
---
## Conventions
### Naming Conventions
| Type | Convention | Example |
|------|------------|---------|
| Files | kebab-case | `user-service.ts` |
| Directories | kebab-case | `api-handlers/` |
| Classes | PascalCase | `UserService` |
| Functions | camelCase | `getUserById` |
| Variables | camelCase | `userName` |
| Constants | SCREAMING_SNAKE | `MAX_RETRY_COUNT` |
| Interfaces | PascalCase (I prefix optional) | `IUserRepository` or `UserRepository` |
| Types | PascalCase | `UserCreateInput` |
| Enums | PascalCase + SCREAMING values | `UserRole.ADMIN` |
| Database tables | snake_case | `user_accounts` |
| Database columns | snake_case | `created_at` |
| API endpoints | kebab-case | `/api/user-profiles` |
| Environment vars | SCREAMING_SNAKE | `DATABASE_URL` |
### File Organization
- One class/service per file
- Barrel exports via `index.ts` in each directory
- Tests co-located as `*.test.ts` or in `__tests__/` directory
- DTOs separate from entities
### Import Order
// 1. External libraries import { Injectable } from '@nestjs/common'; import { z } from 'zod';
// 2. Internal absolute imports import { PrismaService } from '@/db/prisma'; import { logger } from '@/utils/logger';
// 3. Relative imports import { UserDto } from './dto/user.dto'; import { validateUser } from './validators';
### Code Style
- [Formatter]: Prettier with default config
- [Linter]: ESLint with recommended rules
- [Type checking]: TypeScript strict mode
- Max line length: 100 characters
- Indentation: 2 spaces
- Quotes: Single quotes for JS/TS, double for JSX attributes
- Semicolons: [Yes/No]
- Trailing commas: ES5
### Error Handling
- Use custom error classes from `src/errors/`
- Always catch and wrap external service errors
- Include error codes for client-facing errors
- Log errors with context (userId, requestId)
### Logging
- Use structured logging (JSON format)
- Include correlation IDs in all logs
- Log levels: ERROR, WARN, INFO, DEBUG
- Never log sensitive data (passwords, tokens)
### Testing Conventions
- Test file naming: `*.test.ts` or `*.spec.ts`
- Describe blocks match class/function names
- Use descriptive test names: "should [action] when [condition]"
- Arrange-Act-Assert pattern
- Mock external dependencies
### Git Conventions
- Branch naming: `feature/`, `fix/`, `chore/`, `refactor/`
- Commit format: Conventional Commits (`feat:`, `fix:`, `docs:`)
- PR titles match commit format
- Squash merge to main---
Usage
1. Copy the template above 2. Adjust conventions to match your project 3. Remove sections that don't apply 4. Add project-specific conventions
Customization Tips
- Add language-specific conventions (Python, Go, Rust)
- Include framework-specific patterns (React, Django, Rails)
- Document team-specific conventions not in linter configs
Cross-Tool Context Template
Purpose: Unified project context template that works across multiple AI coding assistants (Claude Code, Cursor, Copilot, Windsurf, Cline).
---
Quick Setup
Copy this template to the appropriate location for your tool:
| Tool | Primary Location | Alternative |
|---|---|---|
| Claude Code | CLAUDE.md (repo root) | .claude/CLAUDE.md |
| Cursor | .cursor/rules/project.md | .cursorrules |
| Windsurf | .windsurf/rules/project.md | — |
| Copilot | .github/copilot-instructions.md | — |
| Cline | .cline/rules.md | .clinerules |
| Generic | AGENTS.md (repo root) | — |
---
Universal Context Template
# [Project Name]
Brief description of purpose and what this project does.
## Tech Stack
- Language: [e.g., TypeScript 5.x, Python 3.12]
- Framework: [e.g., Next.js 15, FastAPI]
- Database: [e.g., PostgreSQL 16, SQLite]
- Package Manager: [e.g., pnpm, uv]
## Architecture
### Key Directories
- `src/` - Main source code
- `src/api/` - API routes/handlers
- `src/services/` - Business logic
- `src/models/` - Data models/schemas
- `tests/` - Test files
### Data Flow
1. Request → API handler
2. Handler → Service → Database
3. Response ← Service ← Handler
## Conventions
### Naming
- Files: kebab-case (`user-service.ts`)
- Functions: camelCase (`getUserById`)
- Classes: PascalCase (`UserService`)
- Constants: SCREAMING_SNAKE (`MAX_RETRIES`)
### Patterns
- [Pattern 1, e.g., Repository pattern for data access]
- [Pattern 2, e.g., DTOs for API input/output]
## Key Files
| Purpose | Location | Notes |
|---------|----------|-------|
| Entry point | `src/index.ts` | Server bootstrap |
| Config | `src/config/index.ts` | Environment loading |
| Auth | `src/middleware/auth.ts` | JWT validation |
## Commands
Development
[package-manager] run dev
Testing
[package-manager] test
Build
[package-manager] run build
Lint
[package-manager] run lint
## Important Context
### Design Decisions
- [Decision 1 with rationale]
- [Decision 2 with rationale]
### Known Gotchas
- [Gotcha 1 - what to watch out for]
- [Gotcha 2 - non-obvious behavior]
## For AI Assistants
### When modifying code:
- Follow existing patterns in similar files
- Add tests for new functionality
- Run lint before committing
- Keep functions small and focused
### Avoid:
- Direct database queries outside repositories
- Console.log in production code (use logger)
- Hardcoded configuration values
- Breaking existing API contracts---
Tool-Specific Additions
Claude Code Specific
Add to CLAUDE.md:
## Claude Code Settings
### Preferred Tools
- Use Read over cat for file contents
- Use Grep over grep/rg for searching
- Use Edit over sed for modifications
### Session Patterns
- Use planning mode for >3 file changes
- Update this file after major refactors
- Log session discoveries in ## Recent ChangesCursor Specific
Add to .cursor/rules/project.md:
## Cursor Settings
### Composer Preferences
- Prefer atomic changes over large refactors
- Always show file diffs before applying
- Use @codebase for context when needed
### Agent Mode
- Enable for multi-file changes
- Disable for quick single-file editsCopilot Specific
Add to .github/copilot-instructions.md:
## Copilot Settings
### Workspace Context
- Reference package.json for dependencies
- Check tsconfig.json for TypeScript settings
- Review existing tests for patterns
### Code Style
- Match surrounding code style
- Use existing utility functions
- Follow established error patterns---
Multi-Tool Projects
For projects using multiple AI coding tools, create a shared AGENTS.md at repo root with common context, then tool-specific files for overrides:
repo/
├── AGENTS.md # Shared context (all tools read this)
├── CLAUDE.md # Claude-specific additions
├── .cursor/
│ └── rules/
│ └── project.md # Cursor-specific additions
├── .github/
│ └── copilot-instructions.md # Copilot-specific additions
└── ...In tool-specific files, reference shared context:
# Cursor Project Rules
See `AGENTS.md` for shared project context.
## Cursor-Specific Settings
[Cursor-only additions here]---
Context Sync Checklist
When updating project context:
- [ ] Update primary context file (CLAUDE.md or AGENTS.md)
- [ ] Sync key changes to tool-specific files
- [ ] Verify commands still work
- [ ] Check file paths are still valid
- [ ] Update tech stack versions if changed
- [ ] Add new design decisions or gotchas
---
Security Considerations
Do NOT include:
- API keys, secrets, or credentials
- Internal URLs or IP addresses
- Customer data or PII
- Security vulnerability details
- Production database connection strings
Safe to include:
- Public documentation URLs
- Open source dependency names
- General architecture patterns
- Coding conventions and style guides
---
Tip: Keep context files under 500 lines. Link to detailed docs rather than embedding everything. AI tools work better with focused, actionable context.
Dependencies Context Template
Template for documenting external services and integrations in CLAUDE.md.
---
## External Dependencies
### Databases
| Service | Purpose | Connection | Notes |
|---------|---------|------------|-------|
| PostgreSQL | Primary data store | `DATABASE_URL` | Managed via Prisma ORM |
| Redis | Cache, sessions | `REDIS_URL` | Used for rate limiting |
| MongoDB | Document storage | `MONGO_URL` | Legacy data |
### Message Queues
| Service | Purpose | Connection | Notes |
|---------|---------|------------|-------|
| RabbitMQ | Async messaging | `RABBITMQ_URL` | Email, notifications |
| SQS | Event processing | AWS credentials | Order processing |
| Kafka | Event streaming | `KAFKA_BROKERS` | Analytics events |
### Third-Party APIs
| Service | Purpose | Auth | Rate Limits | Notes |
|---------|---------|------|-------------|-------|
| Stripe | Payments | `STRIPE_SECRET_KEY` | 100/sec | Webhooks at `/webhooks/stripe` |
| SendGrid | Email | `SENDGRID_API_KEY` | 100/sec | Transactional only |
| Auth0 | Authentication | `AUTH0_*` | 1000/min | SSO enabled |
| S3 | File storage | AWS IAM | N/A | Presigned URLs |
| Twilio | SMS | `TWILIO_*` | 100/sec | 2FA only |
### Internal Services
| Service | Purpose | URL | Auth | Notes |
|---------|---------|-----|------|-------|
| User Service | User management | `USER_SERVICE_URL` | JWT | gRPC |
| Notification Service | Alerts | `NOTIF_SERVICE_URL` | API Key | REST |
| Analytics | Metrics | `ANALYTICS_URL` | None (internal) | Fire-and-forget |
### CI/CD & Infrastructure
| Service | Purpose | Notes |
|---------|---------|-------|
| GitHub Actions | CI/CD | Main branch auto-deploy |
| AWS ECS | Hosting | Production environment |
| Datadog | Monitoring | APM + logs |
| Sentry | Error tracking | All environments |
## Integration Patterns
### API Client Pattern
// src/clients/stripe.ts export const stripeClient = new Stripe(config.stripe.secretKey, { apiVersion: '2024-01-01', timeout: 10000, maxRetries: 3, });
### Retry Configuration
| Service | Retries | Backoff | Timeout |
|---------|---------|---------|---------|
| Stripe | 3 | Exponential | 10s |
| SendGrid | 2 | Linear | 5s |
| Internal APIs | 3 | Exponential | 30s |
### Circuit Breaker Settings
| Service | Failure Threshold | Reset Timeout |
|---------|-------------------|---------------|
| Payment APIs | 5 failures | 30 seconds |
| Email APIs | 10 failures | 60 seconds |
| Non-critical | 20 failures | 120 seconds |
## Environment Variables
Databases
DATABASE_URL=postgresql://user:pass@host:5432/db REDIS_URL=redis://localhost:6379
Third-party APIs
STRIPE_SECRET_KEY=sk_test_... STRIPE_WEBHOOK_SECRET=whsec_... SENDGRID_API_KEY=SG.... AUTH0_DOMAIN=tenant.auth0.com AUTH0_CLIENT_ID=... AUTH0_CLIENT_SECRET=...
AWS
AWS_REGION=us-east-1 AWS_ACCESS_KEY_ID=... AWS_SECRET_ACCESS_KEY=... S3_BUCKET=my-bucket
Internal services
USER_SERVICE_URL=http://user-service:3001 NOTIFICATION_SERVICE_URL=http://notif-service:3002
## Fallback Behavior
| Service | Fallback | Notes |
|---------|----------|-------|
| Redis cache | Skip cache, hit DB | Graceful degradation |
| Email service | Queue for retry | Async, non-blocking |
| Payment service | Fail request | Critical path |
| Analytics | Drop event | Non-critical |---
Discovery Commands
# Find external API calls
grep -r "fetch\|axios\|http\." --include="*.ts" | head -30
# Find environment variables
grep -r "process\.env\." --include="*.ts" | sort -u
# Find SDK/client instantiations
grep -r "new.*Client\|createClient\|initialize" --include="*.ts"
# Check package.json for SDK dependencies
cat package.json | jq '.dependencies' | grep -i "aws\|stripe\|sendgrid\|twilio"Usage
1. Inventory all external services 2. Document connection details (without secrets) 3. Note rate limits and quirks 4. Define fallback behaviors
Go CLAUDE.md Template
Copy and customize for Go projects.
---
# [Project Name]
[One-line description of what this project does]
## Tech Stack
- **Go**: [1.21 / 1.22]
- **Framework**: [Standard library / Gin / Echo / Chi / Fiber]
- **Database**: [PostgreSQL / MySQL / SQLite] via [sqlx / pgx / GORM / ent]
- **Cache**: [Redis / go-cache / BigCache]
- **Message Queue**: [RabbitMQ / NATS / Kafka]
- **Testing**: [testify / gomock / mockery]
## Architecture
[2-3 sentences describing the overall design approach]
### Directory Structure
. ├── cmd/ # Application entry points │ └── server/ │ └── main.go # Main entry point ├── internal/ # Private application code │ ├── api/ # HTTP handlers │ │ ├── handlers/ # Request handlers │ │ ├── middleware/ # HTTP middleware │ │ └── routes.go # Route definitions │ ├── service/ # Business logic │ ├── repository/ # Data access layer │ ├── model/ # Domain models │ ├── dto/ # Data transfer objects │ └── config/ # Configuration ├── pkg/ # Public reusable packages │ ├── logger/ # Logging utilities │ └── validator/ # Validation helpers ├── migrations/ # Database migrations ├── scripts/ # Build/deploy scripts ├── docs/ # Documentation ├── go.mod ├── go.sum └── Makefile
### Key Patterns
- **Clean Architecture**: `handler → service → repository` layering
- **Dependency Injection**: Constructor injection, no frameworks
- **Interface-based**: Define interfaces where used, not implemented
- **Context propagation**: `context.Context` passed through all layers
### Data Flow
HTTP Request → Middleware → Handler → Service → Repository → Database ↓ HTTP Response ← Handler ← Service ← Repository ←──────────┘
## Conventions
### Naming
| Type | Convention | Example |
|------|------------|---------|
| Packages | lowercase, short | `user`, `auth` |
| Files | snake_case | `user_service.go` |
| Exported | PascalCase | `UserService`, `GetUser` |
| Unexported | camelCase | `userRepo`, `getByID` |
| Constants | PascalCase or SCREAMING_SNAKE | `MaxRetries`, `MAX_RETRIES` |
| Interfaces | -er suffix (single method) | `Reader`, `UserRepository` |
| Test files | `_test.go` suffix | `user_service_test.go` |
### File Organization
// Order within a file: // 1. Package declaration // 2. Imports (stdlib, external, internal - goimports handles this) // 3. Constants // 4. Types (structs, interfaces) // 5. Constructor functions (New*) // 6. Methods (grouped by receiver) // 7. Helper functions
### Interface Definition
// Define interfaces where used, not where implemented // Keep interfaces small (1-3 methods)
// In service/user.go type userRepository interface { GetByID(ctx context.Context, id int64) (model.User, error) Create(ctx context.Context, user model.User) error }
type UserService struct { repo userRepository }
### Error Handling
// Always handle errors explicitly // Wrap errors with context if err != nil { return fmt.Errorf("failed to get user %d: %w", id, err) }
// Define domain errors var ( ErrUserNotFound = errors.New("user not found") ErrDuplicateEmail = errors.New("email already exists") )
## Key Files
| Purpose | Location | Notes |
|---------|----------|-------|
| Entry point | `cmd/server/main.go` | Server bootstrap |
| Routes | `internal/api/routes.go` | Route registration |
| Config | `internal/config/config.go` | Configuration struct |
| Models | `internal/model/` | Domain entities |
| Handlers | `internal/api/handlers/` | HTTP handlers |
| Services | `internal/service/` | Business logic |
| Repositories | `internal/repository/` | Database access |
## Configuration
### Environment Variables
.env
ENV=development PORT=8080 DATABASE_URL=postgres://user:pass@localhost:5432/db?sslmode=disable REDIS_URL=redis://localhost:6379 JWT_SECRET=your-secret-key LOG_LEVEL=debug
### Config Struct Pattern
// internal/config/config.go type Config struct { Env string env:"ENV" envDefault:"development" Port int env:"PORT" envDefault:"8080" DatabaseURL string env:"DATABASE_URL,required" JWTSecret string env:"JWT_SECRET,required" }
func Load() (*Config, error) { var cfg Config if err := env.Parse(&cfg); err != nil { return nil, err } return &cfg, nil }
## Commands
Development
make run # Run with hot reload (air) go run ./cmd/server # Run directly
Build
make build # Build binary go build -o bin/server ./cmd/server
Database
make migrate-up # Run migrations make migrate-down # Rollback migration make migrate-create name=add_users # Create migration
Testing
make test # Run all tests go test ./... # Run all tests go test -v ./internal/... # Verbose go test -cover ./... # With coverage go test -race ./... # Race detection make test-integration # Integration tests
Quality
make lint # golangci-lint go fmt ./... # Format code go vet ./... # Static analysis make generate # go generate ./...
## Important Context
### Technical Decisions
#### [Why Chi over Gin]
**Context**: Need lightweight HTTP router
**Decision**: Chi for stdlib compatibility and middleware chaining
**Trade-off**: Less batteries-included than Gin, but more idiomatic
#### [Why sqlx over GORM]
**Context**: Complex queries needed
**Decision**: sqlx for raw SQL with struct scanning
**Trade-off**: More boilerplate, but full control over queries
### Known Gotchas
- **nil slices vs empty slices**: `var s []int` (nil) vs `s := []int{}` (empty) - different JSON encoding
- **goroutine leaks**: Always handle context cancellation, use `errgroup`
- **defer in loops**: Deferred calls stack up, move to function
- **interface nil check**: Interface with nil concrete value is not nil
- **time.Time zero value**: Use `time.IsZero()`, not `== time.Time{}`
### Historical Context
- [Any migrations, refactors, or legacy patterns to know about]
## Testing
### Test Structure
// internal/service/user_test.go func TestUserService_GetByID(t testing.T) { tests := []struct { name string id int64 want model.User wantErr error }{ { name: "existing user", id: 1, want: &model.User{ID: 1, Name: "Alice"}, }, { name: "not found", id: 999, wantErr: ErrUserNotFound, }, }
for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { // Arrange repo := &mockUserRepo{} svc := NewUserService(repo)
// Act got, err := svc.GetByID(context.Background(), tt.id)
// Assert if tt.wantErr != nil { require.ErrorIs(t, err, tt.wantErr) return } require.NoError(t, err) assert.Equal(t, tt.want, got) }) } }
### Mocking
// Use mockery or manual mocks // internal/service/mock_test.go type mockUserRepo struct { mock.Mock }
func (m mockUserRepo) GetByID(ctx context.Context, id int64) (model.User, error) { args := m.Called(ctx, id) if args.Get(0) == nil { return nil, args.Error(1) } return args.Get(0).(*model.User), args.Error(1) }
## For AI Assistants
### When modifying this codebase:
- Follow existing patterns in similar files
- Add tests for new functionality
- Handle all errors explicitly
- Propagate context.Context through all functions
- Run `make lint && make test` before committing
### Patterns to follow:
- Constructor injection for dependencies
- Table-driven tests
- Wrap errors with context (`fmt.Errorf("...: %w", err)`)
- Small interfaces defined where used
- `internal/` for private packages
### Avoid:
- Global state and init() functions
- Naked returns (always name return values if using)
- Panic for expected errors
- Deep package nesting
- Circular dependencies between packages---
Quick Start Commands
Run these to gather context for a new Go project:
# Basic structure
tree -L 3 -I 'vendor|.git'
# Module info
cat go.mod | head -20
# Entry points
find . -name "main.go" -type f
# Find services/handlers
find . -name "*service*.go" -o -name "*handler*.go" | grep -v test
# Check for framework
grep -l "gin-gonic\|echo\|chi\|fiber" go.mod
# Database driver
grep -E "pgx|sqlx|gorm|ent" go.modKey Files Context Template
Template for documenting important files in CLAUDE.md.
---
## Key Files
### Entry Points
| Purpose | Location | Notes |
|---------|----------|-------|
| Main entry | `src/index.ts` | Server bootstrap, starts HTTP server |
| App setup | `src/app.ts` | Express/Fastify app configuration |
| CLI entry | `src/cli.ts` | Command-line interface entry |
### Configuration
| Purpose | Location | Notes |
|---------|----------|-------|
| Environment | `.env.example` | Template for environment variables |
| App config | `src/config/index.ts` | Validated configuration loading |
| TypeScript | `tsconfig.json` | Compiler options |
| ESLint | `.eslintrc.js` | Linting rules |
| Prettier | `.prettierrc` | Formatting rules |
### Database
| Purpose | Location | Notes |
|---------|----------|-------|
| Schema | `prisma/schema.prisma` | Database schema definition |
| Migrations | `prisma/migrations/` | Migration history |
| Seed data | `prisma/seed.ts` | Initial/test data |
| DB client | `src/db/client.ts` | Database connection instance |
### API Layer
| Purpose | Location | Notes |
|---------|----------|-------|
| Routes | `src/api/routes/index.ts` | All route definitions |
| Middleware | `src/middleware/` | Auth, validation, error handling |
| Controllers | `src/api/handlers/` | Request handlers |
### Business Logic
| Purpose | Location | Notes |
|---------|----------|-------|
| Services | `src/services/` | Core business logic |
| Repositories | `src/repositories/` | Data access layer |
| Domain models | `src/domain/` | Business entities |
### Types & Interfaces
| Purpose | Location | Notes |
|---------|----------|-------|
| API types | `src/types/api.ts` | Request/response types |
| Domain types | `src/types/domain.ts` | Business entity types |
| Config types | `src/types/config.ts` | Configuration types |
| Shared types | `src/types/index.ts` | Re-exported types |
### Testing
| Purpose | Location | Notes |
|---------|----------|-------|
| Test setup | `src/test/setup.ts` | Jest/Vitest configuration |
| Fixtures | `src/test/fixtures/` | Test data |
| Mocks | `src/test/mocks/` | Mock implementations |
| E2E tests | `tests/e2e/` | End-to-end tests |
### DevOps
| Purpose | Location | Notes |
|---------|----------|-------|
| Dockerfile | `Dockerfile` | Container build |
| Docker Compose | `docker-compose.yml` | Local development |
| CI/CD | `.github/workflows/` | GitHub Actions |
| K8s manifests | `k8s/` | Kubernetes deployment |
### Documentation
| Purpose | Location | Notes |
|---------|----------|-------|
| README | `README.md` | Project overview |
| API docs | `docs/api/` | API documentation |
| ADRs | `docs/adr/` | Architecture decisions |
| CLAUDE.md | `CLAUDE.md` | AI context |---
Discovery Commands
Find key files in a new codebase:
# Entry points
find . -name "index.*" -o -name "main.*" -o -name "app.*" -o -name "server.*" | head -20
# Configuration files
find . -name "*.config.*" -o -name "config.*" -o -name ".env*" | grep -v node_modules
# Package/dependency files
ls package.json requirements.txt Cargo.toml go.mod pom.xml 2>/dev/null
# Database/ORM files
find . -name "schema.prisma" -o -name "*.entity.ts" -o -name "models.py" | head -20
# Route definitions
grep -r "router\.\|app\.get\|app\.post\|@Get\|@Post" --include="*.ts" -l | head -10
# Test configuration
find . -name "jest.config.*" -o -name "vitest.config.*" -o -name "pytest.ini" 2>/dev/nullUsage
1. Copy the relevant sections 2. Fill in actual file paths 3. Add notes about non-obvious locations 4. Remove sections that don't apply
Library/Package CLAUDE.md Template
Template for reusable libraries and npm/pip/crate packages.
---
# [Library Name]
[One-line description of what this library does]
## Overview
- **Type**: [npm package / pip package / cargo crate / go module]
- **Language**: [TypeScript / JavaScript / Python / Rust / Go]
- **Target**: [Browser / Node.js / Both / Universal]
- **Bundler**: [Rollup / esbuild / tsup / Vite / None]
- **Testing**: [Vitest / Jest / pytest / cargo test]
## Installation
npm
npm install [package-name]
yarn
yarn add [package-name]
pnpm
pnpm add [package-name]
## Quick Start
import { mainFunction } from '[package-name]';
// Basic usage const result = mainFunction(input);
// With options const result = mainFunction(input, { option1: true, option2: 'value', });
## Architecture
### Directory Structure
src/ ├── index.ts # Main entry, public exports ├── core/ # Core functionality │ ├── main.ts # Main function │ └── utils.ts # Internal utilities ├── types/ # Type definitions │ ├── index.ts # Public types │ └── internal.ts # Internal types └── __tests__/ # Tests └── main.test.ts
Build outputs
dist/ ├── index.js # CommonJS ├── index.mjs # ESM ├── index.d.ts # Type declarations └── index.min.js # Minified (browser)
### Module Exports
// package.json exports { "exports": { ".": { "types": "./dist/index.d.ts", "import": "./dist/index.mjs", "require": "./dist/index.js" }, "./utils": { "types": "./dist/utils.d.ts", "import": "./dist/utils.mjs", "require": "./dist/utils.js" } } }
## Public API
### Main Exports
// Functions export function mainFunction(input: Input, options?: Options): Output; export function helperFunction(data: Data): Result;
// Classes export class MainClass { constructor(config: Config); method1(): void; method2(arg: string): Promise<Result>; }
// Types export type Input = { ... }; export type Output = { ... }; export type Options = { ... };
// Constants export const VERSION: string; export const DEFAULT_OPTIONS: Options;
### Type Definitions
// src/types/index.ts export interface Options { /* Enable verbose logging / verbose?: boolean; /* Timeout in milliseconds / timeout?: number; /* Custom handler function / onEvent?: (event: Event) => void; }
export interface Result { success: boolean; data?: unknown; error?: Error; }
## Conventions
### Code Style
- Pure functions where possible
- No side effects in core logic
- Explicit return types on public API
- JSDoc comments on all exports
### Naming
| Type | Convention | Example |
|------|------------|---------|
| Public functions | camelCase | `parseConfig` |
| Internal functions | _camelCase | `_validateInput` |
| Types/Interfaces | PascalCase | `ConfigOptions` |
| Constants | SCREAMING_SNAKE | `DEFAULT_TIMEOUT` |
### Error Handling
// Custom error class export class LibraryError extends Error { constructor( message: string, public code: string, public cause?: Error ) { super(message); this.name = 'LibraryError'; } }
// Usage throw new LibraryError( 'Invalid configuration', 'INVALID_CONFIG', originalError );
## Key Files
| Purpose | Location | Notes |
|---------|----------|-------|
| Entry point | `src/index.ts` | All public exports |
| Types | `src/types/index.ts` | Public type definitions |
| Core logic | `src/core/` | Main functionality |
| Build config | `tsup.config.ts` | Build configuration |
| Package config | `package.json` | npm metadata, exports |
## Development
Install dependencies
npm install
Development (watch mode)
npm run dev
Build
npm run build
Test
npm test npm run test:watch npm run test:coverage
Lint & Format
npm run lint npm run format
Type check
npm run typecheck
Release
npm run release # Bumps version, builds, publishes
## Testing
### Test Structure
// src/__tests__/main.test.ts import { mainFunction } from '../index';
describe('mainFunction', () => { it('handles basic input', () => { const result = mainFunction({ key: 'value' }); expect(result.success).toBe(true); });
it('throws on invalid input', () => { expect(() => mainFunction(null as any)).toThrow(LibraryError); });
it('respects options', () => { const result = mainFunction(input, { timeout: 5000 }); expect(result.timeout).toBe(5000); }); });
### Coverage Requirements
- Statements: > 90%
- Branches: > 85%
- Functions: > 90%
- Lines: > 90%
## Publishing
### Pre-publish Checklist
- [ ] All tests pass
- [ ] Types are correct
- [ ] CHANGELOG updated
- [ ] Version bumped
- [ ] README updated
- [ ] Examples work
### Versioning
- **patch**: Bug fixes, no API changes
- **minor**: New features, backward compatible
- **major**: Breaking changes
## Important Context
### Design Decisions
- **[Decision]**: [Why this approach was chosen]
- **[Trade-off]**: [What was sacrificed for what gain]
### Known Limitations
- [Limitation 1 and workaround]
- [Limitation 2 and planned fix]
### Browser Support
- Chrome 80+
- Firefox 78+
- Safari 13.1+
- Edge 80+
- Node.js 16+
## For AI Assistants
### When modifying:
- Maintain backward compatibility for minor/patch versions
- Add JSDoc comments to public API
- Update types when changing signatures
- Add tests for new functionality
### Avoid:
- Breaking changes without major version bump
- Side effects in core functions
- Dependencies with large bundle size
- Platform-specific code without fallbacks---
Discovery Commands
# Check entry points
cat package.json | jq '.main, .module, .exports'
# Find public exports
grep -r "export " --include="*.ts" src/index.ts
# Check bundle size
npm run build && du -h dist/Agentic Coding Performance Metrics Template
Project: [Project Name] Period: [Start Date] - [End Date] Team Size: [Number of Developers] Primary Tool: [Claude Code / Cursor / Copilot / Other]
---
Executive Summary
Overall Productivity: [+X% / -X% / No Change] Quality Impact: [Improved / Neutral / Degraded] Developer Satisfaction: [X/10] ROI: [Positive / Neutral / Negative]
---
1. Velocity Metrics
Development Speed
| Metric | Baseline (No AI) | With AI Tool | Change |
|---|---|---|---|
| Features Completed/Sprint | [X] | [Y] | [+Z% / -Z%] |
| Story Points/Sprint | [X] | [Y] | [+Z% / -Z%] |
| Avg. Feature Completion Time | [X days] | [Y days] | [+Z% / -Z%] |
| PRs Merged/Week | [X] | [Y] | [+Z% / -Z%] |
Task Breakdown
| Task Type | Time Saved | Notes |
|---|---|---|
| Boilerplate Generation | [X min] | CRUD, API endpoints, models |
| Test Writing | [X min] | Unit tests, integration tests |
| Code Documentation | [X min] | Comments, docstrings, README |
| Refactoring | [X min] | Code cleanup, pattern migrations |
| Debugging | [X min] | Root cause analysis, error fixes |
| Architecture Planning | [X min] | Design docs, ADRs |
Total Time Saved Per Developer: [X hours/week]
---
2. Quality Metrics
Code Quality
| Metric | Baseline | With AI | Change |
|---|---|---|---|
| Code Review Iterations | [X] | [Y] | [+Z% / -Z%] |
| Critical Bugs/Release | [X] | [Y] | [+Z% / -Z%] |
| Test Coverage % | [X%] | [Y%] | [+Z%] |
| Technical Debt Score | [X] | [Y] | [+Z% / -Z%] |
| Code Complexity (Cyclomatic) | [X] | [Y] | [+Z% / -Z%] |
Security & Compliance
| Metric | Baseline | With AI | Change |
|---|---|---|---|
| Security Vulnerabilities | [X] | [Y] | [+Z% / -Z%] |
| OWASP Top 10 Violations | [X] | [Y] | [+Z% / -Z%] |
| Secrets Exposed in Code | [X] | [Y] | [+Z% / -Z%] |
| SQL Injection Risks | [X] | [Y] | [+Z% / -Z%] |
Testing Impact
| Metric | Baseline | With AI | Notes |
|---|---|---|---|
| Unit Tests Written | [X tests] | [Y tests] | AI-generated vs manual |
| Test Quality Score | [X/10] | [Y/10] | Edge case coverage |
| Test Maintenance Burden | [X hours/month] | [Y hours/month] | Brittleness, false positives |
---
3. Cost Metrics
Direct Costs
| Item | Monthly Cost | Notes |
|---|---|---|
| AI Tool Subscription | $[X] | [Tool name, plan tier] |
| API Usage | $[X] | Token/request costs |
| Training & Onboarding | $[X] | One-time or ongoing |
| Total Direct Cost | $[X] | Per developer or team |
Time Savings Value
| Calculation | Value |
|---|---|
| Avg. Developer Hourly Rate | $[X]/hour |
| Time Saved per Week | [X] hours |
| Value of Time Saved (Monthly) | $[X * 4.33 weeks] |
| Net Monthly Savings | $[Value - Costs] |
ROI Calculation
ROI = (Value of Time Saved - Direct Costs) / Direct Costs * 100%
Example:
- Time saved: 5 hours/week = 21.65 hours/month
- Hourly rate: $75/hour
- Value: 21.65 * $75 = $1,623.75/month
- Tool cost: $20/month
- ROI: ($1,623.75 - $20) / $20 * 100% = 8,018% [TARGET]Your ROI: [X%]
---
4. Developer Experience Metrics
Satisfaction Survey (1-10 Scale)
| Question | Score | Notes |
|---|---|---|
| Overall Satisfaction | [X/10] | How happy are you with the AI tool? |
| Productivity Gain | [X/10] | Do you feel more productive? |
| Code Quality | [X/10] | Does it improve code quality? |
| Learning Curve | [X/10] | How easy was it to adopt? |
| Trust in Suggestions | [X/10] | Do you trust AI-generated code? |
| Integration with Workflow | [X/10] | Does it fit your workflow? |
Behavioral Metrics
| Metric | Value | Notes |
|---|---|---|
| % Code Generated by AI | [X%] | Lines of AI-written code / total |
| Acceptance Rate | [X%] | Accepted suggestions / total suggestions |
| Rejection Rate | [X%] | Rejected suggestions / total suggestions |
| Modification Rate | [X%] | Modified suggestions / accepted suggestions |
| Daily Active Usage | [X hours/day] | Time spent using AI tool |
Perceived vs. Actual Productivity
| Metric | Perceived | Actual | Delta |
|---|---|---|---|
| Productivity Gain | [+X%] | [+Y%] | [Z% gap] |
| Time Saved | [X hours] | [Y hours] | [Z hours gap] |
Note: METR study (2025) found developers believed they were 20% faster but were actually 19% slower. Track both metrics.
---
5. Task-Specific Performance
Feature Implementation
Feature: [Feature Name] Complexity: [Low / Medium / High]
| Phase | Baseline Time | With AI | Time Saved |
|---|---|---|---|
| Planning | [X min] | [Y min] | [Z min] |
| Implementation | [X min] | [Y min] | [Z min] |
| Testing | [X min] | [Y min] | [Z min] |
| Code Review | [X min] | [Y min] | [Z min] |
| Total | [X min] | [Y min] | [Z min] |
AI Contribution:
- [ ] Architecture planning
- [ ] Boilerplate generation
- [ ] Business logic implementation
- [ ] Test case generation
- [ ] Documentation
- [ ] Code review assistance
Outcome:
- [OK] Successful / [FAIL] Failed / [WARNING] Required significant rework
---
6. Anti-Pattern Detection
Common Issues Encountered
| Anti-Pattern | Frequency | Impact | Mitigation |
|---|---|---|---|
| Hallucinated Code | [X times/week] | [High/Med/Low] | [Manual review] |
| Insecure Code (SQL injection, XSS) | [X times] | [High/Med/Low] | [Security review] |
| Over-Engineering | [X times] | [High/Med/Low] | [Prompt refinement] |
| Copy-Paste Without Understanding | [X times] | [High/Med/Low] | [Training] |
| Deprecated Libraries | [X times] | [High/Med/Low] | [Dependency audit] |
| Missing Error Handling | [X times] | [High/Med/Low] | [Review checklist] |
Rework Required
| Reason | % of AI-Generated Code | Avg. Time to Fix |
|---|---|---|
| Logic Errors | [X%] | [Y min] |
| Security Issues | [X%] | [Y min] |
| Performance Problems | [X%] | [Y min] |
| Style Violations | [X%] | [Y min] |
| Missing Tests | [X%] | [Y min] |
---
7. Use Case Breakdown
Where AI Excels
| Task Type | Success Rate | Notes |
|---|---|---|
| CRUD Operations | [X%] | Boilerplate, API endpoints |
| Unit Tests | [X%] | Test case generation |
| Documentation | [X%] | README, code comments |
| Data Transformations | [X%] | Mapping, parsing |
| Simple Refactoring | [X%] | Rename, extract function |
Where AI Struggles
| Task Type | Success Rate | Notes |
|---|---|---|
| Complex Business Logic | [X%] | Domain-specific rules |
| Performance Optimization | [X%] | Requires profiling |
| Architecture Design | [X%] | Needs human judgment |
| Integration with Legacy Code | [X%] | Context limitations |
| Security-Critical Code | [X%] | Requires expert review |
---
8. Comparative Tool Performance
Multi-Tool Tracking (If Using Multiple Tools)
| Metric | Claude Code | GitHub Copilot | Cursor | Windsurf |
|---|---|---|---|---|
| Acceptance Rate | [X%] | [Y%] | [Z%] | [W%] |
| Code Quality | [X/10] | [Y/10] | [Z/10] | [W/10] |
| Speed | [X sec] | [Y sec] | [Z sec] | [W sec] |
| Context Awareness | [X/10] | [Y/10] | [Z/10] | [W/10] |
| Cost | $[X] | $[Y] | $[Z] | $[W] |
Recommended Primary Tool: [Tool Name] Rationale: [Brief explanation]
---
9. Team Adoption & Training
Onboarding Metrics
| Metric | Value | Notes |
|---|---|---|
| Time to First Productive Use | [X days] | Days until first accepted PR with AI |
| Training Hours Required | [X hours] | Onboarding, best practices |
| Adoption Rate | [X%] | % of team actively using tool |
| Power Users | [X devs] | Developers with >80% acceptance rate |
Learning Curve
| Experience Level | Time to Proficiency | Notes |
|---|---|---|
| Junior Developers | [X weeks] | Fastest adopters |
| Mid-Level Developers | [X weeks] | Moderate adoption |
| Senior Developers | [X weeks] | Slowest adopters (skepticism) |
---
10. Long-Term Trends
Month-over-Month
| Month | Velocity | Quality | Satisfaction | Costs |
|---|---|---|---|---|
| Month 1 | [X%] | [Y/10] | [Z/10] | $[W] |
| Month 2 | [X%] | [Y/10] | [Z/10] | $[W] |
| Month 3 | [X%] | [Y/10] | [Z/10] | $[W] |
| Month 4 | [X%] | [Y/10] | [Z/10] | $[W] |
Trend: [Improving / Stable / Degrading]
---
Recommendations
Continue Using AI For:
- [Task type 1]
- [Task type 2]
- [Task type 3]
Avoid AI For:
- [Task type 1]
- [Task type 2]
- [Task type 3]
Process Improvements:
1. [Improvement 1] 2. [Improvement 2] 3. [Improvement 3]
Tool Adjustments:
- [ ] Upgrade to different tier
- [ ] Switch primary tool
- [ ] Add supplementary tool
- [ ] Adjust usage patterns
---
Data Collection Methods
Automated Tracking
Git Metrics:
# Track AI-generated commits
git log --grep="Claude Code" --since="1 month ago" --oneline | wc -l
# Lines changed with AI assistance
git log --author="Your Name" --since="1 month ago" --numstat | awk '{add+=$1; del+=$2} END {print "Added:", add, "Deleted:", del}'IDE Extensions:
- WakaTime: Time tracking per project/file
- GitLens: Commit analytics
- Code Climate: Code quality metrics
AI Tool Analytics:
- Claude Code: Token usage, session analytics
- Copilot: Suggestions accepted/rejected
- Cursor: Composer usage, model analytics
Manual Tracking
Weekly Survey:
1. How many hours did you use AI tools this week? [X hours]
2. Rate your productivity (1-10): [X]
3. Rate code quality (1-10): [X]
4. Any blockers or issues? [Free text]Code Review Checklist:
- [ ] Was AI-generated code reviewed?
- [ ] Did it require rework? (Yes/No)
- [ ] Security issues found? (Yes/No)
- [ ] Quality issues found? (Yes/No)
---
Example Filled Template
Real-World Example: Acme Corp
Project: E-commerce Platform Refactor Period: 2025-01-01 to 2025-03-31 Team Size: 5 Developers Primary Tool: Claude Code Pro
Velocity:
- Features Completed/Sprint: 8 → 11 (+37.5%)
- Avg. Feature Completion Time: 3.2 days → 2.1 days (-34%)
- Time Saved: 8 hours/week per developer
Quality:
- Test Coverage: 72% → 89% (+17%)
- Code Review Iterations: 2.1 → 1.5 (-28%)
- Critical Bugs: 3/release → 1/release (-67%)
Cost:
- Tool Subscription: $100/month (5 devs × $20)
- Time Saved Value: $13,000/month (8 hrs × 5 devs × $75/hr × 4.33 weeks)
- ROI: 12,900%
Outcome: [OK] Significant productivity gain with improved code quality
---
Resources
Productivity Research:
- METR Study (2025): AI Coding Agent Performance
- GitHub: Copilot Productivity Study
- Anthropic: Claude Code Effectiveness
Tracking Tools:
- WakaTime - Time tracking
- Code Climate - Code quality metrics
- Metabase - Custom dashboards
---
Last Updated: 2025-11-21 Skill: docs-ai-prd Related: ai-agents, qa-observability
Minimal CLAUDE.md Template
Quick-start template for project context. Fill in the sections below.
---
# [Project Name]
[One sentence describing what this project does]
## Tech Stack
- **Language**: [e.g., TypeScript 5.x]
- **Framework**: [e.g., Next.js 16, Express, FastAPI]
- **Database**: [e.g., PostgreSQL, MongoDB]
- **Key deps**: [list 3-5 main libraries]
## Architecture
[2-3 sentences describing the high-level design]
### Key Directories
src/ ├── api/ # HTTP handlers ├── services/ # Business logic ├── models/ # Data models ├── utils/ # Shared utilities └── config/ # Configuration
## Conventions
### Naming
- Files: `kebab-case.ts`
- Functions: `camelCase()`
- Classes: `PascalCase`
### Patterns
- [List 2-3 key patterns used, e.g., "Repository pattern for data access"]
## Key Files
| Purpose | Location |
|---------|----------|
| Entry point | `src/index.ts` |
| Config | `src/config/index.ts` |
| Routes | `src/api/routes.ts` |
## Commands
npm run dev # Development npm run test # Tests npm run build # Production build
## Important Context
### Gotchas
- [List any non-obvious behaviors]
- [Known issues or workarounds]
### Recent Changes
- [Any recent significant changes AI should know about]---
Usage
1. Copy the template above 2. Replace bracketed placeholders with your project info 3. Add to project root as CLAUDE.md or .claude/CLAUDE.md 4. Update as project evolves
Expansion
For more comprehensive context, add:
- Dependencies section - external services, APIs
- Tribal knowledge - why decisions were made
- Testing patterns - how tests are organized
- Deployment info - environments, CI/CD
- AI-specific guidance - patterns to follow/avoid
Node.js/TypeScript CLAUDE.md Template
Copy and customize for Node.js or TypeScript projects.
---
# [Project Name]
[One-line description of what this project does]
## Tech Stack
- **Runtime**: Node.js [version] / Bun / Deno
- **Language**: TypeScript [version] / JavaScript (ESM/CJS)
- **Framework**: [Express / Fastify / NestJS / Hono / None]
- **Database**: [PostgreSQL / MySQL / MongoDB / SQLite] via [Prisma / TypeORM / Drizzle / Mongoose]
- **Cache**: [Redis / Memcached / None]
- **Queue**: [BullMQ / RabbitMQ / SQS / None]
- **Testing**: [Jest / Vitest / Mocha] + [Supertest / MSW]
## Architecture
[2-3 sentences describing the overall design approach]
### Directory Structure
src/ ├── api/ # HTTP handlers (routes, controllers) │ ├── routes/ # Route definitions │ ├── middleware/ # Express/Fastify middleware │ └── handlers/ # Request handlers ├── services/ # Business logic layer ├── repositories/ # Data access layer ├── models/ # Database models/entities │ ├── entities/ # ORM entities │ └── dto/ # Data transfer objects ├── utils/ # Shared utilities ├── config/ # Configuration management ├── types/ # TypeScript type definitions └── __tests__/ # Test files (or co-located)
### Key Patterns
- **Repository Pattern**: Data access abstracted via `src/repositories/`
- **Service Layer**: Business logic in `src/services/`, no direct DB access in handlers
- **Dependency Injection**: [NestJS DI / tsyringe / manual / none]
- **Error Handling**: Custom error classes in `src/errors/`, global handler in middleware
### Data Flow
Request → Middleware (auth, validation) → Handler → Service → Repository → Database ↓ Response ← Handler ← Service ← Repository ←─────────────────────────┘
## Conventions
### Naming
| Type | Convention | Example |
|------|------------|---------|
| Files | kebab-case | `user-service.ts` |
| Classes | PascalCase | `UserService` |
| Functions | camelCase | `getUserById` |
| Constants | SCREAMING_SNAKE | `MAX_RETRY_COUNT` |
| Interfaces | PascalCase + I prefix (optional) | `IUserRepository` or `UserRepository` |
| Types | PascalCase | `UserCreateInput` |
| Enums | PascalCase + SCREAMING values | `UserRole.ADMIN` |
### File Organization
- One class/service per file
- Barrel exports via `index.ts` in each directory
- Tests co-located as `*.test.ts` or `*.spec.ts`
- DTOs separate from entities
### TypeScript
- Strict mode enabled (`strict: true`)
- Explicit return types on public functions
- Avoid `any` - use `unknown` + type guards
- Prefer interfaces for objects, types for unions/primitives
### Imports
// Order: external → internal → relative import { Injectable } from '@nestjs/common'; import { PrismaService } from '@/db/prisma'; import { UserDto } from './dto/user.dto';
## Key Files
| Purpose | Location | Notes |
|---------|----------|-------|
| Entry point | `src/index.ts` or `src/main.ts` | Server bootstrap |
| App setup | `src/app.ts` | Express/Fastify app configuration |
| Routes | `src/api/routes/index.ts` | Route registration |
| Database client | `src/db/client.ts` | Prisma/TypeORM instance |
| Config | `src/config/index.ts` | Environment variable loading |
| Types | `src/types/index.ts` | Shared type definitions |
| Constants | `src/constants/index.ts` | App-wide constants |
## Configuration
### Environment Variables
.env.example
NODE_ENV=development PORT=3000 DATABASE_URL=postgresql://user:pass@localhost:5432/db REDIS_URL=redis://localhost:6379 JWT_SECRET=your-secret-here LOG_LEVEL=debug
### Config Loading Pattern
// src/config/index.ts export const config = { port: parseInt(process.env.PORT || '3000'), db: { url: process.env.DATABASE_URL }, // ... validated with zod/joi };
## Commands
Development
npm run dev # Start with hot reload (nodemon/tsx) npm run build # Compile TypeScript npm start # Run compiled JS
Database
npm run db:migrate # Run migrations npm run db:generate # Generate Prisma client npm run db:seed # Seed database npm run db:studio # Open Prisma Studio
Testing
npm test # Run all tests npm run test:watch # Watch mode npm run test:cov # With coverage npm run test:e2e # E2E tests
Quality
npm run lint # ESLint npm run lint:fix # Auto-fix npm run format # Prettier npm run typecheck # tsc --noEmit
## Important Context
### Technical Decisions
#### [Why Prisma over TypeORM]
**Context**: Needed type-safe database access
**Decision**: Prisma for better DX and type generation
**Trade-off**: Less flexible raw queries, migration workflow different
### Known Gotchas
- **Prisma client regeneration**: Run `npm run db:generate` after schema changes
- **Circular dependencies**: Use barrel exports carefully, may need lazy imports
- **BigInt handling**: JSON.stringify fails on BigInt, use `BigInt.prototype.toJSON`
- **Date timezone**: All dates stored as UTC, convert on display
### Historical Context
- [Any migrations, refactors, or legacy patterns to know about]
## Testing
### Test Structure
// src/services/__tests__/user.service.test.ts describe('UserService', () => { describe('create', () => { it('should create user with valid input', async () => {}); it('should throw on duplicate email', async () => {}); }); });
### Mocking
- Database: Mock repository layer, not Prisma directly
- External APIs: Use MSW for HTTP mocks
- Time: Use `jest.useFakeTimers()` for time-dependent tests
## For AI Assistants
### When modifying this codebase:
- Follow existing patterns in similar files
- Add tests for new functionality
- Update DTOs when changing API contracts
- Run `npm run lint && npm run typecheck` before committing
- Use existing error classes from `src/errors/`
### Patterns to follow:
- Services return domain objects, handlers transform to DTOs
- All database operations through repositories
- Validation at API boundary (middleware or decorators)
- Async/await everywhere, no callbacks
### Avoid:
- Direct database queries outside repositories
- `console.log` in production code (use logger)
- Synchronous file operations
- Mutations in service layer (return new objects)
- `any` type without explicit justification---
Quick Start Commands
Run these to gather context for a new Node.js project:
# Basic structure
tree -L 3 -I 'node_modules|dist|.git|coverage'
# Dependencies
cat package.json | jq '{dependencies, devDependencies, scripts}'
# TypeScript config
cat tsconfig.json | jq '{compilerOptions: {target, module, strict}}'
# Entry point
head -50 src/index.ts || head -50 src/main.ts
# Find all services
find src -name "*service*" -o -name "*Service*"
# Check for ORM
ls prisma/ 2>/dev/null || ls src/entities/ 2>/dev/null# Agentic Session Template
*Purpose: Copy-paste template for structuring a full agentic (AI-powered or LLM-driven) coding session, ensuring safety, repeatability, and handoff quality. Use for autonomous coding tasks, multi-step GenAI workflows, or when running an agent as a “senior engineer.”*
---
## When to Use
Use this template to:
- Launch a new coding or refactor session with a coding agent (Claude Code, Copilot, Cursor, etc.)
- Structure any autonomous or semi-autonomous feature build, bug fix, or root-cause analysis
- Hand off session context between humans and agents, or between agentic runs
---
## Structure
This template has 7 sections:
1. **Session Trigger**
2. **Objectives & Metrics**
3. **Session Rules & Guardrails**
4. **Recon & Context Mapping**
5. **Action Plan**
6. **Execution & Checkpoints**
7. **Session Handoff & Retro**
---
# TEMPLATE STARTS HERE
## 1. Session Trigger
- [ ] What event or request started this session?
_(E.g., “Add real-time task status”, “Fix failing tests on main branch”, “Update docs after refactor”)_
---
## 2. Objectives & Metrics
- [ ] Clear session goals (feature delivered, bug fixed, tests passing, etc.)
- [ ] Success criteria/metrics (quantitative or checklist)
- [ ] Timebox/expected session duration (e.g., “30 min max”, “Until all tests pass”)
---
## 3. Session Rules & Guardrails
- [ ] Planning required before any code or files change? (Y/N)
- [ ] Maximum lines/files per action (e.g., “Do not change more than 5 files per step”)
- [ ] Command/execution limits (e.g., “All shell commands wrapped for safety”)
- [ ] No external writes, deletions, or destructive ops without explicit approval
- [ ] Ask for clarification if context/requirements are unclear
---
## 4. Recon & Context Mapping
- [ ] Inventory current files, dependencies, and key functions (auto-list OK)
- [ ] Map all relevant code/tests/docs (or attach outputs)
- [ ] Identify blockers, missing context, or unknowns before starting work
---
## 5. Action Plan
- [ ] List all steps/phases to complete goal (may update after recon)
- Example:
1. Inventory code/tests
2. Update Task API
3. Add dashboard indicator
4. Run/test/validate
5. Update docs
6. Final QA/handoff
- [ ] Assign owner for each step (agent or human)
- [ ] Attach acceptance criteria to each phase if possible
---
## 6. Execution & Checkpoints
- [ ] Work proceeds in increments (1–2 steps at a time)
- [ ] After each increment: checkpoint, self-review, update context/docs
- [ ] Run tests and validate before moving to next phase
- [ ] QA checklist (see resources) completed at each major milestone
---
## 7. Session Handoff & Retro
- [ ] Summarize session outcome:
- What was completed?
- Any remaining issues, risks, or TODOs?
- Updated docs, context, or artifacts?
- [ ] List learnings, blockers, and process notes for next session or team
- [ ] Confirm all outputs are saved/shared for human or next agent
---
# COMPLETE EXAMPLE
## 1. Session Trigger
- Request: “Add accessibility warnings to dashboard for users with color vision deficiency”
## 2. Objectives & Metrics
- Objective: Add WCAG-compliant status warnings
- Metric: All status colors pass contrast tests; tests automated
- Timebox: 1 hour
## 3. Session Rules & Guardrails
- Planning required before changes: Yes
- Max 2 files per step
- All changes must be reversible via git
- No deletions without approval
## 4. Recon & Context Mapping
- Files: `dashboard.js`, `statusIndicator.css`, `test/dashboard.test.js`
- Context: PRD attached, agentic plan checkpointed in session doc
## 5. Action Plan
1. Inventory code & tests (agent)
2. Update status colors for contrast (agent)
3. Add test for color contrast (agent)
4. Human validates with screen reader tools
5. Update help docs (agent)
6. Final QA, push for review (human)
## 6. Execution & Checkpoints
- After each phase: run tests, checkpoint output, update session doc
- QA checklist at phase 4 and final step
## 7. Session Handoff & Retro
- Outcome: New status colors, passing contrast tests, help docs updated
- Risks: Need user feedback on live accessibility
- Docs: `/docs/accessibility-changelog.md` updated, next steps flagged for future
---
## Quality Checklist
Before finishing:
- [ ] All 7 sections filled and reviewed
- [ ] All outputs, docs, and artifacts checkpointed and saved
- [ ] No open blockers, unknowns, or incomplete phases remain
- [ ] Retro/notes provided for team or next agent# Planning Checklist Template
*Purpose: Ready-to-use, actionable planning checklist for agentic/AI-driven or traditional software projects. Ensures every session or feature starts with clarity, risk control, and an executable plan—suitable for both human and agent workflows.*
---
## When to Use
Use this template before:
- Kicking off an agentic coding session or multi-phase project
- Starting any feature with >3 files, >2 unknowns, or architectural changes
- Major refactors, integrations, or AI-driven implementation tasks
---
## Structure
This checklist has 5 core sections:
1. **Inputs & Triggers**
2. **Goals & Outcomes**
3. **Scope & Risks**
4. **Phases & Milestones**
5. **Review & Commitment**
---
# TEMPLATE STARTS HERE
## 1. Inputs & Triggers
- [ ] Clear problem statement or PRD attached
- [ ] All stakeholders/agents identified
- [ ] Success metrics, deadlines, and business drivers listed
- [ ] Entry criteria met (see “When to use” above)
- [ ] Dependencies, prior context, or session history included
---
## 2. Goals & Outcomes
- [ ] Explicitly define desired outcomes (features, tests, deliverables)
- [ ] Success is measurable (quantified or testable)
- [ ] Non-goals or out-of-scope items listed
---
## 3. Scope & Risks
- [ ] List files/systems/components in scope
- [ ] Document known unknowns, assumptions, and external dependencies
- [ ] Identify risks (integration, agent reliability, unclear specs, etc.)
- [ ] Risk mitigation strategies or fallback options described
---
## 4. Phases & Milestones
- [ ] Break down work into increments/phases (e.g., “Phase 1: API scaffolding”)
- [ ] Assign owner (human or agent) for each phase
- [ ] Define checkpoints for review and test (QA, integration, sign-off)
- [ ] Estimated timeline for each phase
---
## 5. Review & Commitment
- [ ] Team/agent review and approval before implementation
- [ ] Commitment to update docs/context after each major phase
- [ ] QA checklists pre-attached for validation (see resources)
- [ ] Explicit sign-off or “go” before work begins
---
# COMPLETE EXAMPLE
## 1. Inputs & Triggers
- PRD: “Dashboard Status Indicator” attached
- Stakeholders: Product Owner, Agentic Dev, QA
- Success: 30% fewer support tickets by next quarter
- Deadline: Q2 release
- Dependencies: Live Task API, Color design system
## 2. Goals & Outcomes
- Add real-time status icons to dashboard
- Automated tests for all states and accessibility
- Non-goals: No mobile changes, no API redesign
## 3. Scope & Risks
- Scope: Dashboard, Task API, Agent integration
- Risks: Agent may lose context mid-session; UI edge cases
- Mitigation: Context update docs at every phase; manual QA for accessibility
## 4. Phases & Milestones
- Phase 1: Add status icons (owner: Agent)
- Phase 2: Integrate with Task API (owner: Human)
- Phase 3: Test and validate accessibility (owner: QA)
- Timeline: 2 weeks total, review after each phase
## 5. Review & Commitment
- Team review scheduled before each phase
- Docs updated in `/docs/status-dashboard.md` after every increment
- QA checklist attached for final validation
- Go decision logged in project tracker
---
## Quality Checklist
Before starting:
- [ ] All 5 sections filled and reviewed
- [ ] Inputs, risks, and milestones are specific (no “TBD”)
- [ ] QA and review steps are pre-attached
- [ ] Out-of-scope items are listed
- [ ] Docs/context are ready to update during projectAI PRD Template (AI Feature / AI System)
Purpose: define an AI-powered feature/system with an explicit evaluation plan, risk controls, and monitoring/rollback.
References (non-exhaustive):
- NIST AI RMF 1.0: https://www.nist.gov/publications/artificial-intelligence-risk-management-framework-ai-rmf-10
- ISO/IEC 42001 overview: https://www.iso.org/standard/42001
- EU AI Act (Regulation (EU) 2024/1689): https://eur-lex.europa.eu/eli/reg/2024/1689/oj/eng
Inputs
- User problem + workflow context (who, when, why now)
- Data inventory: sources, rights, retention, PII classification
- Baseline solution (non-AI or simpler AI) for comparison
- Constraints: latency/cost budget, safety/compliance requirements, regions
Outputs
- AI PRD with acceptance criteria, eval plan, risk controls, and incident playbook
- Go/no-go criteria and rollout plan with rollback triggers
Core
1) Overview
- Problem statement: {{PROBLEM_STATEMENT}}
- Primary user: {{PRIMARY_USER}}
- Primary job to be done: {{JTBD}}
- Why AI (vs rules/workflow change): {{WHY_AI}}
- Out of scope: {{NON_GOALS}}
2) User Experience + Transparency
- User-facing behavior: {{UX_BEHAVIOR}}
- User controls: {{USER_CONTROLS}}
- Disclosures (what the system is/does): {{DISCLOSURES}}
- Human-in-the-loop requirements (if any): {{HITL_REQUIREMENTS}}
3) System Description
- Inputs: {{INPUTS}}
- Outputs: {{OUTPUTS}}
- Where the AI runs (client/server/vendor): {{RUNTIME}}
- Tool use / integrations: {{TOOLS_INTEGRATIONS}}
- Fallback behavior: {{FALLBACKS}}
4) Data Plan (Privacy, Rights, Retention)
| Data | Source | Fields | PII? | Rights/License | Retention | Access controls |
|---|---|---|---|---|---|---|
| {{DATASET}} | {{SOURCE}} | {{FIELDS}} | {{YES_NO}} | {{RIGHTS}} | {{RETENTION}} | {{ACL}} |
- Data minimization: {{MINIMIZATION}}
- Redaction/anonymization: {{REDACTION}}
- Consent/notice requirements: {{CONSENT_NOTICE}}
- Cross-border constraints: {{DATA_RESIDENCY}}
5) Model/Approach Plan
- Baseline (required): {{BASELINE_APPROACH}}
- Proposed approach: {{MODEL_APPROACH}}
- Prompting/tooling constraints (if LLM): {{PROMPTING_CONSTRAINTS}}
- Safety controls at generation time: {{GENERATION_CONTROLS}}
- Cost/latency budget: {{BUDGETS}}
6) Evaluation Plan (REQUIRED)
Define what “good” means before building.
Offline evaluation
- Test sets: {{DATA_SPLITS_AND_GOLDEN_SET}}
- Labeling/ground truth method: {{LABELING_METHOD}}
- Quality metrics: {{QUALITY_METRICS}}
- Safety metrics: {{SAFETY_METRICS}}
- Performance metrics (latency/cost): {{PERF_METRICS}}
Human evaluation
- Rubric (1–5) with definitions: {{HUMAN_RUBRIC}}
- Reviewer sampling + calibration plan: {{REVIEWER_PLAN}}
- Inter-rater agreement target: {{IRA_TARGET}}
Online evaluation (if applicable)
- Experiment design: {{EXPERIMENT_DESIGN}}
- Success metric + guardrails: {{SUCCESS_AND_GUARDRAILS}}
- Stop rules: {{STOP_RULES}}
7) Failure Modes + Mitigations
| Failure mode | User harm | Likelihood | Detection | Mitigation | Residual risk |
|---|---|---|---|---|---|
| {{MODE}} | {{HARM}} | {{L/M/H}} | {{DETECT}} | {{MITIGATE}} | {{RISK}} |
Include at minimum:
- Incorrect output / hallucination
- Prompt injection / tool misuse (if tool-using)
- Data leakage / memorization risk
- Bias / disparate impact risk
- Abuse and policy violations
8) Monitoring + Incident Response
- Production quality signals: {{PROD_SIGNALS}}
- Drift monitoring: {{DRIFT_PLAN}}
- Logging policy (privacy): {{LOGGING_POLICY}}
- Alerting thresholds: {{ALERT_THRESHOLDS}}
- Incident severity levels + playbook: {{INCIDENT_PLAYBOOK}}
9) Rollout Plan
- Rollout stages: internal → beta → GA (or your plan)
- Feature flags + kill switch: {{FLAGS}}
- Rollback triggers: {{ROLLBACK_TRIGGERS}}
- Customer comms plan: {{COMMS}}
10) Security, Privacy, and Compliance
- Security review requirements: {{SECURITY_REVIEW}}
- Data processing agreements (if vendors): {{DPA}}
- Applicable regulations and classification: {{REGULATORY_NOTES}}
- Audit trail requirements: {{AUDIT_TRAIL}}
Decision Rules
- Do not ship without: baseline comparison + offline eval + explicit safety controls + rollback plan.
- Ship to beta only if: offline metrics meet {{BETA_BAR}} AND failure modes have mitigations and monitoring.
- Stop/rollback if: guardrails regress beyond {{THRESHOLD}} OR incident severity ≥ {{SEVERITY}}.
Risks
- Evaluation gaps: metrics don’t reflect real user value; weak test sets
- Data risks: unclear rights, PII exposure, retention violations
- Compliance risk: misclassification or missing transparency obligations
- Operational risk: cost/latency overruns, unreliable vendor dependencies
Optional: AI / Automation
Use only if allowed by policy and data handling rules.
- PRD drafting: generate first-pass sections from notes; require citation links and human edits.
- Evaluation support: auto-generate test cases, but require human review and spot-checking.
- Monitoring support: summarize incidents and trend alerts; do not auto-resolve without review.
PRD Template (Core, Non-AI)
Purpose: write a minimal, actionable Product Requirements Document (PRD) for any product/feature (not AI-specific).
Inputs
- Problem evidence: quotes, tickets, research notes, logs (sanitized)
- Target users/segments and context of use
- Constraints: timeline, team capacity, dependencies, compliance/security requirements
Outputs
- PRD with scope, requirements, and measurable success criteria
- Explicit go/no-go decision rules and risks
Core
1) Problem
- Problem statement (1–3 sentences): {{PROBLEM_STATEMENT}}
- Who has the problem: {{PRIMARY_USER}}
- Context: {{WHEN_WHERE}}
- Why now: {{WHY_NOW}}
- Evidence links (docs/tickets/metrics): {{EVIDENCE_LINKS}}
2) Goals / Non-Goals
Goals (outcomes first)
- {{GOAL_1}}
- {{GOAL_2}}
Non-goals (explicit exclusions)
- {{NON_GOAL_1}}
- {{NON_GOAL_2}}
3) Users, JTBD, and Success Context
| User/Role | Job to be done | Current workaround | Success looks like |
|---|---|---|---|
| {{USER}} | {{JTBD}} | {{WORKAROUND}} | {{SUCCESS}} |
4) Requirements
Functional requirements (testable)
- FR1: {{REQUIREMENT}} (user value + acceptance)
- FR2: {{REQUIREMENT}}
Non-functional requirements (measurable)
- Performance: {{SLO_LATENCY_THROUGHPUT}}
- Reliability: {{SLO_UPTIME_ERROR_BUDGET}}
- Security/privacy: {{SECURITY_PRIVACY_REQUIREMENTS}}
- Accessibility: {{ACCESSIBILITY_BAR}}
Data & analytics
- Events to instrument: {{EVENTS}}
- Metrics definitions (exact formulas): {{METRIC_DEFS}}
- Guardrails (what must not regress): {{GUARDRAILS}}
Dependencies & constraints
- Dependencies: {{DEPENDENCIES}}
- Constraints: {{CONSTRAINTS}}
- Rollout constraints (regions, roles, etc.): {{ROLLOUT_CONSTRAINTS}}
5) Scope, Plan, and Open Questions
- Milestones (date + owner): {{MILESTONES}}
- Risks / unknowns: {{RISKS_UNKNOWN}}
- Open questions (owner + due date): {{OPEN_QUESTIONS}}
6) Acceptance Criteria & Success Metrics
Acceptance criteria (binary, testable)
- [ ] {{ACCEPTANCE_CRITERION_1}}
- [ ] {{ACCEPTANCE_CRITERION_2}}
Success metrics (measurable)
- Primary: {{PRIMARY_METRIC}} (baseline {{BASELINE}}, target {{TARGET}}, window {{WINDOW}})
- Inputs: {{INPUT_METRICS}}
- Guardrails: {{GUARDRAIL_METRICS}}
Decision Rules
- Build only if: evidence is strong enough ({{EVIDENCE_BAR}}) AND success metrics are measurable AND owner is named.
- Stop/pivot if: guardrails regress beyond {{THRESHOLD}} OR success metric misses by {{THRESHOLD}} for {{WINDOW}}.
Risks
- Mis-scoping: outcome unclear, success metric not attributable
- Data/privacy: PII leakage in analytics or docs
- Delivery: dependency risk, unclear ownership
- Measurement: instrumentation missing, metric definitions inconsistent
Optional: AI / Automation
Use only if allowed by policy and data handling rules.
- Drafting: generate first-pass PRD sections from notes; human owns decisions and final wording.
- Synthesis: cluster interview notes; include an audit trail (source links + spot-checks).
- QA: scan for missing acceptance criteria, unmeasurable metrics, or ambiguous language; do not fabricate data.
# Prompt Playbook Template
*Purpose: Copy-paste ready prompt playbook for GenAI/agentic coding. Use this to standardize high-quality, reproducible prompts for coding agents (Claude Code, Copilot, Cursor, Codex, etc). Includes skeletons for common operational tasks and best-practice checklist.*
---
## When to Use
Use this playbook when:
- Creating new prompts for code generation, refactoring, testing, documentation, or planning
- Standardizing your team’s or project’s prompts for reuse by humans or agents
- Need consistent, reliable, and safe outputs from LLMs or agentic workflows
---
## Structure
This playbook contains:
1. **Prompt Skeletons for Core Tasks**
2. **Quick Reference: Prompt Hygiene**
3. **Prompt QA Checklist**
---
# TEMPLATE STARTS HERE
## 1. Prompt Skeletons for Core Tasks
**A. Feature/Component Generation**You are a senior [role] working on [project/type]. Context: [Insert 1–2 sentences of what the system/feature does, any relevant constraints]. Instruction: Generate [component/code/class/API] that [describes key requirement], using [tech/language/framework]. Output: Reply ONLY with the code in a single [file/block], no explanations. Format: [Markdown/code block/JSON/etc.]
**B. Bug Fixing / Refactoring**Context: Here is the code that needs fixing/refactoring: [Insert code or link] Instruction: [e.g., "Fix the off-by-one error in the loop", "Refactor to improve testability"] Output: Return only the modified code and a summary of the change (2 sentences max).
**C. Test Generation**Context: Here is the function/class that requires tests: [Insert code block or API signature] Instruction: Generate unit tests covering edge cases, invalid inputs, and typical use. Output: [Language]/[Framework]-formatted test code, with comments.
**D. Documentation/Spec Generation**Context: The following code/feature needs doc/spec: [Insert code or PRD snippet] Instruction: Generate concise [docstring/README/spec] summarizing function, inputs, outputs, and usage examples. Output: Only the documentation block in [format].
**E. Planning/Task Decomposition**You are planning a new [feature/refactor/agentic session]. Context: [PRD summary, goals, constraints, user stories]. Instruction: Break this down into actionable tasks and phases, listing dependencies and edge cases. Output: Markdown table or checklist; do not start implementation yet.
---
## 2. Quick Reference: Prompt Hygiene
- [ ] Role and context specified (who/what/where/constraints)
- [ ] Explicit task/instruction (single, unambiguous)
- [ ] Desired output format stated (code block, JSON, Markdown, etc.)
- [ ] Examples included (for reproducibility or structure)
- [ ] Request for “no explanation” or “code only” if applicable
- [ ] No irrelevant information or theory
---
## 3. Prompt QA Checklist
- [ ] Prompt is focused (single clear goal)
- [ ] Context is just enough—no overload or missing info
- [ ] Output format is explicit
- [ ] Copied and pasted into LLM/agent and works as intended
- [ ] Team or agent reviewed and signed off for reuse
- [ ] If output matters: add 1–2 examples for reference
---
# COMPLETE EXAMPLE
**Feature Generation**You are a senior TypeScript developer. Context: Building a dashboard that displays user tasks, using React. Instruction: Generate a reusable TaskStatusIndicator component that shows a color-coded icon for completed/pending tasks, supporting screen readers. Output: Reply only with the complete React component, using TypeScript and Markdown code block.
**Test Generation**Context: This is the sumArray function:
def sumArray(arr):
return sum(arr)Instruction: Generate Python unit tests for edge cases, invalid input, and typical use. Output: Python test code in a Markdown code block.
---
## Quality Checklist
Before using or sharing:
- [ ] Chosen skeleton fits the use case
- [ ] All hygiene/QA checklist items are complete
- [ ] Copy-paste works with the intended LLM or agent
- [ ] Results are validated before merging into production# Structured Prompt Examples Template
*Purpose: Operational template with copy-paste examples of high-quality, structured prompts for GenAI/agentic coding. Use these to ensure reproducible results, format control, and clear agent instructions for common coding and documentation tasks.*
---
## When to Use
- Need examples of well-formed prompts for your LLM or agentic coding tool (Claude, Copilot, Cursor, etc.)
- Onboard team members or standardize prompt patterns for repeated use
- Train agents or workflows to produce consistent outputs (specs, code, docs, tests, etc.)
---
## Structure
Each example includes:
- Task Type
- Context Block
- Instruction Block
- Output Format Block
- (Optional) Few-shot Example
---
# TEMPLATE STARTS HERE
---
### Example 1: Feature Generation (React Component)
**Prompt**You are a senior frontend developer. Context: Building a React dashboard for managing user tasks. Status (completed/pending) must be visible and accessible. Instruction: Generate a TaskStatusIndicator component that displays a green check for completed and gray circle for pending, with ARIA labels for accessibility. Output: Only the React component code, as a Markdown code block.
---
### Example 2: API Endpoint (Express.js)
**Prompt**You are a backend engineer. Context: Users need an endpoint to fetch all their active tasks for the dashboard. Instruction: Generate an Express.js route handler for GET /tasks/active that queries tasks by userId and returns them as JSON. Include basic error handling. Output: Only the route handler code in a Markdown code block.
---
### Example 3: Unit Test Generation (Python)
**Prompt**You are a Python test engineer. Context: The following function needs comprehensive unit tests:
def multiply(a, b):
return a * bInstruction: Generate pytest unit tests covering positive, zero, negative, and invalid input. Output: Only the pytest test functions, as a Markdown code block.
---
### Example 4: Documentation/README Block
**Prompt**You are a technical writer. Context: The following module provides utilities for manipulating dates:
add_days(date, n)days_between(date1, date2)
Instruction: Write a concise README section describing the usage of these functions, with code samples. Output: Only the documentation block, in Markdown format.
---
### Example 5: Planning/Task Breakdown
**Prompt**You are a tech lead planning a new dashboard feature. Context: Goal is to display real-time user notifications in the dashboard. Users need to see new alerts within 2 seconds. Instruction: Break down the work into clear engineering tasks (backend, frontend, agent integration, QA), list dependencies and edge cases. Output as a Markdown checklist. Output: Only the task checklist, no implementation.
---
### Example 6: Few-Shot Prompt (for Standardized Output)
**Prompt**Example: Input: Generate a function to reverse a string in Python. Output:
def reverse_string(s):
return s[::-1]Now do the same for: Input: Generate a function to check if a string is a palindrome in Python. Output:
---
## Quality Checklist
Before using or sharing:
- [ ] Context, instruction, and output format clearly separated
- [ ] Only one main task per example
- [ ] Examples copy-paste directly into agent/LLM and work
- [ ] Team or agent has validated output
Python CLAUDE.md Template
Copy and customize for Python projects.
---
# [Project Name]
[One-line description of what this project does]
## Tech Stack
- **Python**: [3.11 / 3.12]
- **Framework**: [FastAPI / Django / Flask / None]
- **Database**: [PostgreSQL / MySQL / SQLite] via [SQLAlchemy / Django ORM / Tortoise]
- **Async**: [asyncio / sync]
- **Task Queue**: [Celery / RQ / Dramatiq / None]
- **Package Manager**: [uv / poetry / pip]
- **Testing**: [pytest] + [pytest-asyncio / pytest-django]
## Architecture
[2-3 sentences describing the overall design approach]
### Directory Structure
src/ ├── api/ # HTTP layer │ ├── routes/ # Route definitions │ ├── deps.py # Dependency injection │ └── middleware/ # Request middleware ├── services/ # Business logic ├── repositories/ # Data access layer ├── models/ # Database models │ ├── entities/ # SQLAlchemy models │ └── schemas/ # Pydantic schemas ├── core/ # Core utilities │ ├── config.py # Settings │ ├── security.py # Auth utilities │ └── exceptions.py # Custom exceptions ├── utils/ # Shared utilities └── tests/ # Test files ├── unit/ ├── integration/ └── conftest.py
### Key Patterns
- **Repository Pattern**: Data access in `repositories/`, services don't touch ORM directly
- **Dependency Injection**: FastAPI `Depends()` or manual DI
- **Pydantic Schemas**: Request/response validation via Pydantic v2
- **Async-first**: All I/O operations are async (FastAPI/SQLAlchemy async)
### Data Flow
Request → Middleware → Route → Service → Repository → Database ↓ Response ← Route ← Service ← Repository ←────┘
## Conventions
### Naming
| Type | Convention | Example |
|------|------------|---------|
| Files | snake_case | `user_service.py` |
| Classes | PascalCase | `UserService` |
| Functions | snake_case | `get_user_by_id` |
| Constants | SCREAMING_SNAKE | `MAX_RETRY_COUNT` |
| Private | Leading underscore | `_internal_method` |
| Type aliases | PascalCase | `UserId = int` |
### File Organization
- One class per file for services/repositories
- Models can be grouped by domain
- Tests mirror source structure in `tests/`
- `__init__.py` for explicit exports
### Type Hints
Always use type hints
def get_user(user_id: int) -> User | None: ...
Use modern syntax (3.10+)
def process(items: list[str]) -> dict[str, int]: ...
Pydantic for validation
class UserCreate(BaseModel): email: EmailStr name: str = Field(min_length=1, max_length=100)
### Imports
Order: stdlib → third-party → local (isort handles this)
from __future__ import annotations
import asyncio from typing import TYPE_CHECKING
from fastapi import Depends from sqlalchemy.ext.asyncio import AsyncSession
from src.core.config import settings from src.models.user import User
if TYPE_CHECKING: from src.services.user import UserService
## Key Files
| Purpose | Location | Notes |
|---------|----------|-------|
| Entry point | `src/main.py` | FastAPI app creation |
| App factory | `src/app.py` | App configuration |
| Routes | `src/api/routes/__init__.py` | Router registration |
| Database | `src/core/database.py` | SQLAlchemy engine/session |
| Config | `src/core/config.py` | Pydantic Settings |
| Models | `src/models/` | SQLAlchemy + Pydantic |
## Configuration
### Environment Variables
.env
ENV=development DEBUG=true DATABASE_URL=postgresql+asyncpg://user:pass@localhost:5432/db REDIS_URL=redis://localhost:6379 SECRET_KEY=your-secret-key LOG_LEVEL=DEBUG
### Settings Pattern (Pydantic)
src/core/config.py
from pydantic_settings import BaseSettings
class Settings(BaseSettings): env: str = "development" debug: bool = False database_url: str secret_key: str
class Config: env_file = ".env"
settings = Settings()
## Commands
Development
uv run uvicorn src.main:app --reload # Start dev server uv run python -m src.main # Alternative start
Database
uv run alembic upgrade head # Run migrations uv run alembic revision --autogenerate -m "description" # Create migration uv run python -m src.scripts.seed # Seed database
Testing
uv run pytest # Run all tests uv run pytest -v --tb=short # Verbose with short traceback uv run pytest --cov=src # With coverage uv run pytest -k "test_user" # Run specific tests uv run pytest -x # Stop on first failure
Quality
uv run ruff check . # Linting uv run ruff check . --fix # Auto-fix uv run ruff format . # Formatting uv run mypy src/ # Type checking uv run pre-commit run --all-files # All checks
## Important Context
### Technical Decisions
#### [Why FastAPI over Django]
**Context**: Building async API with strong typing
**Decision**: FastAPI for native async + Pydantic integration
**Trade-off**: Less batteries-included than Django, manual auth setup
#### [Why SQLAlchemy 2.0 async]
**Context**: Needed async database operations
**Decision**: SQLAlchemy 2.0 with asyncpg
**Trade-off**: More complex setup than sync, careful session management
### Known Gotchas
- **Async session management**: Always use `async with` for sessions, never share across requests
- **Circular imports**: Use `TYPE_CHECKING` guard for type hints
- **Alembic autogenerate**: Review generated migrations, doesn't catch everything
- **Pydantic v2**: Different from v1, use `model_dump()` not `dict()`
- **SQLAlchemy lazy loading**: Doesn't work in async, use `selectinload()`
### Historical Context
- [Any migrations, refactors, or legacy patterns to know about]
## Testing
### Test Structure
tests/unit/services/test_user_service.py
import pytest from src.services.user import UserService
class TestUserService: @pytest.fixture def service(self, mock_repo): return UserService(repo=mock_repo)
async def test_create_user_success(self, service): result = await service.create(email="test@example.com") assert result.email == "test@example.com"
async def test_create_user_duplicate_raises(self, service): with pytest.raises(DuplicateEmailError): await service.create(email="existing@example.com")
### Fixtures
tests/conftest.py
import pytest from httpx import AsyncClient from src.main import app
@pytest.fixture async def client(): async with AsyncClient(app=app, base_url="http://test") as ac: yield ac
@pytest.fixture async def db_session():
Test database session setup
...
## For AI Assistants
### When modifying this codebase:
- Follow existing patterns in similar files
- Add tests for new functionality (pytest)
- Use type hints everywhere
- Run `ruff check && mypy src/` before committing
- Create Alembic migration for model changes
### Patterns to follow:
- Async/await for all I/O operations
- Pydantic schemas for API input/output
- Repository pattern for database access
- Dependency injection via FastAPI `Depends()`
### Avoid:
- Sync database operations in async context
- Direct ORM queries in route handlers
- `print()` statements (use `logging`)
- Bare `except:` clauses
- Mutable default arguments---
Quick Start Commands
Run these to gather context for a new Python project:
# Basic structure
tree -L 3 -I '__pycache__|.venv|.git|.pytest_cache|*.egg-info'
# Dependencies
cat pyproject.toml | grep -A 50 "[tool.poetry.dependencies]" || cat requirements.txt
# Python version
cat .python-version 2>/dev/null || python --version
# Entry point
head -50 src/main.py || head -50 app.py
# Find all services
find . -name "*service*" -type f -name "*.py"
# Check for ORM
ls alembic/ 2>/dev/null && echo "SQLAlchemy/Alembic detected"
ls */migrations/ 2>/dev/null && echo "Django detected"React / Next.js CLAUDE.md Template
Copy and customize for React or Next.js projects.
---
# [Project Name]
[One-line description of what this project does]
## Tech Stack
- **Framework**: [Next.js 16 / React 19 / Remix / Vite + React]
- **Language**: TypeScript [version]
- **Styling**: [Tailwind CSS / CSS Modules / styled-components / Emotion]
- **State**: [Zustand / Redux Toolkit / Jotai / React Query / Context]
- **Data Fetching**: [React Query / SWR / tRPC / Server Actions]
- **Forms**: [React Hook Form / Formik] + [Zod / Yup]
- **UI Components**: [shadcn/ui / Radix / Headless UI / MUI]
- **Testing**: [Vitest / Jest] + [Testing Library / Playwright]
## Architecture
[2-3 sentences describing the overall design approach]
### Directory Structure (Next.js App Router)
src/ ├── app/ # App Router pages │ ├── (auth)/ # Route group: auth pages │ │ ├── login/ │ │ └── register/ │ ├── (dashboard)/ # Route group: authenticated │ │ ├── layout.tsx │ │ └── settings/ │ ├── api/ # API routes │ │ └── users/ │ ├── layout.tsx # Root layout │ ├── page.tsx # Home page │ └── globals.css ├── components/ # Shared components │ ├── ui/ # Base UI components (buttons, inputs) │ ├── forms/ # Form components │ ├── layouts/ # Layout components │ └── features/ # Feature-specific components ├── lib/ # Utilities and configurations │ ├── api.ts # API client │ ├── auth.ts # Auth utilities │ └── utils.ts # Helper functions ├── hooks/ # Custom React hooks ├── stores/ # State management (Zustand) ├── types/ # TypeScript types └── styles/ # Global styles (if not using Tailwind)
### Alternative: Pages Router / Vite
src/ ├── pages/ # Page components (Pages Router) ├── components/ ├── features/ # Feature-based organization │ └── users/ │ ├── components/ │ ├── hooks/ │ ├── api.ts │ └── types.ts ├── lib/ ├── hooks/ └── stores/
### Key Patterns
- **Server Components**: Default for data fetching, use `'use client'` for interactivity
- **Colocation**: Keep related files together (component + styles + tests)
- **Composition**: Small, composable components over large monolithic ones
- **Custom Hooks**: Extract reusable logic into hooks
### Data Flow
Server Component → fetch data → pass to Client Component as props ↓ Client Component → useState/useStore → UI updates ↓ User action → Server Action / API call → revalidate → refresh
## Conventions
### Naming
| Type | Convention | Example |
|------|------------|---------|
| Components | PascalCase | `UserProfile.tsx` |
| Hooks | camelCase + use prefix | `useUserData.ts` |
| Utilities | camelCase | `formatDate.ts` |
| Types | PascalCase | `UserProfileProps` |
| Constants | SCREAMING_SNAKE | `MAX_FILE_SIZE` |
| CSS classes | kebab-case (BEM optional) | `user-profile__avatar` |
### Component Structure
// 1. Imports (external → internal → relative → types) import { useState } from 'react'; import { Button } from '@/components/ui/button'; import { formatDate } from '@/lib/utils'; import type { User } from '@/types';
// 2. Types interface UserCardProps { user: User; onEdit?: () => void; }
// 3. Component export function UserCard({ user, onEdit }: UserCardProps) { const [isExpanded, setIsExpanded] = useState(false);
return ( <div className="user-card"> {/ JSX /} </div> ); }
// 4. Sub-components (if small and tightly coupled) function UserAvatar({ src }: { src: string }) { return <img src={src} alt="" className="avatar" />; }
### File Organization
- One component per file (except small sub-components)
- Barrel exports via `index.ts` in component directories
- Tests co-located as `ComponentName.test.tsx`
- Styles co-located as `ComponentName.module.css` (if using CSS Modules)
## Key Files
| Purpose | Location | Notes |
|---------|----------|-------|
| Root layout | `src/app/layout.tsx` | HTML structure, providers |
| Home page | `src/app/page.tsx` | Landing page |
| API routes | `src/app/api/` | Backend endpoints |
| UI components | `src/components/ui/` | shadcn/ui or custom |
| API client | `src/lib/api.ts` | fetch wrapper |
| Auth | `src/lib/auth.ts` | NextAuth / custom |
| Global styles | `src/app/globals.css` | Tailwind base |
| Tailwind config | `tailwind.config.ts` | Theme, plugins |
| Types | `src/types/index.ts` | Shared type definitions |
## Configuration
### Environment Variables
.env.local
NEXT_PUBLIC_API_URL=http://localhost:3001 NEXT_PUBLIC_APP_URL=http://localhost:3000
Server-only (no NEXT_PUBLIC_ prefix)
DATABASE_URL=postgresql://... NEXTAUTH_SECRET=your-secret NEXTAUTH_URL=http://localhost:3000
### Next.js Config
// next.config.js /* @type {import('next').NextConfig} / const nextConfig = { images: { domains: ['cdn.example.com'], }, experimental: { serverActions: true, }, };
## Commands
Development
npm run dev # Start dev server (localhost:3000) npm run build # Production build npm start # Start production server npm run lint # ESLint npm run lint:fix # Auto-fix lint issues
Testing
npm test # Run tests npm run test:watch # Watch mode npm run test:coverage # With coverage npm run test:e2e # Playwright E2E tests
Type checking
npm run typecheck # tsc --noEmit
Storybook (if used)
npm run storybook # Start Storybook npm run build-storybook # Build static Storybook
## Important Context
### Technical Decisions
#### [Why App Router over Pages Router]
**Context**: Starting new Next.js 16 project
**Decision**: App Router for Server Components and better data fetching
**Trade-off**: Steeper learning curve, some ecosystem packages not updated
#### [Why Zustand over Redux]
**Context**: Need simple global state
**Decision**: Zustand for minimal boilerplate and hooks-based API
**Trade-off**: Less middleware ecosystem than Redux
### Known Gotchas
- **Server vs Client Components**: Default is server; add `'use client'` for hooks/interactivity
- **Hydration errors**: Ensure server and client render the same initial content
- **Image optimization**: Use `next/image` for automatic optimization, configure domains
- **API routes caching**: Next.js caches by default, use `export const dynamic = 'force-dynamic'`
- **Tailwind purge**: Ensure all class names are complete strings (not dynamic)
### Historical Context
- [Any migrations, refactors, or legacy patterns to know about]
## Component Patterns
### Server Component (default)
// app/users/page.tsx async function UsersPage() { const users = await fetchUsers(); // Direct async fetch
return <UserList users={users} />; }
### Client Component
// components/UserForm.tsx 'use client';
import { useState } from 'react';
export function UserForm() { const [name, setName] = useState(''); // Interactive logic }
### Server Action
// app/actions.ts 'use server';
export async function createUser(formData: FormData) { const name = formData.get('name'); await db.user.create({ data: { name } }); revalidatePath('/users'); }
## Testing
### Component Test
// components/Button.test.tsx import { render, screen } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { Button } from './Button';
describe('Button', () => { it('calls onClick when clicked', async () => { const onClick = vi.fn(); render(<Button onClick={onClick}>Click me</Button>);
await userEvent.click(screen.getByRole('button'));
expect(onClick).toHaveBeenCalledOnce(); }); });
## For AI Assistants
### When modifying this codebase:
- Check if component should be Server or Client
- Use existing UI components from `components/ui/`
- Follow Tailwind utility class patterns
- Add types for all props and state
- Run `npm run lint && npm run typecheck` before committing
### Patterns to follow:
- Server Components for data fetching
- Client Components only when needed (hooks, events)
- Composition over prop drilling
- Custom hooks for reusable logic
- Zod schemas for form validation
### Avoid:
- `useEffect` for data fetching (use Server Components or React Query)
- Inline styles (use Tailwind)
- Large monolithic components
- Direct DOM manipulation
- `any` type---
Quick Start Commands
Run these to gather context for a new React/Next.js project:
# Basic structure
tree -L 3 -I 'node_modules|.next|.git|coverage|.turbo'
# Package info
cat package.json | jq '{dependencies, devDependencies}'
# Next.js or Vite config
cat next.config.js 2>/dev/null || cat vite.config.ts 2>/dev/null
# Check for App Router vs Pages Router
ls src/app 2>/dev/null && echo "App Router" || ls src/pages 2>/dev/null && echo "Pages Router"
# Find components
find src/components -name "*.tsx" | head -20
# Check styling approach
cat tailwind.config.* 2>/dev/null && echo "Tailwind detected"
find src -name "*.module.css" | head -5 && echo "CSS Modules detected"# Technical Specification Template
*Purpose: Copy-paste template for a concise, operational technical spec for GenAI/agentic or standard software projects. Use this to define system design, data flows, interfaces, and validation/monitoring plans before implementation begins.*
---
## When to Use
Use this template when:
- Detailing how a feature/requirement from the PRD will be built
- Specifying system changes for agentic/AI-driven implementations
- Aligning engineers, agents, and reviewers on architecture, APIs, data flows, and QA
---
## Structure
This template has 6 sections:
1. **Overview**
2. **Architecture & Data Flow**
3. **APIs & Interfaces**
4. **Error Handling & Edge Cases**
5. **Validation & Monitoring**
6. **Risks & Rollback**
---
# TEMPLATE STARTS HERE
## 1. Overview
_1–2 sentences: What is being built? What problem/requirement does it address?_
> Example:
> Implement a new `/status` API endpoint that returns all user task statuses in real time, supporting the dashboard status indicator PRD goal.
---
## 2. Architecture & Data Flow
**Diagram or list showing components and data flow.**
_Specify how agents, LLMs, or system modules interact, what data moves where, and key transformations._
> Example:
- Client → `/status` API → Task service → DB
- LLM/agent updates data via `/update-task` webhook
---
## 3. APIs & Interfaces
| Name | Endpoint/Method | Input | Output | Notes |
|--------------|--------------------------|------------------------|------------------------|----------------------|
| Get Status | `GET /status` | `{userId}` | `[{taskId, status}]` | Auth required |
| Update Task | `POST /update-task` | `{taskId, newStatus}` | `{success}` | Called by agent/LLM |
- **Data models/schemas:**
- `Task`: `{taskId, status, ...}`
- **Auth/permissions:**
- JWT or API key, as needed
---
## 4. Error Handling & Edge Cases
**What can go wrong, and what should the system do?**
- [ ] Invalid input (missing/invalid fields)
- [ ] Unauthorized access
- [ ] Downstream service failure (DB/API timeout)
- [ ] Race conditions, concurrent updates
- [ ] Edge cases (no tasks, deleted tasks, malformed agent payloads)
- [ ] Rollback/compensating actions on failure
---
## 5. Validation & Monitoring
**How do you test, monitor, and confirm this works in production?**
- [ ] Unit & integration tests: API, data updates, error handling
- [ ] Acceptance criteria mapping (from PRD)
- [ ] Monitoring/alerts for failures, latency, status mismatches
- [ ] Log/trace agent activity and errors
- [ ] Success metrics (e.g., endpoint error rate <0.5%, p95 latency <2s)
---
## 6. Risks & Rollback
**Known risks:**
- [ ] Possible breaking changes for legacy clients?
- [ ] Agent/LLM may generate unexpected data or malformed payloads
- [ ] Data consistency or sync delays
**Rollback plan:**
- [ ] Can changes be reverted quickly (feature flag, config switch)?
- [ ] Data migration/backfill, if needed
- [ ] Alerting on issues post-deploy
---
# COMPLETE EXAMPLE
## 1. Overview
Add `/status` endpoint to support dashboard task indicators; handles live status fetches and agent updates.
## 2. Architecture & Data Flow
- Dashboard → `/status` (API server) → Task DB
- Agent system calls `/update-task` after task state changes
- Error flows logged to monitoring
## 3. APIs & Interfaces
| Name | Endpoint/Method | Input | Output | Notes |
|--------------|------------------------|---------------|--------------------|----------------------|
| Get Status | `GET /status` | `userId` | `[{id, status}]` | JWT auth |
| Update Task | `POST /update-task` | `taskId, status` | `{ok}` | Agent-only |
- Task: `{id, status, updatedAt}`
- Auth: Required for all endpoints
## 4. Error Handling & Edge Cases
- 400: missing/invalid input
- 401: unauthorized
- 5xx: log, auto-retry agent update if transient
- Edge: user has no tasks, deleted tasks
## 5. Validation & Monitoring
- Tests: mock agent, all error paths, data races
- Alerts: 5xx spike, status mismatch, high latency
- Metrics: Error rate <0.5%, median latency <1.5s
## 6. Risks & Rollback
- Risk: Agent sending corrupted status; will validate all fields and log rejects
- Rollback: Toggle feature flag, revert to static status if issues detected
---
## Quality Checklist
Before finalizing:
- [ ] All endpoints, data flows, and error paths documented
- [ ] Edge cases/risks are explicit
- [ ] Monitoring/rollback steps are clear
- [ ] Links to PRD and requirements included
- [ ] Copy-paste tested by team or agent# Gherkin Example Template
*Purpose: Copy-paste template for writing Given-When-Then (Gherkin) scenarios for AI/agentic or standard projects. Use for executable specs, automated acceptance tests, or to drive clear agentic story breakdowns.*
---
## When to Use
Use this template when:
- Defining acceptance criteria for features, stories, or API changes
- Aligning team and agents on expected system behaviors and edge cases
- Enabling automation (BDD, Spec by Example, agent-driven QA)
---
## Structure
Each scenario includes:
- **Title**
- **Given** (context/setup)
- **When** (action/event)
- **Then** (expected outcome)
---
# TEMPLATE STARTS HERE
## Scenario: [Feature or User Story Name]
**Given** [initial system state, user, or precondition]
**And** [additional preconditions if needed]
**When** [user or agent performs an action/event]
**Then** [expected result/output/state change]
**And** [additional outcome/validation, if any]
---
### Example 1: Dashboard Task Status
Scenario: User sees task status update after completion
Given a user is logged in and sees the dashboard And they have a list of pending tasks When the user marks a task as completed Then the dashboard shows a green status icon for that task And the task moves to the "Completed" section
---
### Example 2: API Error Handling
Scenario: Agent receives error on invalid input
Given the agent is connected to the /update-task API And sends a request with a missing taskId When the API processes the request Then it responds with a 400 error code And the error message is "Missing required field: taskId"
---
### Example 3: Accessibility Check
Scenario: Status indicator passes accessibility test
Given the dashboard shows a status indicator for each task When a screen reader inspects the status icon Then it reads out "Task completed" or "Task pending" with correct ARIA labels
---
## Acceptance Checklist
- [ ] Each scenario has clear Given, When, Then steps
- [ ] Covers both happy path and at least one edge case/unhappy path
- [ ] Steps are executable (manually or by automation/agent)
- [ ] All requirements/criteria in the PRD or story are covered
---
## Quality Checklist
Before sharing or using:
- [ ] Gherkin is copy-paste ready (no placeholders, ambiguous steps)
- [ ] Scenarios reviewed for completeness and testability
- [ ] Ready for agentic, human, or automated execution