Skip to content

Automatic context injection for Claude Code - inject project knowledge, schemas, and patterns on every prompt

License

Notifications You must be signed in to change notification settings

darraghh1/bmad-context-injection

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

7 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

BMAD Context Injection for Claude Code

Automatically inject project-specific knowledge, schemas, and code patterns into Claude Code based on what you're working on.

Type "create a form" → Claude receives your forms documentation, relevant Zod schemas, code usage examples, and BMAD workflow suggestions before processing your prompt.

Getting Started? See INTEGRATION-GUIDE.md for step-by-step setup instructions, including how to create knowledge files from scratch.

What's New in v2.1

  • 🌍 Global Skills — Set "global": true to always inject (no trigger required)
  • 📊 Priority Sorting — Output sorted by priority level (critical → high → medium → low)
  • File Caching — Cached file locations for better performance on large codebases
  • 🔌 Pluggable Schema Extractors — Built-in support for Zod, Yup, and Valibot (configurable)

Features

  • 📚 Knowledge Injection — Summarizes markdown docs and injects key points
  • 📐 Schema Discovery — Finds and extracts relevant schemas from your codebase (Zod, Yup, Valibot)
  • 🔧 Code Pattern Extraction — Shows usage examples from your existing code
  • 🤖 BMAD Agent Suggestions — Recommends relevant agents and workflows
  • ⚠️ Guardrails — Warns before potentially problematic operations
  • 🎯 Priority-Based Filtering — Critical/high priority auto-injects, medium/low suggests only
  • 🌍 Global Skills — Always-active skills that inject on every prompt
  • Caching — File location caching for performance
  • 🐛 Debug Mode — Set DEBUG_HOOK=1 for error logging

What It Looks Like

You: "Create a form for adding team members"

Claude receives (before your prompt):
╔═══════════════════════════════════════════════════════════╗
║  ____  __  __    _    ____                                ║
║ | __ )|  \/  |  / \  |  _ \                               ║
║ |  _ \| |\/| | / _ \ | | | |                              ║
║ | |_) | |  | |/ ___ \| |_| |                              ║
║ |____/|_|  |_/_/   \_\____/  Context Injection System     ║
╚═══════════════════════════════════════════════════════════╝

📋 INJECTED PROJECT CONTEXT
────────────────────────────────────────

📚 Knowledge: knowledge/forms-validation.md
# Forms & Validation Patterns
## Required Libraries
- `react-hook-form` — Form state management
- `zod` — Schema validation
## Critical Rules
1. NO generic on useForm — Let zodResolver infer types
2. Schema in separate file — Shared between client/server

📐 Schema: apps/web/app/.../member.schema.ts
export const CreateMemberSchema = z.object({
  name: z.string().min(1),
  email: z.string().email(),
  role: z.enum(['admin', 'member']),
});

🔧 Pattern: apps/web/app/.../member-form.tsx
const form = useForm({
  resolver: zodResolver(CreateMemberSchema),
});

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🎯 SKILL ACTIVATION SUGGESTIONS
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

🤖 BMAD AGENT AVAILABLE
────────────────────────────────────────
🤖 bmad-dev
   Developer agent for implementing stories
   💡 Consider activating: /bmad:bmm:agents:dev

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
💡 TIP: Review suggestions above before proceeding
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Quick Start

1. Copy files to your project

# Copy the .claude folder to your project root
cp -r .claude /path/to/your/project/

# Copy knowledge files (or create your own)
cp -r knowledge /path/to/your/project/

2. Install tsx in your project root

cd /path/to/your/project
npm install -D tsx

Installing in your project root ensures npx finds it quickly without re-downloading.

3. Customize skill rules

Edit .claude/skills/skill-rules.json to match your project's patterns.

4. Create knowledge files

Add markdown files to knowledge/ documenting your project's conventions.

How It Works

