Context Engineering Intro Template

repository·main·Indexed 42 days ago

https://github.com/incomestreamsurfer/context-engineering-intro

A template for 'Context Engineering'—the practice of providing AI coding assistants with structured documentation, rules, and examples. It includes workflows for using Claude Code commands like /generate-prp and /execute-prp to create and implement Product Requirements Prompts (PRPs), as well as a multi-agent research approach using Jina for documentation scraping.

Tokens
13K
Snippets
36
Records
53
Agent score
54%

What's inside Context Engineering Intro

  1. Project Structure and Directory Overview

    main

    The repository is organized into the following key directories and files:

    • .claude/: Contains Claude Code configuration, including hooks/ for documentation automation and settings.json for hook configuration.
    • research/: A local repository of up-to-date API documentation (e.g., OpenAI, Pydantic AI, Anthropic, Jina AI, Shopify GraphQL, Google Search Console).
    • examples/: Contains relevant code examples to guide implementation.
    • CLAUDE.md: Contains specific AI coding instructions and project guidelines.
    • phase-1.md & phase-2.md: Specification files for different project phases.
  2. Frontend architecture requirements (No-Framework approach)

    main

    The frontend is designed to function without heavy framework dependencies (like React). Instead, follow these patterns:

    • Architecture: Use ES6 modules to create a component-like architecture.
    • DOM Management: Implement manual DOM manipulation and event handling.
    • Modern JS: Utilize async/await, destructuring, and modules.
    • Styling: Use Tailwind CSS for a utility-first design system.
    // CRITICAL: Frontend must work without framework dependencies
    Use ES6 modules for component-like architecture
    Implement manual DOM manipulation and event handling
    Use modern JavaScript features (async/await, destructuring, modules)
  3. Avoid these Anti-Patterns in the AI-Powered CRM System

    main

    To maintain the integrity and performance of the system, avoid the following development practices:

    • Framework Overuse: Do not use React or other heavy frameworks; stick to HTML5, CSS, and ES6.
    • Security Risks: Never hardcode API keys (use environment variables) or skip JWT token validation on protected routes. Do not skip input validation.
    • AI/Service Mismanagement: Do not skip AI service error handling (implement fallbacks) or ignore OpenRouter API rate limits.
    • Performance Issues: Do not ignore MongoDB indexing or use synchronous operations in asynchronous contexts.
    • Infrastructure Neglect: Do not ignore WebSocket connection management or skip test coverage.
  4. Use the examples/ folder to guide AI implementation

    main

    The examples/ folder is critical for providing the AI with concrete patterns to follow. Instead of describing patterns in prose, provide actual code files. Effective examples include:

    • Code Structure Patterns: Module organization, import conventions, and class/function patterns.
    • Testing Patterns: Test file structure, mocking approaches, and assertion styles.
    • Integration Patterns: API client implementations, database connections, and authentication flows.
    • CLI Patterns: Argument parsing, output formatting, and error handling.
    examples/
    ├── README.md           # Explains what each example demonstrates
    ├── cli.py             # CLI implementation pattern
    ├── agent/             # Agent architecture patterns
    │   ├── agent.py      # Agent creation pattern
    │   ├── tools.py      # Tool implementation pattern
    │   └── providers.py  # Multi-provider pattern
    └── tests/            # Testing patterns
        ├── test_agent.py # Unit test patterns
        └── conftest.py  # Pytest configuration
  5. Avoid PRP Anti-Patterns

    main

    When writing or reviewing a PRP, ensure the following anti-patterns are avoided:

    • Creating new patterns: Always use existing codebase patterns where possible.
    • Skipping validation: Never assume code "should work" without running tests.
    • Ignoring failures: Do not ignore failing tests; fix the underlying code.
    • Sync in Async: Do not use synchronous functions in an asynchronous context.
    • Hardcoding: Avoid hardcoding values that belong in configuration.
    • Broad Exception Catching: Do not use generic except Exception blocks; be specific about what you are catching.
  6. Implement JWT Authentication pattern

    main

    The system requires a dual-token pattern for security:

    • Access Tokens: 15-minute expiry.
    • Refresh Tokens: 7-day expiry, stored in secure HTTP-only cookies.

    This pattern is designed to support the separation between the marketing frontend and the dashboard backend.

    // CRITICAL: JWT tokens need both access and refresh token pattern
    Access tokens: 15 minutes expiry for security
    Refresh tokens: 7 days expiry stored in secure HTTP-only cookies
  7. Data Models for AI-Powered CRM

    main

    The CRM system uses four primary Mongoose schemas to manage users, customers, tasks, and automation pipelines.

    • UserSchema: Manages authentication, roles (admin, sales, marketing), and granular permissions.
    • CustomerSchema: The core entity for lead tracking, including contact info, status (lead, prospect, customer, inactive), and pipeline stage tracking.
    • TaskSchema: Supports AI-enhanced management. It includes an aiGenerated object containing subtasks, a timeline (with estimated dates and milestones), and metadata (tracking the AI model used, confidence scores, and prompts).
    • PipelineSchema: Defines automation workflows with stages that can trigger actions like create_task, send_email, or assign_user based on entry or task completion.
    // Example TaskSchema structure highlighting AI metadata
    const TaskSchema = {
      _id: ObjectId,
      title: String,
      aiGenerated: {
        subtasks: [{
          _id: ObjectId,
          title: String,
          estimatedTime: Number,
          dependencies: [ObjectId],
          status: String
        }],
        timeline: {
          estimatedStartDate: Date,
          estimatedEndDate: Date,
          milestones: [{ name: String, date: Date, completed: Boolean }]
        },
        metadata: {
          generatedBy: String, // e.g., 'gpt-4o-mini'
          confidence: Number, // 0-1 score
          promptUsed: String
        }
      }
    }
  8. Organize research documentation by feature

    main

    When building a research directory for context engineering, organize your files by technology and feature to make them easily consumable by an AI. A typical structure includes subdirectories for each major dependency, containing specific markdown files for different aspects of that technology and an examples/ folder for code snippets.

    Example directory structure:

    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
  9. How the documentation hooks work

    main

    The project uses Claude Code hooks to provide real-time documentation context. When you write or edit code involving external APIs, the hook performs the following lifecycle:

    1. Extract keywords: It identifies imports, API calls, and function names from your code.
    2. Search: It searches the local research/ directory for matching documentation.
    3. Show relevant docs: It presents the found documentation to Claude before any code is written.
    4. Ensure accuracy: This process ensures Claude uses up-to-date API specifications rather than relying on potentially outdated training data.

    Example Workflow: If you write from openai import OpenAI, the hook automatically retrieves and shows Claude the documentation located in research/openai/ before proceeding with the implementation.

    from openai import OpenAI
    client = OpenAI()
  10. Avoid common multi-agent development anti-patterns

    main

    When building multi-agent systems, avoid these common mistakes:

    • Hardcoding API keys: Always use environment variables.
    • Mixing sync/async: Do not use synchronous functions within an asynchronous agent context.
    • Skipping OAuth setup: Ensure Gmail OAuth flows are properly configured.
    • Ignoring rate limits: Respect API rate limits for external services.
    • Missing context in calls: Do not forget to pass ctx.usage in multi-agent calls.
    • Committing secrets: Never commit credentials.json or token.json files to version control.
  11. Research Directory Structure

    main

    When using the multi-agent research approach, the agent organizes scraped documentation into a structured directory under research/. Each technology or API provider receives its own subdirectory containing individual .md files for each documentation page.

    Example structure:

    research/
    ├── pydantic-ai/      # 22+ documentation pages
    ├── openai/           # 20+ API documentation pages  
    ├── anthropic/        # 18+ Claude documentation pages
    ├── jina/             # 12+ scraping API pages
    ├── shopify/          # 18+ GraphQL/REST API pages
    └── seo-apis/         # 24+ Search Console/Ahrefs pages