### Feature Request with Examples and Docs Source: https://github.com/incomestreamsurfer/context-engineering-intro/blob/main/QUICKSTART.md This snippet demonstrates how to structure a feature request in INITIAL.md, including specifying examples and linking to relevant documentation. It guides the AI on the desired functionality, structure, and external resources. ```markdown ## FEATURE: Build a REST API for user authentication with JWT tokens ## EXAMPLES: See examples/auth_api.py for our standard API structure ## DOCUMENTATION: - FastAPI docs: https://fastapi.tiangolo.com/ - JWT best practices: [link] ## OTHER CONSIDERATIONS: - Must support refresh tokens - Use bcrypt for password hashing ``` -------------------------------- ### Execute Implementation Blueprint Source: https://github.com/incomestreamsurfer/context-engineering-intro/blob/main/QUICKSTART.md This command executes a previously generated implementation blueprint (PRP) file. The AI will then implement the described feature, adhering to all provided context, examples, and rules. ```shell /execute-prp PRPs/your-feature.md ``` -------------------------------- ### Start Claude Code CLI Source: https://github.com/incomestreamsurfer/context-engineering-intro/blob/main/SETUP.md Initiates the Claude Code command-line interface after hooks have been set up. ```bash claude ``` -------------------------------- ### OpenAI Client Initialization Example Source: https://github.com/incomestreamsurfer/context-engineering-intro/blob/main/SETUP.md Demonstrates initializing the OpenAI client in Python. This action triggers the documentation hook to provide relevant OpenAI API documentation to Claude. ```python from openai import OpenAI client = OpenAI() ``` -------------------------------- ### Clone Repository Source: https://github.com/incomestreamsurfer/context-engineering-intro/blob/main/SETUP.md Clones the context engineering intro project repository from GitHub and navigates into the project directory. ```bash git clone https://github.com/IncomeStreamSurfer/context-engineering-intro.git cd context-engineering-intro ``` -------------------------------- ### Generate Implementation Blueprint Source: https://github.com/incomestreamsurfer/context-engineering-intro/blob/main/QUICKSTART.md This command initiates the process of generating a comprehensive implementation blueprint (PRP) based on a feature request defined in an INITIAL.md file. It's a core step in the AI-assisted development workflow. ```shell /generate-prp INITIAL.md ``` -------------------------------- ### Project Setup and Workflow Commands Source: https://github.com/incomestreamsurfer/context-engineering-intro/blob/main/README.md Provides essential bash commands for setting up the context engineering template project. This includes cloning the repository, configuring project rules, adding examples, defining initial feature requests, and generating/executing Product Requirements Prompts (PRPs) using custom Claude Code commands. ```bash git clone https://github.com/IncomeStreamSurfer/context-engineering-intro.git cd context-engineering-intro # Set up your project rules (optional - template provided) # Edit CLAUDE.md to add your project-specific guidelines # Add examples (highly recommended) # Place relevant code examples in the examples/ folder # Create your initial feature request # Edit INITIAL.md with your feature requirements # Generate a comprehensive PRP (Product Requirements Prompt) # In Claude Code, run: /generate-prp INITIAL.md # Execute the PRP to implement your feature # In Claude Code, run: /execute-prp PRPs/your-feature-name.md ``` -------------------------------- ### Project Structure: Current vs. Desired Source: https://github.com/incomestreamsurfer/context-engineering-intro/blob/main/PRPs/EXAMPLE_multi_agent_prp.md Illustrates the evolution of the project's directory structure, moving from an initial setup with examples to a more organized, modular architecture for agents, tools, configuration, and tests. ```bash Current Codebase tree: ```bash . ├── examples/ │ ├── agent/ │ │ ├── agent.py │ │ ├── providers.py │ │ └── ... │ └── cli.py ├── PRPs/ │ └── templates/ │ └── prp_base.md ├── INITIAL.md ├── CLAUDE.md └── requirements.txt ``` ``` ```bash Desired Codebase tree with files to be added: ```bash . ├── agents/ │ ├── __init__.py # Package init │ ├── research_agent.py # Primary agent with Brave Search │ ├── email_agent.py # Sub-agent with Gmail capabilities │ ├── providers.py # LLM provider configuration │ └── models.py # Pydantic models for data validation ├── tools/ │ ├── __init__.py # Package init │ ├── brave_search.py # Brave Search API integration │ └── gmail_tool.py # Gmail API integration ├── config/ │ ├── __init__.py # Package init │ └── settings.py # Environment and config management ├── tests/ │ ├── __init__.py # Package init │ ├── test_research_agent.py # Research agent tests │ ├── test_email_agent.py # Email agent tests │ ├── test_brave_search.py # Brave search tool tests │ ├── test_gmail_tool.py # Gmail tool tests │ └── test_cli.py # CLI tests ├── cli.py # CLI interface ├── .env.example # Environment variables template ├── requirements.txt # Updated dependencies ├── README.md # Comprehensive documentation └── credentials/.gitkeep # Directory for Gmail credentials ``` ``` -------------------------------- ### Initial Feature Request Markdown Structure Source: https://github.com/incomestreamsurfer/context-engineering-intro/blob/main/README.md Illustrates the recommended markdown structure for defining initial feature requests in the `INITIAL.md` file. This structure guides the AI by specifying the feature, referencing relevant examples, providing necessary documentation links, and highlighting other important considerations. ```markdown ## FEATURE: [Describe what you want to build - be specific about functionality and requirements] ## EXAMPLES: [List any example files in the examples/ folder and explain how they should be used] ## DOCUMENTATION: [Include links to relevant documentation, APIs, or MCP server resources] ## OTHER CONSIDERATIONS: [Mention any gotchas, specific requirements, or things AI assistants commonly miss] ``` -------------------------------- ### Start Development Service Source: https://github.com/incomestreamsurfer/context-engineering-intro/blob/main/PRPs/templates/prp_base.md Starts the application service in development mode using the 'uv' command and Python. This command is typically used to run the main application entry point. ```bash uv run python -m src.main --dev ``` -------------------------------- ### Enable Claude Code Hooks Source: https://github.com/incomestreamsurfer/context-engineering-intro/blob/main/SETUP.md Copies the project's pre-configured Claude settings file to the user's Claude configuration directory, enabling custom hooks. ```bash cp .claude/settings.json ~/.claude/settings.json ``` -------------------------------- ### Python Docstring Example Source: https://github.com/incomestreamsurfer/context-engineering-intro/blob/main/CLAUDE.md Illustrates the required Google-style docstring format for functions, including brief summary, arguments with types, and return values with types. This standard ensures code clarity and maintainability. ```Python def example(param1: str, param2: int) -> bool: """ Brief summary of the function's purpose. Args: param1 (str): Description of the first parameter. param2 (int): Description of the second parameter. Returns: bool: Description of the return value. """ # Function implementation here pass ``` -------------------------------- ### OpenRouter API Documentation Reference Source: https://github.com/incomestreamsurfer/context-engineering-intro/blob/main/PRPs/ai-powered-crm-system.md Provides a reference to the OpenRouter API documentation, covering quickstart guides, authentication, model selection, and function calling capabilities. This serves as a primary resource for integrating with various AI models. ```APIDOC OpenRouter API Documentation: URL: https://openrouter.ai/docs/quickstart Sections: - Quickstart Guide - Authentication Setup - Model Selection - Function Calling Purpose: This documentation provides comprehensive details on how to interact with the OpenRouter API, enabling access to a wide range of AI models. It covers essential setup, authentication mechanisms, and advanced features like model selection and function calling for building AI-powered applications. ``` -------------------------------- ### Example Research Directory Structure Source: https://github.com/incomestreamsurfer/context-engineering-intro/blob/main/research/README.md Illustrates a typical organization for a research directory used in context engineering. It categorizes documentation and examples by technology or framework, such as OpenAI API, MongoDB, Node.js, and Docker, to facilitate systematic information gathering for AI models. ```shell research/ ├── openai/ # OpenAI API documentation │ ├── chat-completions.md │ ├── models.md │ └── examples/ ├── mongodb/ # MongoDB documentation │ ├── queries.md │ ├── schemas.md │ └── aggregation.md ├── nodejs/ # Node.js patterns │ ├── express-routing.md │ ├── middleware.md │ └── error-handling.md └── docker/ # Docker best practices ├── compose.md └── networking.md ``` -------------------------------- ### OpenRouter API Quickstart & Authentication Source: https://github.com/incomestreamsurfer/context-engineering-intro/blob/main/PRPs/ai-powered-crm-system.md Provides guidance on OpenRouter API authentication and basic integration patterns. This is essential for establishing initial connectivity and understanding fundamental API usage. ```APIDOC OpenRouter API Quickstart: __authentication__ - API Key management and secure credential handling. __basic_integration__ - Initial API call examples. - Request/response structure overview. __dependencies__ - Requires valid OpenRouter API key. __related_docs__ - research/openrouter/RESEARCH_SUMMARY.md: Overall research summary and model details. ``` -------------------------------- ### Start Frontend Development Server Source: https://github.com/incomestreamsurfer/context-engineering-intro/blob/main/PRPs/ai-powered-crm-system.md Starts a simple HTTP server using Python's built-in module to serve static files for the frontend. This is typically used during development to test the frontend application locally. ```bash # Start frontend development server cd frontend python -m http.server 8080 # Simple HTTP server for static files ``` -------------------------------- ### Unit Tests Source: https://github.com/incomestreamsurfer/context-engineering-intro/blob/main/PRPs/EXAMPLE_multi_agent_prp.md Example unit tests for research and email agents, demonstrating functionality like searching and drafting emails. These tests use pytest and cover agent logic. ```python # test_research_agent.py async def test_research_with_brave(): """Test research agent searches correctly""" agent = create_research_agent() result = await agent.run("AI safety research") assert result.data assert len(result.data) > 0 async def test_research_creates_email(): """Test research agent can invoke email agent""" agent = create_research_agent() result = await agent.run( "Research AI safety and draft email to john@example.com" ) assert "draft_id" in result.data # test_email_agent.py def test_gmail_authentication(monkeypatch): """Test Gmail OAuth flow handling""" monkeypatch.setenv("GMAIL_CREDENTIALS_PATH", "test_creds.json") tool = GmailTool() assert tool.service is not None async def test_create_draft(): """Test draft creation with proper encoding""" agent = create_email_agent() result = await agent.run( "Create email to test@example.com about AI research" ) assert result.data.get("draft_id") ``` -------------------------------- ### Backend and Frontend Setup Source: https://github.com/incomestreamsurfer/context-engineering-intro/blob/main/PRPs/ai-powered-crm-system.md Defines the core technologies and file structure for the backend and frontend. Includes Express, Mongoose, JWT for backend, and Tailwind CSS, ES6 modules for frontend. ```yaml Task 1: Environment Setup and Project Structure CREATE backend/package.json: - EXPRESS framework with Socket.IO for real-time features - MONGOOSE for MongoDB object modeling - JSONWEBTOKEN for authentication - BCRYPTJS for password hashing - AXIOS for OpenRouter API integration - CORS for frontend-backend communication - DOTENV for environment variable management CREATE frontend file structure: - ORGANIZE HTML files for marketing, dashboard, and authentication - SETUP Tailwind CSS for utility-first styling - CREATE ES6 module structure for component-like architecture CREATE .env.example: - INCLUDE all required environment variables - DOCUMENT OpenRouter API key, MongoDB URI, JWT secrets - SET proper development and production configurations ``` -------------------------------- ### Codebase Quirks and Gotchas Source: https://github.com/incomestreamsurfer/context-engineering-intro/blob/main/PRPs/templates/prp_base.md A placeholder for critical notes regarding library-specific requirements, common pitfalls, or known limitations within the project's codebase. Examples include FastAPI's async requirements or ORM batch insert limits. ```python # CRITICAL: [Library name] requires [specific setup] # Example: FastAPI requires async functions for endpoints # Example: This ORM doesn't support batch inserts over 1000 records # Example: We use pydantic v2 and ``` -------------------------------- ### Database Configuration and Indexing Source: https://github.com/incomestreamsurfer/context-engineering-intro/blob/main/PRPs/ai-powered-crm-system.md Details the setup for MongoDB connection using Mongoose, including connection pooling, error handling, and the creation of performance-enhancing database indexes for various query types. ```yaml Task 2: MongoDB Database Setup and Connection CREATE config/database.js: - ESTABLISH MongoDB connection with Mongoose - CONFIGURE connection pooling for production performance - IMPLEMENT connection error handling and retry logic - CREATE database initialization and seeding scripts CREATE MongoDB indexes: - IMPLEMENT performance indexes for CRM queries - UNIQUE index on user emails and customer emails - COMPOUND indexes for task queries by assignedTo + status + priority - INDEX pipeline stages for automation performance ``` -------------------------------- ### Initialize Research Framework with Jina Scrape Source: https://github.com/incomestreamsurfer/context-engineering-intro/blob/main/README.md This shell command initiates the research process by instructing a tool (likely Jina AI) to scrape documentation from a specified URL. It includes authorization details and instructions for handling errors like 404s, emphasizing the storage of separate pages into technology-specific directories. ```shell curl \ "https://r.jina.ai/https://platform.openai.com/docs/" \ -H "Authorization: Bearer jina_033257e7cdf14fd3b948578e2d34986bNtfCCkjHt7_j1Bkp5Kx521rDs2Eb" ``` -------------------------------- ### Syntax and Style Validation Commands Source: https://github.com/incomestreamsurfer/context-engineering-intro/blob/main/PRPs/templates/prp_base.md Lists the bash commands for performing initial syntax and style checks on new code. It includes running linters like 'ruff' for auto-fixing and type checkers like 'mypy' to ensure code quality. ```bash # Run these FIRST - fix any errors before proceeding ruff check src/new_feature.py --fix # Auto-fix what's possible mypy src/new_feature.py # Type checking # Expected: No errors. If errors, READ the error and fix. ``` -------------------------------- ### Project Validation Commands Source: https://github.com/incomestreamsurfer/context-engineering-intro/blob/main/PRPs/templates/prp_base.md A set of commands used for comprehensive project validation, including running all tests, checking for linting errors, and verifying type correctness. ```bash uv run pytest tests/ -v ``` ```bash uv run ruff check src/ ``` ```bash uv run mypy src/ ``` -------------------------------- ### Task Implementation Blueprint Source: https://github.com/incomestreamsurfer/context-engineering-intro/blob/main/PRPs/templates/prp_base.md Outlines the structured approach for completing tasks, including modifying existing files and creating new ones. It specifies patterns to mirror, modifications needed, and preservation of existing signatures and error handling. ```yaml ```yaml Task 1: MODIFY src/existing_module.py: - FIND pattern: "class OldImplementation" - INJECT after line containing "def __init__" - PRESERVE existing method signatures CREATE src/new_feature.py: - MIRROR pattern from: src/similar_feature.py - MODIFY class name and core logic - KEEP error handling pattern identical ...(...) Task N: ... ``` ``` -------------------------------- ### Run Backend Linting and Formatting Source: https://github.com/incomestreamsurfer/context-engineering-intro/blob/main/PRPs/ai-powered-crm-system.md Commands to check code quality and format the backend project using ESLint and Prettier. These steps should be performed first to ensure code adheres to project standards. ```bash cd backend npm run lint npm run format npm run test:syntax ``` -------------------------------- ### Pseudocode for New Feature Implementation Source: https://github.com/incomestreamsurfer/context-engineering-intro/blob/main/PRPs/templates/prp_base.md Provides pseudocode for implementing a new feature, detailing critical steps like input validation, database connection handling, API rate limiting, and response formatting. It highlights patterns and gotchas to follow. ```python # Task 1 # Pseudocode with CRITICAL details dont write entire code async def new_feature(param: str) -> Result: # PATTERN: Always validate input first (see src/validators.py) validated = validate_input(param) # raises ValidationError # GOTCHA: This library requires connection pooling async with get_connection() as conn: # see src/db/pool.py # PATTERN: Use existing retry decorator @retry(attempts=3, backoff=exponential) async def _inner(): # CRITICAL: API returns 429 if >10 req/sec await rate_limiter.acquire() return await external_api.call(validated) result = await _inner() # PATTERN: Standardized response format return format_response(result) # see src/utils/responses.py ``` -------------------------------- ### Node.js Backend & Socket.IO Integration Source: https://github.com/incomestreamsurfer/context-engineering-intro/blob/main/PRPs/ai-powered-crm-system.md Details the technical requirements for the backend, specifying Node.js with Express.js and MongoDB, integrated with real-time Socket.IO for live updates. This setup enables seamless communication for AI processing feedback. ```APIDOC Node.js Backend Stack: __frameworks__ - Node.js - Express.js __realtime_communication__ - Socket.IO for WebSocket connections. - Enables live updates and progress indicators during AI processing. __database__ - MongoDB with optimized schemas for CRM workflows. __authentication__ - JWT-based authentication. __performance_goal__ - Real-time AI processing with progress feedback <2 seconds response time. __related_technologies__ - MongoDB: Database integration. - OpenRouter API: AI model integration. ``` -------------------------------- ### Context Documentation Structure Source: https://github.com/incomestreamsurfer/context-engineering-intro/blob/main/PRPs/templates/prp_base.md Defines the structure for referencing external documentation, codebase files, and library documentation critical for AI agent implementation. It specifies the 'url', 'file', 'doc', and 'docfile' fields along with their 'why' or 'section' for context. ```yaml ```yaml # MUST READ - Include these in your context window - url: [Official API docs URL] why: [Specific sections/methods you'll need] - file: [path/to/example.py] why: [Pattern to follow, gotchas to avoid] - doc: [Library documentation URL] section: [Specific section about common pitfalls] critical: [Key insight that prevents common errors] - docfile: [PRPs/ai_docs/file.md] why: [docs that the user has pasted in to the project] ``` ``` -------------------------------- ### Integration Points Configuration Source: https://github.com/incomestreamsurfer/context-engineering-intro/blob/main/PRPs/templates/prp_base.md Details the necessary integration points for a new feature, covering database migrations, index creation, configuration file updates, and route inclusions. It specifies patterns for adding new settings and routing. ```yaml ```yaml DATABASE: - migration: "Add column 'feature_enabled' to users table" - index: "CREATE INDEX idx_feature_lookup ON users(feature_id)" CONFIG: - add to: config/settings.py - pattern: "FEATURE_TIMEOUT = int(os.getenv('FEATURE_TIMEOUT', '30'))" ROUTES: - add to: src/api/routes.py - pattern: "router.include_router(feature_router, prefix='/feature')" ``` ``` -------------------------------- ### Codebase Tree Command Source: https://github.com/incomestreamsurfer/context-engineering-intro/blob/main/PRPs/templates/prp_base.md Provides the bash command to generate a tree view of the current project's codebase. This is used to understand the project structure and identify relevant files for implementation. ```bash ```bash # Run `tree` in the root of the project ``` ``` -------------------------------- ### Generate PRP with Parallel Research Agents Source: https://github.com/incomestreamsurfer/context-engineering-intro/blob/main/README.md This snippet represents a command-line instruction to generate a PRP document based on an initial file. It also includes a conversational prompt to activate parallel research agents for simultaneous data gathering, a key feature of the advanced method. ```shell /generate-prp initial.md # Wait until it gets to the research phase, then press escape and say: can you spin up multiple research agents and do this all at the same time ``` -------------------------------- ### Project Codebase Structure Source: https://github.com/incomestreamsurfer/context-engineering-intro/blob/main/PRPs/ai-powered-crm-system.md Displays the directory structure of the project, outlining research directories for backend, frontend, and AI agent architectures, along with configuration and documentation files. ```bash .\n├── CLAUDE.md # Project instructions and coding guidelines\n├── initial.md # Feature requirements and API specifications\n├── PRPs/\n│ ├── templates/\n│ │ └── prp_base.md # PRP template structure\n│ └── EXAMPLE_multi_agent_prp.md # Multi-agent system example\n├── research/ # Comprehensive research documentation\n│ ├── pydantic-ai/ # AI agent architecture research (20 pages)\n│ ├── openrouter/ # Multi-model API research (23 pages)\n│ ├── nodejs-mongodb/ # Backend architecture research (15 pages)\n│ └── frontend-ai-ux/ # Frontend UX research (6 pages)\n└── tests/ # Test directory (empty)\n ``` -------------------------------- ### User Registration and Task Creation Workflow Source: https://github.com/incomestreamsurfer/context-engineering-intro/blob/main/PRPs/ai-powered-crm-system.md Demonstrates an integration test scenario using curl to simulate a user registration followed by a task creation workflow. This tests the end-to-end flow of user interaction with the API. ```bash # Start MongoDB (ensure it's running) mongod --dbpath ./data/db # Start the backend server in test mode NODE_ENV=test npm start # Test complete user workflows echo "Testing user registration and task creation workflow..." curl -X POST http://localhost:3000/api/auth/register \ -H "Content-Type: application/json" \ -d '{ "email": "integration@test.com", "password": "testPassword123", "firstName": "Integration", "lastName": "Test", "role": "sales" }' ``` -------------------------------- ### Execute PRP Command Source: https://github.com/incomestreamsurfer/context-engineering-intro/blob/main/README.md Executes the /execute-prp command to implement features based on a generated Product Requirements Prompt (PRP). The AI assistant reads the PRP, creates an implementation plan, executes steps, validates, and iterates until requirements are met. ```bash /execute-prp PRPs/your-feature-name.md ``` -------------------------------- ### Generate PRP Command Source: https://github.com/incomestreamsurfer/context-engineering-intro/blob/main/README.md Executes the /generate-prp command to create a Product Requirements Prompt (PRP) from an initial markdown file. This command researches the codebase, gathers documentation, and creates a comprehensive PRP. ```bash /generate-prp INITIAL.md ``` -------------------------------- ### Integration Test CLI Interaction Source: https://github.com/incomestreamsurfer/context-engineering-intro/blob/main/PRPs/EXAMPLE_multi_agent_prp.md Demonstrates how to test the command-line interface (CLI) by simulating user interactions and observing the assistant's responses and tool usage. ```bash # Test CLI interaction python cli.py # Expected interaction: You: Research latest AI safety developments 🤖 Assistant: [Streams research results] 🛠 Tools Used: 1. brave_search (query='AI safety developments', limit=10) You: Create an email draft about this to john@example.com 🤖 Assistant: [Creates draft] 🛠 Tools Used: 1. create_email_draft (recipient='john@example.com', ...) # Check Gmail drafts folder for created draft ``` -------------------------------- ### Run Pytest Tests Source: https://github.com/incomestreamsurfer/context-engineering-intro/blob/main/PRPs/templates/prp_base.md Executes pytest tests for a specific file with verbose output. This command is used for iterative testing during development to ensure code correctness. ```bash uv run pytest test_new_feature.py -v ``` -------------------------------- ### Environment Configuration Source: https://github.com/incomestreamsurfer/context-engineering-intro/blob/main/PRPs/EXAMPLE_multi_agent_prp.md Defines essential environment variables for LLM, Brave Search, and Gmail OAuth integration. These should be added to the project's .env file. ```yaml ENVIRONMENT: - add to: .env - vars: | # LLM Configuration LLM_PROVIDER=openai LLM_API_KEY=sk-... LLM_MODEL=gpt-4 # Brave Search BRAVE_API_KEY=BSA... # Gmail (path to credentials.json) GMAIL_CREDENTIALS_PATH=./credentials/credentials.json CONFIG: - Gmail OAuth: First run opens browser for authorization - Token storage: ./credentials/token.json (auto-created) DEPENDENCIES: - Update requirements.txt with: - google-api-python-client - google-auth-httplib2 - google-auth-oauthlib ``` -------------------------------- ### Unit Test Cases for New Feature Source: https://github.com/incomestreamsurfer/context-engineering-intro/blob/main/PRPs/templates/prp_base.md Defines essential unit test cases for a new feature, covering happy path scenarios, validation errors, and graceful handling of external API issues like timeouts. It uses pytest and mock for testing. ```python # CREATE test_new_feature.py with these test cases: def test_happy_path(): """Basic functionality works""" result = new_feature("valid_input") assert result.status == "success" def test_validation_error(): """Invalid input raises ValidationError""" with pytest.raises(ValidationError): new_feature("") def test_external_api_timeout(): """Handles timeouts gracefully""" with mock.patch('external_api.call', side_effect=TimeoutError): result = new_feature("valid") assert result.status == "error" assert "timeout" in result.message ``` -------------------------------- ### Project Directory Structure Source: https://github.com/incomestreamsurfer/context-engineering-intro/blob/main/PRPs/ai-powered-crm-system.md The overall file and directory layout for the IncomestreamSurfer project, indicating the organization of backend, frontend, testing, and configuration files. ```bash .\n├── backend/\n│ ├── package.json # Node.js dependencies and scripts\n│ ├── server.js # Express.js server setup and middleware\n│ ├── config/\n│ │ ├── database.js # MongoDB connection and configuration\n│ │ ├── auth.js # JWT authentication configuration\n│ │ └── openrouter.js # OpenRouter API client setup\n│ ├── models/\n│ │ ├── User.js # User authentication and profile schema\n│ │ ├── Customer.js # Customer/lead data schema\n│ │ ├── Task.js # Task and subtask schema with AI metadata\n│ │ └── Pipeline.js # Sales/marketing pipeline schema\n│ ├── routes/\n│ │ ├── auth.js # Authentication endpoints (login, register, refresh)\n│ │ ├── customers.js # Customer CRUD operations\n│ │ ├── tasks.js # Task management with AI generation endpoints\n│ │ ├── pipelines.js # Pipeline management and automation\n│ │ └── dashboard.js # Dashboard statistics and analytics\n│ ├── services/\n│ │ ├── aiService.js # OpenRouter AI integration service\n│ │ ├── taskGenerator.js # AI-powered task and timeline generation\n│ │ ├── pipelineAutomation.js # Pipeline stage automation logic\n│ │ └── realTimeService.js # Socket.IO real-time update handling\n│ ├── middleware/\n│ │ ├── auth.js # JWT token validation middleware\n│ │ ├── validation.js # Request data validation\n│ │ └── rateLimiting.js # API rate limiting and security\n│ └── utils/\n│ ├── logger.js # Logging utility\n│ ├── errorHandler.js # Centralized error handling\n│ └── helpers.js # Common utility functions\n├── frontend/\n│ ├── index.html # Marketing landing page\n│ ├── dashboard.html # Main CRM dashboard\n│ ├── login.html # Authentication page\n│ ├── css/\n│ │ ├── tailwind.min.css # Tailwind CSS framework\n│ │ ├── components.css # Custom component styles\n│ │ └── dashboard.css # Dashboard-specific styles\n│ ├── js/\n│ │ ├── main.js # Entry point and app initialization\n│ │ ├── auth.js # Authentication handling\n│ │ ├── api.js # API client and HTTP utilities\n│ │ ├── components/\n│ │ │ ├── TaskCard.js # Task display component\n│ │ │ ├── AIProgress.js # AI processing progress indicator\n│ │ │ ├── Pipeline.js # Pipeline visualization component\n│ │ │ └── Dashboard.js # Dashboard layout and widgets\n│ │ ├── services/\n│ │ │ ├── aiService.js # Frontend AI service integration\n│ │ │ ├── socketService.js # Real-time WebSocket handling\n│ │ │ └── stateManager.js # Application state management\n│ │ └── utils/\n│ │ ├── helpers.js # Utility functions\n│ │ ├── constants.js # Application constants\n│ │ └── validation.js # Form validation utilities\n├── tests/\n│ ├── backend/\n│ │ ├── auth.test.js # Authentication endpoint tests\n│ │ ├── tasks.test.js # Task management tests\n│ │ ├── aiService.test.js # AI integration tests\n│ │ └── integration.test.js # Full system integration tests\n│ └── frontend/\n│ ├── components.test.js # Frontend component tests\n│ └── e2e.test.js # End-to-end user workflow tests\n├── docker-compose.yml # MongoDB and app containerization\n├── .env.example # Environment variables template\n├── .gitignore # Git ignore patterns\n├── README.md # Setup and deployment documentation\n└── package.json # Root project configuration\n ``` -------------------------------- ### Run All Unit Tests and Check Coverage Source: https://github.com/incomestreamsurfer/context-engineering-intro/blob/main/PRPs/ai-powered-crm-system.md Commands to execute all unit tests, generate a test coverage report, and run integration tests. The goal is to achieve 80%+ test coverage for critical functions. ```bash # Run tests iteratively until passing: npm test npm run test:coverage npm run test:integration ``` -------------------------------- ### Email Agent Tool for Draft Creation Source: https://github.com/incomestreamsurfer/context-engineering-intro/blob/main/PRPs/EXAMPLE_multi_agent_prp.md Defines a tool for an agent to create email drafts. It takes recipient, subject, and context, then calls an 'email_agent' to generate the draft. It demonstrates dependency injection using RunContext and passes usage information for tracking. ```Python # Assuming AgentDependencies, RunContext, email_agent, EmailAgentDeps are defined elsewhere # from .agent import Agent, AgentDependencies # from .tools.gmail_tool import EmailAgentDeps # @research_agent.tool # Assuming research_agent is an instance of Agent async def create_email_draft( ctx: RunContext[AgentDependencies], recipient: str, subject: str, context: str ) -> str: """Create email draft based on research context.""" # CRITICAL: Pass usage for token tracking result = await email_agent.run( f"Create an email to {recipient} about: {context}", deps=EmailAgentDeps(subject=subject), usage=ctx.usage # PATTERN from multi-agent docs ) return f"Draft created with ID: {result.data}" ``` -------------------------------- ### Linting and Type Checking Source: https://github.com/incomestreamsurfer/context-engineering-intro/blob/main/PRPs/EXAMPLE_multi_agent_prp.md Commands to automatically fix code style issues using Ruff and perform static type checking with MyPy. These should be run before proceeding to tests. ```bash # Run these FIRST - fix any errors before proceeding ruff check . --fix # Auto-fix style issues mypy . # Type checking # Expected: No errors. If errors, READ and fix. ``` -------------------------------- ### Configure OpenRouter API Headers (JavaScript) Source: https://github.com/incomestreamsurfer/context-engineering-intro/blob/main/PRPs/ai-powered-crm-system.md Details the necessary headers for the OpenRouter API to ensure proper functionality and API rankings. Includes Authorization, HTTP-Referer, and X-Title. ```javascript const openRouterConfig = { baseURL: "https://openrouter.ai/api/v1", headers: { "Authorization": "Bearer " + process.env.OPENROUTER_API_KEY, "HTTP-Referer": process.env.SITE_URL, // Required for API rankings "X-Title": process.env.SITE_NAME // Required for API rankings } } ``` -------------------------------- ### Test Feature Endpoint (POST) Source: https://github.com/incomestreamsurfer/context-engineering-intro/blob/main/PRPs/templates/prp_base.md Performs an integration test by sending a POST request to the '/feature' endpoint. It includes a JSON payload and expects a success response. Error handling involves checking application logs. ```APIDOC POST /feature Description: Endpoint to test a specific feature. Request Body: Content-Type: application/json Schema: type: object properties: param: { type: string, description: "A parameter for the feature." } required: - param Example Request: curl -X POST http://localhost:8000/feature \ -H "Content-Type: application/json" \ -d '{"param": "test_value"}' Example Success Response: { "status": "success", "data": {} } Error Handling: If an error occurs, check logs at logs/app.log for stack traces. ``` -------------------------------- ### Test User Registration and Login Source: https://github.com/incomestreamsurfer/context-engineering-intro/blob/main/PRPs/ai-powered-crm-system.md Unit tests for the authentication system, verifying user registration with valid data and successful authentication of existing users. It checks for expected properties in the response body. ```javascript describe('Authentication System', () => { test('should register new user with valid data', async () => { const userData = { email: 'test@example.com', password: 'securePassword123', firstName: 'Test', lastName: 'User', role: 'sales' }; const response = await request(app) .post('/api/auth/register') .send(userData) .expect(201); expect(response.body).toHaveProperty('user'); expect(response.body).toHaveProperty('token'); expect(response.body.user.email).toBe(userData.email); }); test('should authenticate existing user', async () => { const loginData = { email: 'test@example.com', password: 'securePassword123' }; const response = await request(app) .post('/api/auth/login') .send(loginData) .expect(200); expect(response.body).toHaveProperty('token'); expect(response.body).toHaveProperty('refreshToken'); }); }); ``` -------------------------------- ### OpenRouter API Integration Research Summary Source: https://github.com/incomestreamsurfer/context-engineering-intro/blob/main/PRPs/ai-powered-crm-system.md This entry summarizes research on OpenRouter API integration patterns, model specifications, and pricing. It highlights critical aspects for setting up GPT-4o-mini and Gemini 2.5 Pro, including cost optimization strategies. ```APIDOC OpenRouter API Integration Research: __summary__ - Comprehensive integration patterns for OpenRouter API. - Model specifications and pricing details. - Critical setup for GPT-4o-mini and Gemini 2.5 Pro. - Cost optimization strategies. __related_docs__ - research/openrouter/page1_quickstart.md: OpenRouter API authentication and basic integration. - research/openrouter/page22_gpt_4o_mini.md: Specific model configuration for fast/cheap AI operations. - research/openrouter/page23_gemini_2_5_pro.md: Configuration for high-quality AI operations. ``` -------------------------------- ### Test Execution Command Source: https://github.com/incomestreamsurfer/context-engineering-intro/blob/main/PRPs/EXAMPLE_multi_agent_prp.md Command to run all tests, including coverage reporting. This should be executed iteratively until all tests pass. ```bash # Run tests iteratively until passing: pytest tests/ -v --cov=agents --cov=tools --cov-report=term-missing # If failing: Debug specific test, fix code, re-run ``` -------------------------------- ### Pydantic AI Multi-Agent Quirks and Best Practices Source: https://github.com/incomestreamsurfer/context-engineering-intro/blob/main/PRPs/EXAMPLE_multi_agent_prp.md Critical considerations for developing Pydantic AI multi-agent systems, including asynchronous execution requirements, OAuth2 flow for Gmail API, Brave API rate limits, agent-as-tool context passing, MIME formatting for Gmail drafts, absolute imports, and secure credential management. ```python # CRITICAL: Pydantic AI requires async throughout - no sync functions in async context ``` ```python # CRITICAL: Gmail API requires OAuth2 flow on first run - credentials.json needed ``` ```python # CRITICAL: Brave API has rate limits - 2000 req/month on free tier ``` ```python # CRITICAL: Agent-as-tool pattern requires passing ctx.usage for token tracking ``` ```python # CRITICAL: Gmail drafts need base64 encoding with proper MIME formatting ``` ```python # CRITICAL: Always use absolute imports for cleaner code ``` ```python # CRITICAL: Store sensitive credentials in .env, never commit them ``` -------------------------------- ### Brave Search API Source: https://github.com/incomestreamsurfer/context-engineering-intro/blob/main/PRPs/EXAMPLE_multi_agent_prp.md Documentation for the Brave Search API endpoint used for web searches. Specifies the request method, URL, required headers, query parameters, and expected response structure. ```APIDOC Brave Search Web Search API: Endpoint: GET https://api.search.brave.com/res/v1/web/search Description: Retrieves web search results. Authentication: - Header: X-Subscription-Token: Parameters: - q (string, required): The search query. - count (integer, optional, default: 10): The number of results to return. Constraints: 1 <= count <= 50. Headers: - X-Subscription-Token (string, required): Your Brave Search API subscription key. Response (Success - 200 OK): Content-Type: application/json Body: { "web": { "results": [ { "title": "string", "url": "string", "description": "string", "score": float (0.0 to 1.0) } // ... more results ] } } Error Responses: - 401 Unauthorized: Invalid or missing API key. - 400 Bad Request: Invalid query parameters. - 5xx Server Error: Issues with the Brave Search service. Usage Example: curl -H "X-Subscription-Token: YOUR_API_KEY" "https://api.search.brave.com/res/v1/web/search?q=context+engineering&count=5" ``` -------------------------------- ### Gemini 2.5 Pro Model Configuration Source: https://github.com/incomestreamsurfer/context-engineering-intro/blob/main/PRPs/ai-powered-crm-system.md Outlines configuration for Gemini 2.5 Pro, emphasizing its use for slow, expensive, but high-quality AI operations. This section covers parameters for leveraging its advanced capabilities. ```APIDOC Gemini 2.5 Pro Model Configuration: __model_name__ - "gemini-2.5-pro" __configuration_goals__ - High-quality output. - Complex reasoning and analysis. __parameters__ - `temperature`: Controls randomness (e.g., 0.5). - `max_tokens`: Limits response length. - `model`: "gemini-2.5-pro" __usage_scenario__ - Ideal for detailed timeline generation, complex subtask dependencies, and in-depth AI-driven insights. __related_docs__ - research/openrouter/RESEARCH_SUMMARY.md: Overall research summary. - research/openrouter/page22_gpt_4o_mini.md: Comparison with GPT-4o-mini. ``` -------------------------------- ### OpenRouter Model Rate Limits and Usage (JavaScript) Source: https://github.com/incomestreamsurfer/context-engineering-intro/blob/main/PRPs/ai-powered-crm-system.md Compares rate limits and usage characteristics of different OpenRouter models, providing guidance on selecting models for specific AI tasks. ```javascript // CRITICAL: OpenRouter models have different rate limits // GPT-4o-mini: 20 req/min on free tier, good for fast operations // Gemini 2.5 Pro: Higher cost but better quality for complex AI tasks ``` -------------------------------- ### Frontend Component Architecture Source: https://github.com/incomestreamsurfer/context-engineering-intro/blob/main/PRPs/ai-powered-crm-system.md Outlines the creation of frontend components using ES6 modules for displaying tasks with AI indicators, real-time AI processing feedback, pipeline visualization, and dashboard metrics. ```yaml Task 9: Frontend Component Architecture (HTML5/CSS/ES6) CREATE js/components/ modules: - IMPLEMENT TaskCard.js for task display with AI indicators - CREATE AIProgress.js for real-time AI processing feedback - ADD Pipeline.js for drag-and-drop pipeline visualization - IMPLEMENT Dashboard.js for metric displays and quick actions ``` -------------------------------- ### Claude Code PRP Workflow Commands Source: https://github.com/incomestreamsurfer/context-engineering-intro/blob/main/README.md Defines custom commands for the Claude Code environment to manage the Product Requirements Prompt (PRP) workflow. These commands facilitate the creation and execution of PRPs, which are central to implementing features based on initial requirements. ```APIDOC Claude Code Commands: /generate-prp Description: Generates a comprehensive Product Requirements Prompt (PRP) from an initial feature request file. Parameters: INITIAL_FILE: Path to the markdown file describing the feature request (e.g., INITIAL.md). Usage Example: /generate-prp INITIAL.md /execute-prp Description: Executes a generated PRP to implement a feature. The PRP file contains detailed instructions for the AI. Parameters: PRP_FILE: Path to the generated PRP markdown file (e.g., PRPs/your-feature-name.md). Usage Example: /execute-prp PRPs/my-new-feature.md ```