diff --git a/README.md b/README.md index 1da0cb7..a6ee23c 100644 --- a/README.md +++ b/README.md @@ -630,8 +630,10 @@ Attempting to solve complex data analysis, system integration, or real-time prob ## Issue Generation -**Maturity**: Intermediate -**Description**: Generate Kanban-optimized work items (4-8 hours max) from requirements using AI to ensure continuous flow with clear acceptance criteria and dependencies. +**Maturity**: Intermediate +**Description**: Generate small, deployable work items (<1 hour with AI assistance) from requirements using AI to ensure continuous delivery with clear acceptance criteria and dependency tracking. + +**Methodology Note**: This pattern aligns well with Kanban principles (continuous flow, small batches) but works with any development methodology including Scrum, Scrumban, or ad-hoc workflows. **Related Patterns**: [Readiness Assessment](#readiness-assessment), [Spec-Driven Development](#spec-driven-development) @@ -641,19 +643,19 @@ Attempting to solve complex data analysis, system integration, or real-time prob graph TD A[Requirements Document] --> B[AI Feature Analysis] B --> C[Work Item Splitting] - C --> D{<8 hours?} + C --> D{<1 hour?} D -->|No| E[Split Further] E --> C D -->|Yes| F[Story Generation] F --> G[Acceptance Criteria] G --> H[Cycle Time Target] H --> I[Dependency Mapping] - I --> J[Kanban Card Creation] + I --> J[Work Item Creation] ``` **Core Principles** -- **Kanban Optimization**: Each work item sized for <8 hours to ensure continuous flow +- **Small Batch Sizing**: Each work item sized for <1 hour (AI-assisted development velocity) to enable continuous delivery and rapid feedback - **AI-Assisted Decomposition**: Use AI to break down requirements into implementable tasks - **Traceability Integration**: Connect issues to implementation files and CI workflows - **Dependency Mapping**: Establish clear relationships between work items and epics @@ -663,7 +665,7 @@ graph TD Generated issues must include: - **Title**: Specific, actionable description of the work -- **Cycle Time Target**: Estimated completion time (4-8 hours) +- **Cycle Time Target**: Estimated completion time (<1 hour with AI assistance) - **Acceptance Criteria**: Testable conditions for completion - **File Scope**: Which files will be added, updated, or removed - **CI Requirements**: Test coverage, pipeline steps, quality gates @@ -678,11 +680,10 @@ Generated issues must include: **Implementation Examples**: See [examples/issue-generation/](examples/issue-generation/) for detailed AI prompts, epic breakdown workflows, CI integration patterns, and traceability implementations. For AI-first workflows, see [Beads guide](examples/issue-generation/beads-guide.md) - a git-native issue tracker with CLI access and persistent agent memory. -> "If a task takes more than one day, split it." -> – Kanban Guide, Lean Kanban University - > "Small, frequent deliveries expose issues early and keep teams aligned." -> – Agile Alliance, Kanban Glossary +> – Agile Alliance + +**Kanban Context**: This pattern embodies Kanban principles of continuous flow and small batch sizes. If using Kanban: "If a task takes more than one day, split it." (Kanban Guide, Lean Kanban University). However, the pattern works equally well with Scrum sprints, continuous delivery, or any methodology that values incremental progress. **Anti-pattern: Under-Specified Issues** Creating generic tasks without specific acceptance criteria, proper sizing, or clear dependencies leads to scope creep and estimation errors. @@ -697,13 +698,14 @@ Creating issues without CI workflow integration, file tracking, or traceability ❌ "Add some tests" ❌ "AUTH-002: Implement password validation" (no file tracking or CI requirements) -✅ "Add OAuth 2.0 token validation endpoint (8 hours)" -✅ "Implement dashboard metric WebSocket connection (6 hours)" -✅ "Write unit tests for user service login method (4 hours)" +✅ "Add OAuth 2.0 token validation endpoint (<1 hour with AI)" +✅ "Implement dashboard metric WebSocket connection (45 minutes)" +✅ "Write unit tests for user service login method (30 minutes)" ✅ "AUTH-002: Password validation service with CI integration" - Files: src/auth/validators.py, tests/test_validators.py - Coverage: 95%, unit + integration tests - CI: lint, test, security-scan must pass + - AI-assisted: Use AI for implementation and test generation ``` --- diff --git a/examples/issue-generation/ANALYSIS.md b/examples/issue-generation/ANALYSIS.md deleted file mode 100644 index b265001..0000000 --- a/examples/issue-generation/ANALYSIS.md +++ /dev/null @@ -1,432 +0,0 @@ -# Issue Generation Examples - MECE Analysis - -## Executive Summary - -The `/examples/issue-generation` directory has **good content coverage** but suffers from: -1. **Overlapping content** between files (not mutually exclusive) -2. **No clear learning path** (lacks progressive structure) -3. **README as dumping ground** (should be navigation hub) -4. **⚠️ CRITICAL: Outdated task sizing** - References 4-8 hour tasks, but AI-assisted development enables **<1 hour tasks** for much faster feedback cycles - -**Recommendation**: Restructure to create clear, non-overlapping files with a guided learning journey AND update task sizing guidance for AI-first development. - ---- - -## Current Structure Assessment - -### Files Inventory -``` -├── README.md (5.4KB) # Overview + examples + comparison -├── ai-prompts-for-epic-management.md (5.5KB) # AI prompts for epics -├── beads-example.md (3.1KB) # Beads tool guide -├── ci-integration-examples.md (9.0KB) # CI/CD patterns -├── detailed-kanban-workflow.md (7.2KB) # Kanban + epic examples -└── issue-generator.py (16KB) # Python script -``` - ---- - -## MECE Violations - -### ❌ NOT Mutually Exclusive - -#### Problem 1: Epic Management Duplication -**ai-prompts-for-epic-management.md** and **detailed-kanban-workflow.md** overlap significantly: - -| Topic | ai-prompts... | detailed-kanban... | -|-------|---------------|-------------------| -| Epic breakdown | ✅ Lines 5-29 | ✅ Lines 6-66 | -| Progress tracking | ✅ Lines 82-105 | ✅ Lines 143-180 | -| Dependency management | ✅ Lines 128-155 | ✅ Lines 216-233 | -| Epic-subissue linking | ✅ Lines 31-50 | ✅ Lines 69-141 | - -**Impact**: Users don't know which file to read, content is redundant. - -#### Problem 2: README Contains Deep Examples -**README.md** includes: -- Feature breakdown example (lines 48-57) -- Epic decomposition example (lines 59-72) -- Bug triage example (lines 74-81) - -These belong in dedicated example files, not the navigation hub. - -#### Problem 3: AI Prompts Scattered -AI prompt examples appear in: -- README.md (lines 38-45, 64-69) -- ai-prompts-for-epic-management.md (entire file) -- detailed-kanban-workflow.md (lines 13-34, 72-88, 145-162, 217-232) - -**Impact**: No single source of truth for prompt templates. - -### ✅ Collectively Exhaustive - -**Good news**: All necessary topics are covered: -- ✅ Tool selection (Beads vs traditional) -- ✅ AI prompt templates -- ✅ Epic management patterns -- ✅ Kanban workflow optimization -- ✅ CI/CD integration -- ✅ Programmatic generation (Python) -- ✅ Progress tracking -- ✅ Dependency validation - -**Gaps identified**: -1. Missing a "Basics/Getting Started" document explaining core concepts -2. **CRITICAL**: Task sizing guidance is outdated - examples reference 4-8 hours but AI-assisted development enables <1 hour tasks: - - AI can generate code in minutes, not hours - - Faster iteration cycles (prompt → code → test → deploy) - - Tighter feedback loops - - More frequent deployments - - Traditional Kanban was 4-8 hours for manual coding - - **AI-assisted Kanban should be <1 hour per task** - ---- - -## Logical Flow Issues - -### Current User Journey (Confusing) -``` -User lands on README → - Sees tool comparison immediately (premature) - Sees scattered examples - Unclear where to go next - Three files about epics (which one?) -``` - -### Ideal User Journey (Clear) -``` -User lands on README → - 1. Understand core concepts - 2. See decision tree (Beads vs traditional) - 3. Choose their path: - Path A: Traditional tools → AI prompts → Epic mgmt → CI integration - Path B: Beads → Beads guide → Best practices - 4. Advanced: Python script for automation -``` - ---- - -## CRITICAL: Task Sizing for AI-Assisted Development - -### Current Problem -All files reference **4-8 hour tasks** as the Kanban standard: -- README.md line 19: "4-8 hour tasks for continuous flow" -- README.md line 31: "Tasks deployable in <1 day (4-8 hours max)" -- ai-prompts-for-epic-management.md line 11: "4-8 hours max" -- detailed-kanban-workflow.md line 21: "Maximum 4-8 hours per task" -- ci-integration-examples.md references same sizing - -### Why This Is Wrong for AI Development - -**Traditional Kanban (Manual Coding)**: -``` -Planning (30 min) → Coding (6 hours) → Testing (1 hour) → Review (30 min) = 8 hours -``` - -**AI-Assisted Kanban**: -``` -Planning (5 min) → AI prompting (10 min) → Review/refine (20 min) → Testing (15 min) → Deploy (10 min) = 60 min -``` - -### AI Development Velocity -- **Code generation**: Minutes, not hours -- **Iteration cycles**: 5-15 minutes (prompt → review → refine) -- **Testing**: Automated, runs in parallel -- **Deployment**: Continuous, not batched -- **Feedback**: Immediate, not end-of-day - -### Recommended Task Sizing - -**AI-Assisted Development**: -- **Target**: <1 hour per task -- **Maximum**: 2 hours (if longer, split it) -- **Optimal**: 15-45 minutes for most tasks - -**Examples**: -``` -❌ Old (4-8 hours): "Implement user authentication system" -✅ New (<1 hour): "Add JWT token generation function" -✅ New (<1 hour): "Add token validation middleware" -✅ New (<1 hour): "Write integration tests for token flow" -✅ New (<1 hour): "Add password reset endpoint" -``` - -### Impact on All Files - -**Every file needs updating** to reflect AI-first task sizing: -1. README.md: Change "4-8 hours" to "<1 hour" -2. ai-prompts-for-epic-management.md: Update all examples -3. detailed-kanban-workflow.md: Revise cycle time targets -4. ci-integration-examples.md: Update timing expectations -5. beads-example.md: Already mentions "4-8 hours" in best practices - -### Benefits of <1 Hour Tasks -1. **Faster feedback**: Deploy multiple times per day -2. **Reduced risk**: Smaller changes = easier to debug -3. **Better flow**: No work sits "in progress" for hours -4. **Higher quality**: More frequent testing and validation -5. **AI advantage**: Leverages AI's speed, not constrained by human typing speed - ---- - -## Detailed File Analysis - -### README.md (❌ Needs Restructuring) -**Current problems:** -- Mixes overview with deep examples -- Comparison table appears too early -- No clear "what next?" guidance - -**Should contain:** -- Brief overview (3-4 sentences) -- Learning path navigation -- File descriptions with "read this if..." -- Quick decision tree - -**Should NOT contain:** -- Detailed code examples -- Long AI prompts -- Deep technical content - -### ai-prompts-for-epic-management.md (⚠️ Overlaps with detailed-kanban-workflow.md) -**Content:** -- Epic creation prompts ✅ -- Universal linking ✅ -- RED/GREEN/REFACTOR ✅ -- Progress tracking ✅ -- CI/CD prompts ✅ -- Dependency prompts ✅ - -**Recommendation:** This should be THE authoritative prompt library. Remove duplicate content from other files and point here. - -### detailed-kanban-workflow.md (⚠️ Overlaps with ai-prompts...) -**Content:** -- Kanban epic breakdown example -- Generated work items JSON -- Epic-subissue relationships -- Progress tracking examples -- Dependency validation - -**Recommendation:** Rename to `workflow-examples.md`. Focus on OUTPUT examples (JSON structures, relationship graphs) rather than INPUT (AI prompts). Cross-reference ai-prompts file for the prompts themselves. - -### ci-integration-examples.md (✅ Well Scoped) -**Content:** -- CI integration patterns -- Traceability structures -- File validation -- Coverage enforcement -- GitHub Actions examples - -**Recommendation:** Keep as-is. This is well-scoped and doesn't overlap significantly with other files. - -### beads-example.md (✅ Well Scoped) -**Content:** -- Beads installation -- Quick start commands -- AI agent workflow -- Python integration -- Best practices - -**Recommendation:** Keep as-is. Tool-specific guide is appropriately separated. - -### issue-generator.py (✅ Well Scoped) -**Content:** -- Python implementation for programmatic generation - -**Recommendation:** Keep as-is. Consider adding a companion `issue-generator-guide.md` if usage becomes complex. - ---- - -## Recommended Restructuring - -### Option A: Consolidate by Learning Path (RECOMMENDED) - -``` -examples/issue-generation/ -├── README.md # Navigation hub (2KB max) -├── 01-getting-started.md # NEW: Core concepts, 4-8 hour tasks, Kanban principles -├── 02-choosing-tools.md # NEW: Decision tree, comparison table, when to use what -├── 03-ai-prompts.md # RENAME: ai-prompts-for-epic-management.md (consolidated prompts) -├── 04-workflow-examples.md # RENAME: detailed-kanban-workflow.md (output examples) -├── 05-ci-integration.md # KEEP: ci-integration-examples.md -├── beads-guide.md # RENAME: beads-example.md (parallel track for Beads users) -└── issue-generator.py # KEEP: Python script -``` - -**Flow:** -1. README → "Start at 01-getting-started.md" -2. 01 → Understand principles -3. 02 → Choose traditional or Beads -4. Traditional path: 03 → 04 → 05 -5. Beads path: beads-guide.md -6. Advanced: issue-generator.py - -### Option B: Reorganize by Topic (Alternative) - -``` -examples/issue-generation/ -├── README.md # Navigation hub -├── concepts/ -│ └── kanban-principles.md # Core concepts -├── tools/ -│ ├── tool-comparison.md # Decision framework -│ └── beads-guide.md # Beads-specific -├── workflows/ -│ ├── ai-prompts.md # All prompts -│ ├── epic-management.md # Epic patterns -│ └── ci-integration.md # CI/CD patterns -└── automation/ - └── issue-generator.py # Script -``` - ---- - -## Specific Changes Required - -### 1. Merge Duplicate Epic Content - -**Action:** Consolidate into single authoritative file - -**From ai-prompts-for-epic-management.md:** -- Keep: All AI prompt templates (these are the INPUT) - -**From detailed-kanban-workflow.md:** -- Keep: JSON output examples, relationship structures (these are the OUTPUT) - -**Result:** Clear separation between "what to ask AI" vs "what you get back" - -### 2. Slim Down README.md - -**Remove:** -- Detailed code examples (lines 48-81) -- Long AI prompts (lines 38-45, 64-69) -- Deep technical content - -**Add:** -- Learning path guide: "New to issue generation? Start here..." -- File descriptions: "Read ai-prompts.md if you want to..." -- Decision tree: "Use Beads if... Use GitHub/JIRA if..." - -**Keep:** -- Directory structure overview -- Key features (high-level only) -- Comparison table (it's useful here for quick reference) - -### 3. Create Missing "Getting Started" - -**New file: 01-getting-started.md** - -Content: -```markdown -# Getting Started with AI Issue Generation - -## What Are Kanban-Optimized Issues? -- Work items sized for 4-8 hours -- Independently deployable -- Continuous flow over batching - -## Why 4-8 Hours? -- Rapid feedback cycles -- Reduced work-in-progress -- Earlier detection of problems - -## Core Principles -1. Flow over estimates -2. Independent deployment -3. RED/GREEN/REFACTOR -4. CI/CD for every task - -## Next Steps -- Choosing tools: See 02-choosing-tools.md -- AI prompts: See 03-ai-prompts.md -``` - -### 4. Rename Files for Clarity - -| Current | Proposed | Reason | -|---------|----------|--------| -| ai-prompts-for-epic-management.md | 03-ai-prompts.md | Clearer name, numbered sequence | -| detailed-kanban-workflow.md | 04-workflow-examples.md | More accurate description | -| ci-integration-examples.md | 05-ci-integration.md | Consistent naming | -| beads-example.md | beads-guide.md | "Guide" is more descriptive than "example" | - -### 5. Add Cross-References - -Each file should clearly point to related files: - -```markdown -# ai-prompts.md - -See [workflow-examples.md](04-workflow-examples.md) for examples of the JSON structures these prompts generate. - -See [ci-integration.md](05-ci-integration.md) for CI/CD integration patterns. -``` - ---- - -## Implementation Plan - -### Phase 1: Create New Structure (No Breaking Changes) -1. Create `01-getting-started.md` -2. Create `02-choosing-tools.md` (extract from README) -3. Keep existing files unchanged - -### Phase 2: Consolidate Content -1. Merge duplicate epic content between ai-prompts and detailed-kanban -2. Update README to be navigation hub only -3. Add cross-references between files - -### Phase 3: Rename (Breaking Changes) -1. Rename files with numbered prefixes -2. Update all internal links -3. Update main README.md references - -### Phase 4: Validate -1. Check all internal links work -2. Test user journey from README → 01 → 02 → etc. -3. Verify no orphaned content - ---- - -## Success Metrics - -✅ **Mutually Exclusive**: Each file has a clear, non-overlapping purpose -✅ **Collectively Exhaustive**: All topics covered, no gaps -✅ **Logical Flow**: Clear learning path from basics → advanced -✅ **Easy Navigation**: README acts as effective hub -✅ **No Duplication**: Single source of truth for each topic - ---- - -## Priority Recommendations - -### 🔴 CRITICAL Priority (Do Immediately) -1. **Update task sizing everywhere** - Change "4-8 hours" to "<1 hour" across all files - - This is a fundamental conceptual error for AI-assisted development - - Affects: README.md, ai-prompts-for-epic-management.md, detailed-kanban-workflow.md, ci-integration-examples.md, beads-example.md - - Impact: Changes user expectations and workflow design - -### 🔴 High Priority (Do First) -2. **Slim down README.md** - Make it a navigation hub -3. **Merge epic content** - Consolidate ai-prompts and detailed-kanban -4. **Create getting-started.md** - Fill the conceptual gap, emphasize AI-first approach - -### 🟡 Medium Priority -5. **Add cross-references** - Link related files -6. **Rename files** - Numbered sequence for clarity - -### 🟢 Low Priority -7. **Create tool-comparison.md** - Separate if README gets too long -8. **Add diagrams** - Visual learning path with AI-assisted timing - ---- - -## Conclusion - -The current structure has **good content** but **poor organization**. The recommended restructuring will: -- Eliminate duplication (MECE compliance) -- Create clear learning path (logical flow) -- Make README an effective navigation hub -- Improve discoverability and user experience - -**Next step:** Implement Phase 1 (create new files without breaking existing structure). diff --git a/examples/issue-generation/README.md b/examples/issue-generation/README.md index b89db53..94f789f 100644 --- a/examples/issue-generation/README.md +++ b/examples/issue-generation/README.md @@ -1,6 +1,8 @@ # AI Issue Generation Examples -Learn how to generate Kanban-optimized issues for AI-assisted development with <1 hour cycle times. +Learn how to generate small, deployable work items for AI-assisted development with <1 hour cycle times. + +> **Pattern Definition**: This directory provides implementation examples for the [Issue Generation pattern](../../README.md#issue-generation) - an intermediate-level foundation pattern that uses AI to generate small work items (<1 hour) from requirements, ensuring continuous delivery with clear acceptance criteria and dependencies. Works with any methodology (Kanban, Scrum, or ad-hoc workflows). ## 🚀 Quick Start @@ -24,14 +26,15 @@ Learn how to generate Kanban-optimized issues for AI-assisted development with < ├── 04-workflow-examples.md # Epic breakdown and relationship patterns ├── 05-ci-integration.md # CI/CD integration and traceability ├── beads-guide.md # Beads setup and usage guide -├── issue-generator.py # Python script for automated generation -└── ANALYSIS.md # MECE analysis and restructuring notes +└── issue-generator.py # Python script for automated generation ``` ## Key Concepts ### Why <1 Hour Tasks? +**Methodology-Agnostic**: Whether you use Kanban, Scrum, or continuous delivery, <1 hour tasks enable rapid feedback and reduce risk. + AI-assisted development is fundamentally faster than manual coding: | Activity | Manual | AI-Assisted | @@ -49,11 +52,13 @@ See [01-getting-started.md](01-getting-started.md) for detailed velocity compari ### Core Principles -1. **Flow over estimates**: Split work until each task is <1 hour +1. **Small batch sizing**: Split work until each task is <1 hour (enables continuous delivery) 2. **Independent deployment**: Every task ships without waiting 3. **RED/GREEN/REFACTOR**: Test-first, minimal implementation, then clean 4. **CI/CD always**: Every task runs through the pipeline +**Works with any methodology**: These principles support Kanban (continuous flow), Scrum (sprint tasks), or ad-hoc delivery. + ## Tool Decision Framework ### Choose Beads if: @@ -185,7 +190,6 @@ A: Yes! See hybrid approach in [02-choosing-tools.md#hybrid-approach](02-choosin ## Resources - **Python Script**: [issue-generator.py](issue-generator.py) - Automated issue generation -- **Analysis**: [ANALYSIS.md](ANALYSIS.md) - MECE analysis of this directory structure - **Main Pattern**: [../../README.md#issue-generation](../../README.md#issue-generation) - Pattern documentation ## Getting Help diff --git a/experiments/README.md b/experiments/README.md index 5d3a47c..46654ac 100644 --- a/experiments/README.md +++ b/experiments/README.md @@ -10,6 +10,10 @@ These experimental patterns extend the core AI development patterns with advance - **[Operations Automation](#operations-automation)** - Experimental automation patterns for CI/CD and production management - **[Monitoring & Intelligence](#monitoring--intelligence)** - Advanced observability and predictive maintenance patterns +## Pattern Exploration + +**[NOTES.md](NOTES.md)** - Tracks patterns under early exploration before formalization. This is where new pattern ideas are documented, evaluated, and refined before becoming full experimental patterns. Current explorations include voice-to-code interfaces and other emerging AI development approaches. + ## Experimental Pattern Reference | Pattern | Maturity | Type | Description | Dependencies | @@ -35,6 +39,7 @@ These experimental patterns extend the core AI development patterns with advance | **[Image Spec](#image-spec)** | Intermediate | Development | Upload images (diagrams, mockups, flows) as primary specifications for AI coding tools to build accurate implementations from visual context | Spec-Driven Development, Progressive Enhancement, Context Optimization | | **[Event Automation](#event-automation)** | Intermediate | Development | Execute custom commands automatically at specific lifecycle events in AI coding assistants to enforce policies and automate workflows | Codified Rules, Security Sandbox | | **[Custom Commands](#custom-commands)** | Intermediate | Development | Discover and use built-in command vocabularies, then extend them with custom commands that encode domain expertise and project-specific workflows | Event Automation, Spec-Driven Development | +| **[Progressive Disclosure](#progressive-disclosure)** | Intermediate | Development | Load AI assistant rules incrementally based on task context to prevent instruction saturation and maintain consistency | Codified Rules, Context Optimization | | **[Asynchronous Research](#asynchronous-research)** | Intermediate | Development | Use fire-and-forget coding agents in dedicated repositories to conduct autonomous code investigations that prove technical feasibility through executable experiments | Parallel Agents, Context Persistence, Choice Generation | | **[Centralized Rules](#centralized-rules)** | Advanced | Operations | Enforce organization-wide AI rules through a central gateway service or shared SDK library rather than distributing configuration files | Codified Rules, Policy Generation, Security Orchestration | @@ -703,6 +708,466 @@ Deploy to database: $1 (default: $STAGING_DB) --- +### Progressive Disclosure + +**Maturity**: Intermediate +**Description**: Load AI assistant rules incrementally based on task context rather than bundling all instructions upfront, preventing context bloat and maintaining instruction-following consistency across any AI coding assistant (Claude Code, Cursor, Aider, etc.). + +**Related Patterns**: [Codified Rules](../README.md#codified-rules), [Context Optimization](#context-optimization), [Custom Commands](#custom-commands), [Event Automation](#event-automation) + +**Source**: HumanLayer, "Context engineering: Why your CLAUDE.md is probably too long" (research on instruction limits and context optimization) + +#### Core Problem + +**Instruction saturation**: LLMs can follow ~150-200 instructions with reasonable consistency. AI coding assistants' system prompts already contain ~50 instructions, leaving ~100-150 for your project rules. Loading all rules every session causes: + +- Linear decay in instruction-following accuracy +- Context window waste on irrelevant rules +- Cognitive overload for the AI +- Slower response times from processing unnecessary context + +**Example of bloat**: A 500-line configuration file (CLAUDE.md, AGENTS.md, .cursorrules, .aiderules, etc.) with security rules, deployment procedures, architecture patterns, testing standards, code style guides, API conventions, database migration rules, monitoring setup, and team workflows—but only 10% is relevant to any single task. + +#### Implementation Strategy + +**Three-tier rule architecture:** + +This pattern works with any AI assistant configuration file. Examples shown use CLAUDE.md, but apply equally to AGENTS.md (OpenCode/Zed), .cursorrules (Cursor), .aiderules (Aider), or other AI coding assistant configuration files. + +``` +.ai/ +├── CLAUDE.md # Main rules file: Universal rules only (<60 lines) +│ # (or AGENTS.md, .cursorrules, .aiderules, etc.) +├── rules/ # Specialized rules loaded on-demand +│ ├── security/ +│ │ ├── secrets.md # Load when: editing .env, credentials +│ │ ├── dependencies.md # Load when: package.json, requirements.txt +│ │ └── authentication.md # Load when: auth/ directory work +│ ├── development/ +│ │ ├── api-design.md # Load when: working in api/ or routes/ +│ │ ├── database.md # Load when: migrations/, models/ +│ │ ├── testing.md # Load when: tests/ or spec files +│ │ └── frontend.md # Load when: components/, styles/ +│ ├── operations/ +│ │ ├── deployment.md # Load when: Dockerfile, k8s/, terraform/ +│ │ ├── monitoring.md # Load when: logs, metrics, alerts +│ │ └── cicd.md # Load when: .github/workflows/ +│ └── architecture/ +│ ├── patterns.md # Load when: major refactoring +│ └── performance.md # Load when: optimization tasks +└── prompts/ # Reusable task templates + ├── implement-feature.md + └── fix-bug.md +``` + +#### Main Rules File + +**Keep it minimal** - only universally applicable rules. + +This example uses CLAUDE.md, but the same structure applies to AGENTS.md, .cursorrules, .aiderules, or any AI assistant configuration file: + +```markdown +# AI Development Rules + +## Universal Principles (Always Apply) + +### Code Quality +- Write clear, self-documenting code with meaningful names +- Follow existing patterns in the codebase +- Include error handling for all external calls + +### Communication +- Ask clarifying questions before major changes +- Explain non-obvious decisions in comments +- Reference task/issue numbers in commits + +### Safety +- Never commit secrets, API keys, or credentials +- Run tests before committing code changes +- Check git diff before every commit + +### Context Loading (Progressive Disclosure) +When working in specific areas, load specialized rules: + +- **Security work** (auth/, .env, credentials): Read .ai/rules/security/ +- **API development** (api/, routes/): Read .ai/rules/development/api-design.md +- **Database changes** (migrations/, models/): Read .ai/rules/development/database.md +- **Testing** (tests/, specs/): Read .ai/rules/development/testing.md +- **Frontend** (components/, styles/): Read .ai/rules/development/frontend.md +- **Deployment** (Dockerfile, k8s/): Read .ai/rules/operations/deployment.md +- **CI/CD** (.github/workflows/): Read .ai/rules/operations/cicd.md + +**How to load**: "Before proceeding, read the relevant rules from .ai/rules/[category]/" +``` + +**Key insight**: The main file becomes a **router** that tells the AI which specialized rules to load based on context. + +#### Specialized Rules Examples + +**Example: .ai/rules/security/secrets.md** + +```markdown +# Security: Secret Management Rules + +## When to Load +Load this file when working with: +- .env files or environment variables +- credentials.json, secrets.yaml, config files with sensitive data +- Authentication tokens or API keys +- Deployment configurations with passwords + +## Rules + +### Secret Detection +1. Run `gitleaks detect --no-git --source=` before committing +2. Block commits containing patterns: AWS keys, JWT tokens, database passwords +3. Use environment variable references, never hardcoded values + +### Environment Variables +# CORRECT: Reference variables +DATABASE_URL=${DATABASE_URL} +API_KEY=${STRIPE_API_KEY} + +# WRONG: Hardcoded secrets +DATABASE_URL=postgresql://admin:password123@prod-db.com +API_KEY=sk_live_abc123xyz + +### Credential Files +- NEVER edit .env files directly +- Use .env.example templates with placeholder values +- All secrets go in secret management (AWS Secrets Manager, 1Password) + +### Validation +Before committing, verify: +# No secrets in staged files +git diff --cached | gitleaks detect --no-git --verbose --source=/dev/stdin + +# No .env files staged +git diff --cached --name-only | grep -E "(\.env$|credentials)" && exit 1 +``` + +**Example: .ai/rules/development/api-design.md** + +```markdown +# Development: API Design Rules + +## When to Load +Load this file when working with: +- api/, routes/, controllers/ directories +- HTTP endpoint implementation +- API contract changes + +## Rules + +### RESTful Design +- Use standard HTTP methods: GET (read), POST (create), PUT/PATCH (update), DELETE +- Plural nouns for resources: `/users`, `/orders`, not `/getUser` +- Nest related resources: `/users/:id/orders` for user-specific orders + +### Response Format +All API responses must use this structure: +{ + "success": true, + "data": { ... }, + "error": null, + "meta": { + "timestamp": "2025-01-15T10:30:00Z", + "request_id": "abc-123" + } +} + +### Error Handling +// CORRECT: Structured errors +res.status(404).json({ + success: false, + data: null, + error: { + code: "USER_NOT_FOUND", + message: "User with ID 123 not found", + details: { user_id: 123 } + } +}); + +// WRONG: Generic errors +res.status(500).send("Error"); + +### Validation +- Validate all inputs at API boundary +- Return 400 Bad Request with specific validation errors +- Document all endpoints in OpenAPI/Swagger spec +``` + +#### Decision Framework for Rule Loading + +```mermaid +graph TD + A[AI Assistant Receives Task] --> B{Analyze Task Context} + + B -->|File paths mentioned| C[Extract directory/file patterns] + B -->|Task description keywords| D[Identify domain area] + + C --> E{Match Pattern} + D --> E + + E -->|auth/, .env, credentials| F[Load security/ rules] + E -->|api/, routes/| G[Load api-design.md] + E -->|migrations/, models/| H[Load database.md] + E -->|tests/, spec/| I[Load testing.md] + E -->|components/, styles/| J[Load frontend.md] + E -->|Dockerfile, k8s/| K[Load deployment.md] + E -->|.github/workflows/| L[Load cicd.md] + E -->|No specific pattern| M[Use main rules only] + + F --> N[Execute Task with Specialized Context] + G --> N + H --> N + I --> N + J --> N + K --> N + L --> N + M --> N +``` + +#### Automatic Loading with Event Hooks + +Combine Progressive Disclosure with [Event Automation](#event-automation) for automatic context loading: + +```bash +#!/bin/bash +# .ai/hooks/auto-load-context.sh +# Runs before AI tool use to automatically load relevant rules + +FILE_PATH="$TOOL_INPUT_FILE_PATH" +LOADED_RULES="" + +# Security context +if echo "$FILE_PATH" | grep -E "(\.env|credentials|secrets|auth/)" > /dev/null; then + LOADED_RULES="$LOADED_RULES .ai/rules/security/" +fi + +# API development context +if echo "$FILE_PATH" | grep -E "(api/|routes/|controllers/)" > /dev/null; then + LOADED_RULES="$LOADED_RULES .ai/rules/development/api-design.md" +fi + +# Database context +if echo "$FILE_PATH" | grep -E "(migrations/|models/|database/)" > /dev/null; then + LOADED_RULES="$LOADED_RULES .ai/rules/development/database.md" +fi + +# Testing context +if echo "$FILE_PATH" | grep -E "(tests?/|spec/|\.test\.|\.spec\.)" > /dev/null; then + LOADED_RULES="$LOADED_RULES .ai/rules/development/testing.md" +fi + +# Output loaded context as AI message +if [ -n "$LOADED_RULES" ]; then + echo "📋 Auto-loading specialized rules for this context:" + for rule in $LOADED_RULES; do + echo " - $rule" + done + echo "" + echo "AI: Please read these files before proceeding: $LOADED_RULES" +fi + +exit 0 # Allow operation to continue +``` + +**Hook configuration (example for Claude Code, adapt for your AI assistant)**: +```json +{ + "hooks": { + "PreToolUse": [{ + "matcher": "Edit|Write", + "hooks": [{"type": "command", "command": ".ai/hooks/auto-load-context.sh"}] + }] + } +} +``` + +#### Integration with Custom Commands + +Create commands that automatically load relevant context: + +```markdown +--- +description: Implement API endpoint with auto-loaded API design rules +argument-hint: endpoint_name (e.g., "GET /users/:id") +--- + +# API Implementation with Progressive Disclosure + +Before implementing the API endpoint, I will: + +1. **Auto-load specialized context**: + - Read `.ai/rules/development/api-design.md` for API standards + - Read `.ai/rules/security/authentication.md` if endpoint requires auth + - Read `.ai/rules/development/testing.md` for test requirements + +2. **Implement endpoint** following loaded rules: + - RESTful design patterns from api-design.md + - Error handling standards + - Input validation requirements + - Response format consistency + +3. **Generate tests** following testing.md: + - Happy path tests + - Error case coverage + - Authentication/authorization tests + - Input validation tests + +4. **Verify compliance**: + - Check against API design rules + - Run security validation + - Ensure test coverage >80% + +Implement: $ARGUMENTS +``` + +#### Validation & Metrics + +**Measure effectiveness**: + +```bash +# Count instructions in main file (target: <60 lines of actual rules) +grep -v "^#" .ai/CLAUDE.md | grep -v "^$" | wc -l + +# Count specialized rule files (aim for 5-10 domain areas) +find .ai/rules -name "*.md" | wc -l + +# Track context loading patterns (add to event hooks) +echo "$(date): Loaded $LOADED_RULES for $FILE_PATH" >> .ai/context-usage.log + +# Analyze which rules are most frequently loaded +cat .ai/context-usage.log | grep -oE "rules/[^/]+/[^ ]+" | sort | uniq -c | sort -rn +``` + +**Success criteria**: +- Main CLAUDE.md: <60 lines of actual instructions (excluding comments/blank lines) +- Specialized rules: 5-10 focused files, each <100 lines +- Context loading: Automatic via hooks or explicit in commands +- Instruction count per session: <150 total (main + loaded specializations) + +#### Anti-pattern: Bloated Configuration + +**Problem**: Putting all rules in a single configuration file regardless of relevance. + +```markdown +# AI Configuration File - WRONG APPROACH (500+ lines) +# (applies to CLAUDE.md, AGENTS.md, .cursorrules, .aiderules, etc.) + +## Security Rules (100 lines) +- Secret management for .env files +- Dependency scanning procedures +- Authentication implementation standards +- OAuth flow requirements +- API key rotation policies +... + +## Database Rules (80 lines) +- Migration file naming +- Model relationship patterns +- Query optimization guidelines +- Index creation standards +... + +## API Design Rules (90 lines) +- RESTful endpoint patterns +- Response format requirements +- Error handling standards +... + +## Frontend Rules (110 lines) +- Component structure +- State management patterns +- CSS conventions +... + +## Deployment Rules (70 lines) +- Docker build optimization +- Kubernetes manifests +- Blue-green deployment +... + +## Testing Rules (50 lines) +... +``` + +**Why it fails**: +- AI task: "Fix typo in README.md" +- Loaded context: ALL 500 lines of rules (security, database, API, frontend, deployment, testing) +- Relevant context: Maybe 10 lines about code quality and git commit messages +- Result: 490 lines of wasted context, reduced instruction-following accuracy +- Performance: Slower responses, more hallucinations, missed critical instructions + +**Consequences**: +1. **Instruction decay**: With 500+ instructions loaded, AI follows maybe 60-70% accurately +2. **Context waste**: 90% of loaded rules are irrelevant to the task +3. **Maintenance burden**: Editing security rules requires opening 500-line file +4. **Slow responses**: AI processes unnecessary context before every response +5. **Higher costs**: More tokens consumed per interaction +6. **Cognitive overload**: New team members overwhelmed by monolithic config + +**Correct approach**: Progressive Disclosure +- Main file: 40 lines of universal rules + routing instructions +- Specialized files: 8 files × 60 lines = 480 lines total +- Per-task context: 40 (main) + 60 (relevant specialization) = 100 instructions +- Result: 3x better instruction-following, faster responses, easier maintenance + +#### Anti-pattern: Over-Fragmentation + +**Problem**: Creating too many tiny rule files that require constant loading. + +``` +.ai/rules/ +├── api/ +│ ├── get-endpoints.md # 10 lines +│ ├── post-endpoints.md # 12 lines +│ ├── put-endpoints.md # 11 lines +│ ├── delete-endpoints.md # 9 lines +│ ├── error-handling.md # 8 lines +│ ├── validation.md # 15 lines +│ ├── response-format.md # 10 lines +│ └── versioning.md # 7 lines +... +``` + +**Why it fails**: +- API implementation task requires loading 8 different files +- Overhead of reading 8 files > benefit of separation +- Harder to maintain consistency across related rules +- AI must constantly re-read interconnected files + +**Correct approach**: Balance granularity +- Combine related rules: api-design.md (all API rules, ~80 lines) +- Split by clear domains: security/, development/, operations/ +- Aim for 5-10 specialized files, not 50 + +#### Anti-pattern: No Loading Guidance + +**Problem**: Creating specialized rule files but not telling the AI when to load them. + +```markdown +# Main Configuration File (no routing) +# (CLAUDE.md, AGENTS.md, .cursorrules, etc.) +Follow the project coding standards. + +# (Specialized rules exist in .ai/rules/ but AI never knows to load them) +``` + +**Why it fails**: +- AI doesn't know specialized rules exist +- Relies on human to remember: "also read .ai/rules/security/secrets.md" +- No automation or consistency + +**Correct approach**: Explicit routing in main file +- Document WHEN to load each specialized file +- Provide file path patterns that trigger loading +- Use event hooks for automatic loading +- Include loading instructions in custom commands + +--- + ### Asynchronous Research **Maturity**: Intermediate