┌─────────────────┐     ┌──────────────────┐     ┌─────────────────┐
│  Your Prompt    │────▶│  Hook Script     │────▶│  Injected       │
│  "create form"  │     │  - Match skills  │     │  Context +      │
│                 │     │  - Extract docs  │     │  Suggestions +  │
│                 │     │  - Find schemas  │     │  Your Prompt    │
│                 │     │  - Find patterns │     │                 │
└─────────────────┘     └──────────────────┘     └─────────────────┘
  1. UserPromptSubmit hook runs before every prompt
  2. Skill rules map keywords/patterns to knowledge files and actions
  3. Hook script extracts and formats relevant content
  4. Claude receives the injected context before your prompt

File Structure

your-project/
├── .claude/
│   ├── settings.json              # Hook registration
│   ├── hooks/
│   │   ├── context-injection.ts   # Main hook script
│   │   ├── package.json           # Dependencies (tsx)
│   │   └── tsconfig.json
│   └── skills/
│       └── skill-rules.json       # Keyword → knowledge mapping
│
└── knowledge/                      # Your pattern documentation
    ├── forms-validation.md
    ├── server-actions.md
    ├── database-patterns.md
    └── ...

Configuration

settings.json

{
  "hooks": {
    "UserPromptSubmit": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "npx tsx .claude/hooks/context-injection.ts"
          }
        ]
      }
    ]
  }
}

skill-rules.json

{
  "version": "2.1",
  "config": {
    "contextInjection": {
      "enabled": true,
      "maxKnowledgeLines": 50,
      "maxSchemaLines": 30,
      "maxPatternLines": 20,
      "schemaSearchDirs": ["apps", "packages", "src", "lib"],
      "cacheEnabled": true,
      "cacheTTLSeconds": 300,
      "schemaExtractors": [
        {
          "name": "zod",
          "filePattern": ".schema.ts",
          "extractPatterns": ["export\\s+(const|type)\\s+\\w+.*=.*z\\."]
        }
      ]
    }
  },
  "skills": {
    "global-anti-patterns": {
      "type": "knowledge",
      "priority": "critical",
      "global": true,
      "description": "Anti-patterns to avoid (always active)",
      "knowledgeFile": "knowledge/anti-patterns.md"
    },
    "forms": {
      "type": "knowledge",
      "priority": "high",
      "description": "Forms and validation patterns",
      "knowledgeFile": "knowledge/forms-validation.md",
      "promptTriggers": {
        "keywords": ["form", "validation", "zod"],
        "intentPatterns": ["(create|build).*?form"]
      },
      "fileTriggers": {
        "pathPatterns": ["**/*-form.tsx"],
        "contentPatterns": ["useForm", "zodResolver"]
      },
      "contextInjection": {
        "enabled": true,
        "includeSchemas": true,
        "includePatterns": true,
        "schemaPatterns": ["form", "input"]
      }
    }
  }
}

Skill Types

Type Purpose Auto-Inject
knowledge Injects documentation from markdown files ✅ (high/critical)
agent Suggests a BMAD agent slash command
workflow Suggests a BMAD workflow to run
skill Suggests a Claude Code skill
guardrail Shows warning before proceeding ✅ (always)

Priority Levels

Priority Behavior
critical Always inject content + show prominently
high Auto-inject content + show suggestion
medium Show suggestion only (no injection)
low Skip unless contextInjection.enabled: true

Context Injection Options

Option Description
enabled Force enable/disable injection for this skill
includeSchemas Find *.schema.ts files matching patterns
includePatterns Find code examples via fileTriggers.contentPatterns
schemaPatterns Patterns to search for in schema file content

Global Skills (v2.1)

Set "global": true on any skill to make it always active — no trigger required:

{
  "global-anti-patterns": {
    "type": "knowledge",
    "priority": "critical",
    "global": true,
    "description": "Anti-patterns to avoid (always active)",
    "knowledgeFile": "knowledge/anti-patterns.md"
  }
}

Global skills are useful for:

  • Anti-patterns that should always be visible
  • Project conventions that apply to all code
  • Critical warnings that shouldn't be forgotten

Caching (v2.1)

File caching improves performance on large codebases by caching schema file locations:

