diff --git a/CLAUDE.md b/CLAUDE.md index f0423f5470..9f881be344 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,59 +1,242 @@ -### πŸ”„ Project Awareness & Context -- **Always read `PLANNING.md`** at the start of a new conversation to understand the project's architecture, goals, style, and constraints. -- **Check `TASK.md`** before starting a new task. If the task isn’t listed, add it with a brief description and today's date. -- **Use consistent naming conventions, file structure, and architecture patterns** as described in `PLANNING.md`. -- **Use venv_linux** (the virtual environment) whenever executing Python commands, including for unit tests. - -### 🧱 Code Structure & Modularity -- **Never create a file longer than 500 lines of code.** If a file approaches this limit, refactor by splitting it into modules or helper files. -- **Organize code into clearly separated modules**, grouped by feature or responsibility. - For agents this looks like: - - `agent.py` - Main agent definition and execution logic - - `tools.py` - Tool functions used by the agent - - `prompts.py` - System prompts -- **Use clear, consistent imports** (prefer relative imports within packages). -- **Use clear, consistent imports** (prefer relative imports within packages). -- **Use python_dotenv and load_env()** for environment variables. - -### πŸ§ͺ Testing & Reliability -- **Always create Pytest unit tests for new features** (functions, classes, routes, etc). -- **After updating any logic**, check whether existing unit tests need to be updated. If so, do it. -- **Tests should live in a `/tests` folder** mirroring the main app structure. - - Include at least: - - 1 test for expected use - - 1 edge case - - 1 failure case - -### βœ… Task Completion -- **Mark completed tasks in `TASK.md`** immediately after finishing them. -- Add new sub-tasks or TODOs discovered during development to `TASK.md` under a β€œDiscovered During Work” section. - -### πŸ“Ž Style & Conventions -- **Use Python** as the primary language. -- **Follow PEP8**, use type hints, and format with `black`. -- **Use `pydantic` for data validation**. -- Use `FastAPI` for APIs and `SQLAlchemy` or `SQLModel` for ORM if applicable. -- Write **docstrings for every function** using the Google style: +# 🎯 Context Engineering Template - Global Rules for AI Assistants + +This repository is a comprehensive template for **Context Engineering** - the discipline of engineering context for AI coding assistants. This CLAUDE.md file provides global instructions that AI assistants should follow when working in this repository. + +## πŸ“‹ Repository Structure + +This is a **template repository** with multiple use cases demonstrating context engineering patterns: + +``` +context-engineering-intro/ +β”œβ”€β”€ .claude/ +β”‚ └── commands/ # Slash commands for workflows +β”‚ β”œβ”€β”€ generate-prp.md # Generate Product Requirements Prompts +β”‚ └── execute-prp.md # Execute PRPs to implement features +β”œβ”€β”€ PRPs/ # Product Requirements Prompts +β”‚ β”œβ”€β”€ templates/ +β”‚ β”‚ └── prp_base.md # Base PRP template +β”‚ └── EXAMPLE_*.md # Example PRPs +β”œβ”€β”€ examples/ # Code examples (add your own) +β”œβ”€β”€ use-cases/ # Specialized use case templates +β”‚ β”œβ”€β”€ pydantic-ai/ # Building PydanticAI agents +β”‚ β”œβ”€β”€ agent-factory-with-subagents/ # Multi-agent factory system +β”‚ β”œβ”€β”€ mcp-server/ # Building MCP servers +β”‚ β”œβ”€β”€ template-generator/ # Template generation +β”‚ └── ai-coding-workflows-foundation/ # AI workflow foundation +β”œβ”€β”€ claude-code-full-guide/ # Complete Claude Code documentation +β”œβ”€β”€ CLAUDE.md # This file - global rules +β”œβ”€β”€ INITIAL.md # Template for feature requests +β”œβ”€β”€ INITIAL_EXAMPLE.md # Example feature request +└── README.md # Getting started guide +``` + +## 🎯 Primary Workflow: PRP Pattern + +This repository implements the **PRP (Product Requirements Prompt) workflow** for systematic feature implementation: + +### Step 1: Create Feature Request (INITIAL.md) +Define what you want to build with: +- **FEATURE**: Detailed description of functionality +- **EXAMPLES**: Reference code patterns and existing files +- **DOCUMENTATION**: Links to relevant docs, APIs, libraries +- **OTHER CONSIDERATIONS**: Gotchas, requirements, edge cases + +### Step 2: Generate PRP +```bash +/generate-prp INITIAL.md +``` +This command: +1. Researches the codebase for similar patterns +2. Searches for relevant documentation +3. Creates a comprehensive implementation blueprint in `PRPs/` +4. Includes validation gates and test requirements + +### Step 3: Execute PRP +```bash +/execute-prp PRPs/your-feature-name.md +``` +This command: +1. Reads all context from the PRP +2. Creates detailed implementation plan (use TodoWrite tool) +3. Implements each step with validation +4. Runs tests and fixes issues +5. Ensures all success criteria are met + +## πŸ”„ Working with Use Cases + +Each use case in `use-cases/` has its own specialized context: + +- **When working in `use-cases/pydantic-ai/`**: Follow the PydanticAI-specific rules in that directory's CLAUDE.md +- **When working in `use-cases/agent-factory-with-subagents/`**: Follow the agent factory orchestration workflow +- **When working in `use-cases/mcp-server/`**: Follow MCP server development patterns +- **When at repository root**: Follow the general rules below + +## 🧱 Code Structure & Modularity + +- **Never create a file longer than 500 lines of code.** Refactor by splitting into modules when approaching this limit. +- **Organize code into clearly separated modules**, grouped by feature or responsibility: + - For **AI agents**: `agent.py`, `tools.py`, `prompts.py`, `models.py`, `dependencies.py` + - For **APIs**: `routes/`, `services/`, `models/`, `schemas/` + - For **libraries**: Logical module separation by feature +- **Use clear, consistent imports** (prefer relative imports within packages) +- **Use python-dotenv and load_dotenv()** for environment variables - never hardcode secrets +- **Create .env.example files** showing required environment variables + +## πŸ§ͺ Testing & Reliability + +- **Always create comprehensive tests** for new features using pytest +- **Tests should mirror the main structure** in a `/tests` folder +- **Include at least**: + - 1 test for expected/happy path + - 1 edge case test + - 1 failure/error case test +- **For AI agents**: Use TestModel/FunctionModel for testing without API calls +- **Run tests before marking tasks complete** + +## βœ… Task Management with TodoWrite + +- **Use TodoWrite tool proactively** for multi-step tasks to track progress +- **Create specific, actionable items** with clear completion criteria +- **Mark tasks completed immediately** after finishing them +- **Keep exactly ONE task in_progress** at any time +- **Include both forms** for each task: + - `content`: Imperative form ("Run tests", "Build feature") + - `activeForm`: Present continuous ("Running tests", "Building feature") + +## πŸ“Ž Style & Conventions + +### Python (Primary Language) +- **Follow PEP8** with type hints throughout +- **Use `pydantic` for data validation** and settings management +- **Use `black` for formatting** (or ruff format) +- **Write docstrings for every function** using Google style: ```python - def example(): + def example(param1: str) -> dict: """ - Brief summary. + Brief summary of what function does. Args: - param1 (type): Description. + param1: Description of parameter. Returns: - type: Description. + Description of return value. """ ``` -### πŸ“š Documentation & Explainability -- **Update `README.md`** when new features are added, dependencies change, or setup steps are modified. -- **Comment non-obvious code** and ensure everything is understandable to a mid-level developer. -- When writing complex logic, **add an inline `# Reason:` comment** explaining the why, not just the what. +### Security Best Practices +- **Never hardcode API keys or secrets** +- **Always use .env files** with python-dotenv +- **Validate all external inputs** using Pydantic models +- **Implement proper error handling** without exposing sensitive information + +## πŸ“š Documentation & Explainability + +- **Update README.md** when features are added or setup steps change +- **Comment non-obvious code** for mid-level developer understanding +- **Add inline `# Reason:` comments** for complex logic explaining the "why" +- **Create comprehensive PRPs** with all necessary context for one-pass implementation +- **Include validation gates** in PRPs (executable commands that must pass) + +## 🧠 AI Assistant Behavior Rules + +### Context Engineering Principles +- **Always use the PRP workflow** for complex features (3+ steps) +- **Research extensively** before generating PRPs: + - Search codebase for similar patterns + - Find relevant documentation online + - Identify integration points and gotchas +- **Include ALL necessary context** in PRPs: + - Documentation URLs with specific sections + - Code examples from the codebase + - Library quirks and version-specific issues + - Existing patterns to follow + +### General Behavior +- **Never assume missing context** - ask clarifying questions +- **Never hallucinate libraries or functions** - only use verified packages +- **Always confirm file paths exist** before referencing them +- **Never delete or overwrite code** unless explicitly instructed +- **Avoid over-engineering**: + - Don't add unrequested features + - Don't create abstractions for one-time operations + - Don't add error handling for impossible scenarios + - Keep solutions simple and focused +- **Use specialized tools over bash** when available (Read, Edit, Write, Glob, Grep) +- **Use the Explore agent** for codebase exploration rather than direct searches + +### Proactive Tool Usage +- **Use TodoWrite** for multi-step tasks to track progress +- **Use Task tool with Explore agent** for codebase questions +- **Use WebSearch** for researching documentation and best practices +- **Use parallel tool calls** when operations are independent + +## 🎨 Context Engineering Best Practices + +### When Creating PRPs +1. **Be explicit and comprehensive** - don't assume the AI knows preferences +2. **Provide many examples** - show what to do AND what not to do +3. **Include validation gates** - executable tests that must pass +4. **Reference documentation** - specific URLs and sections +5. **Document gotchas** - library quirks, common pitfalls, version issues + +### When Executing PRPs +1. **Read the entire PRP first** - understand all context and requirements +2. **Create detailed plan with TodoWrite** - break down into manageable steps +3. **Follow patterns from examples** - don't invent new approaches +4. **Run validation gates** - iterate until all tests pass +5. **Verify success criteria** - ensure all requirements met + +## πŸ” Slash Commands Reference + +Custom commands available in `.claude/commands/`: + +- **`/generate-prp INITIAL.md`** - Generate comprehensive Product Requirements Prompt +- **`/execute-prp PRPs/feature.md`** - Execute PRP to implement feature +- Use case-specific commands may be available in `use-cases/*/. claude/commands/` + +## 🚨 Important Anti-Patterns to Avoid + +### NEVER: +- ❌ Skip the PRP workflow for complex features +- ❌ Hardcode API keys, secrets, or sensitive data +- ❌ Create files without reading similar existing files first +- ❌ Skip testing phases or mark tasks complete with failing tests +- ❌ Ignore validation gates in PRPs +- ❌ Over-engineer with unnecessary abstractions +- ❌ Add backwards-compatibility hacks for unused code +- ❌ Create PLANNING.md or TASK.md files (use TodoWrite tool instead) +- ❌ Commit to implementing before understanding requirements + +### ALWAYS: +- βœ… Use environment variables via python-dotenv +- βœ… Create comprehensive tests for new features +- βœ… Follow existing code patterns and conventions +- βœ… Document implementation decisions +- βœ… Validate against requirements before marking complete +- βœ… Use TodoWrite for task tracking on multi-step features +- βœ… Ask clarifying questions when requirements are unclear + +## πŸ“– Learning Resources + +- **README.md** - Quick start guide and overview +- **claude-code-full-guide/README.md** - Complete Claude Code documentation +- **PRPs/templates/prp_base.md** - Template for creating PRPs +- **PRPs/EXAMPLE_*.md** - Example PRPs showing best practices +- **use-cases/** - Specialized templates for different use cases + +## πŸŽ“ Using This Template + +This repository serves as both: +1. **A template** - Fork or copy for your own projects +2. **A learning resource** - Study the patterns and workflows +3. **A use case library** - Explore specialized implementations + +When starting a new project: +1. Copy relevant files (CLAUDE.md, INITIAL.md, .claude/commands/) +2. Customize for your tech stack and conventions +3. Add your own examples to the `examples/` directory +4. Create PRPs for your features using the workflow + +--- -### 🧠 AI Behavior Rules -- **Never assume missing context. Ask questions if uncertain.** -- **Never hallucinate libraries or functions** – only use known, verified Python packages. -- **Always confirm file paths and module names** exist before referencing them in code or tests. -- **Never delete or overwrite existing code** unless explicitly instructed to or if part of a task from `TASK.md`. \ No newline at end of file +**Remember**: Context Engineering is about providing AI assistants with **all the information they need** to implement features correctly on the first try. The more context you provide upfront, the better the results. \ No newline at end of file