{
  "config": {
    "contextInjection": {
      "cacheEnabled": true,
      "cacheTTLSeconds": 300
    }
  }
}
  • Cache is stored in .claude/.cache/file-cache.json
  • Default TTL is 5 minutes (300 seconds)
  • Cache is invalidated when files are deleted
  • Set cacheEnabled: false to disable

Pluggable Schema Extractors (v2.1)

Configure extractors for different validation libraries:

{
  "config": {
    "contextInjection": {
      "schemaExtractors": [
        {
          "name": "zod",
          "filePattern": ".schema.ts",
          "extractPatterns": ["export\\s+(const|type)\\s+\\w+.*=.*z\\."]
        },
        {
          "name": "yup",
          "filePattern": ".schema.ts",
          "extractPatterns": ["export\\s+(const|type)\\s+\\w+.*=.*yup\\."]
        },
        {
          "name": "valibot",
          "filePattern": ".schema.ts",
          "extractPatterns": ["export\\s+(const|type)\\s+\\w+.*=.*v\\."]
        }
      ]
    }
  }
}

Default extractors for Zod, Yup, and Valibot are included. Add custom extractors for other libraries.

Trigger Configuration

Keywords (Simple Matching)

Case-insensitive substring matching:

"keywords": ["form", "validation", "zod"]

Intent Patterns (Regex)

For complex matching with capture groups:

"intentPatterns": [
  "(create|build|add|make).*?form",
  "(validate|check).*?(input|data)"
]

File Triggers (Code Discovery)

Find code patterns in your codebase:

"fileTriggers": {
  "pathPatterns": ["**/*-form.tsx", "**/*.schema.ts"],
  "contentPatterns": ["useForm", "zodResolver", "FormField"]
}

Debugging

Test the hook manually

# Windows (PowerShell)
$env:DEBUG_HOOK="1"; echo '{"prompt":"create a form"}' | npx tsx .claude/hooks/context-injection.ts

# Linux/Mac
echo '{"prompt":"create a form"}' | DEBUG_HOOK=1 npx tsx .claude/hooks/context-injection.ts

Common Issues

Issue Solution
Hook not running Check .claude/settings.json is valid JSON
No output Verify keywords match and knowledge files exist
Errors silently Run with DEBUG_HOOK=1 to see errors
Wrong schemas found Adjust schemaPatterns or schemaSearchDirs

BMAD Integration

This is part of the BMAD Method — an AI-driven agile development framework.

Agent Suggestions

{
  "bmad-dev": {
    "type": "agent",
    "priority": "high",
    "description": "Developer agent for implementing stories",
    "slashCommand": "/bmad:bmm:agents:dev",
    "promptTriggers": {
      "keywords": ["implement", "build feature", "code this"]
    },
    "suggestion": "Consider activating: /bmad:bmm:agents:dev"
  }
}

Workflow Suggestions

{
  "dev-story": {
    "type": "workflow",
    "priority": "high",
    "description": "Execute story implementation",
    "slashCommand": "/bmad:bmm:workflows:dev-story",
    "promptTriggers": {
      "keywords": ["implement story", "execute story"]
    }
  }
}

Guardrails

{
  "no-story-warning": {
    "type": "guardrail",
    "priority": "critical",
    "description": "Reminder to load story context",
    "promptTriggers": {
      "intentPatterns": ["^implement.*?feature$"]
    },
    "suggestion": "⚠️ Ensure you have a story loaded first!"
  }
}

Example Knowledge Files

See the knowledge/ folder for examples:

  • forms-validation.md — React Hook Form + Zod patterns
  • server-actions.md — Server Actions and data fetching
  • database-patterns.md — Supabase, RLS, migrations
  • ui-components.md — Shadcn/UI component usage
  • testing.md — Playwright E2E testing patterns

License

MIT — Use however you like.

Contributing

PRs welcome! Especially for:

  • Additional framework knowledge files
  • New skill types and patterns
  • Hook improvements
  • Documentation

About

Automatic context injection for Claude Code - inject project knowledge, schemas, and patterns on every prompt

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 2

  •  
  •