<metadata>
purpose: Advanced guide to meta-prompts that generate prompts for autonomous execution
type: technical-architecture
course: Tactical Agentic Coding
category: prompt-engineering
difficulty: advanced
dependencies: template-engineering-guide, lesson-03-success-is-planned
last-updated: 2025-09-30
</metadata>

<overview>
Meta-prompts are prompts that build other prompts. They represent the highest leverage point in agentic coding: taking minimal human input and expanding it into comprehensive, executable specifications. This guide covers the architecture, patterns, and implementation of meta-prompt systems.
</overview>

# META-PROMPT ARCHITECTURE

**Advanced Guide to Prompts That Build Prompts**

---

## WHAT IS A META-PROMPT?

### Definition

<definition>
A meta-prompt is a structured prompt that takes minimal input and generates a comprehensive, executable plan or specification. It encodes the process of planning itself, allowing agents to autonomously transform high-level intent into detailed implementation instructions.
</definition>

### The Meta-Prompt Hierarchy

<hierarchy>
<level number="0" name="direct-execution">
<input>Explicit, detailed instructions</input>
<output>Direct execution by agent</output>
<example>
"Create file UserProfile.tsx with interface UserProfileProps containing name:string and email:string, export default functional component that renders a div with className='profile' containing h2 with name and p with email"
</example>
<characteristics>
- Every detail specified
- No ambiguity
- No planning needed
- Agent executes directly
</characteristics>
</level>

<level number="1" name="simple-prompt">
<input>High-level request</input>
<output>Agent attempts execution</output>
<example>
"Create a UserProfile component"
</example>
<characteristics>
- Ambiguous
- Multiple interpretations
- Agent must guess at details
- Multiple clarifying questions
- In-loop back-and-forth
</characteristics>
</level>

<level number="2" name="template-guided">
<input>Request + Template reference</input>
<output>Agent follows template structure</output>
<example>
"Use react-component-template to create UserProfile component"
</example>
<characteristics>
- Structure provided
- Less ambiguity
- Fewer clarifications
- Still requires manual template application
</characteristics>
</level>

<level number="3" name="meta-prompt">
<input>Minimal input</input>
<output>Comprehensive plan generated</output>
<example>
"UserProfile component"
</example>
<characteristics>
- Meta-prompt analyzes input
- Gathers necessary context
- Applies appropriate template
- Generates complete specification
- Agent executes autonomously
</characteristics>
</level>

<level number="4" name="meta-meta-prompt">
<input>Problem class description</input>
<output>Meta-prompt generated</output>
<example>
"Generate meta-prompt for React component creation"
</example>
<characteristics>
- Analyzes problem class
- Creates meta-prompt structure
- Self-generating system
- Ultimate leverage
</characteristics>
</level>
</hierarchy>

### Why Meta-Prompts Matter

<impact-analysis>
<dimension name="compression">
<measurement>Input size to output size ratio</measurement>
<typical-ratio>1:100 to 1:1000</typical-ratio>
<example>
Input: "dark mode" (2 words)
Output: 5-page specification (2000 words)
Compression: 1:1000
</example>
</dimension>

<dimension name="time">
<measurement>Human time to create plan</measurement>
<typical-savings>30-60 minutes → 30 seconds</typical-savings>
<multiplier>60-120x faster</multiplier>
</dimension>

<dimension name="quality">
<measurement>Completeness and consistency</measurement>
<improvement>Human plans miss steps; meta-prompts encode best practices</improvement>
</dimension>

<dimension name="scalability">
<measurement>Reuse potential</measurement>
<value>One meta-prompt used infinitely across team</value>
</dimension>
</impact-analysis>

---

## PROMPTS THAT BUILD PROMPTS

### The Core Pattern

<pattern-structure>
<component name="input-parsing">
<purpose>Extract intent from minimal input</purpose>
<process>
1. Analyze input format and content
2. Identify key entities (resource names, operations, etc.)
3. Classify intent (create, fix, refactor, etc.)
4. Extract explicit and implicit requirements
</process>
</component>

<component name="context-gathering">
<purpose>Collect all information needed for comprehensive plan</purpose>
<process>
1. Read relevant files
2. Analyze existing patterns
3. Check dependencies and configuration
4. Review recent changes
5. Identify constraints
</process>
</component>

<component name="template-selection">
<purpose>Choose appropriate template for this problem</purpose>
<process>
1. Match input to problem class
2. Select base template
3. Identify required variations
4. Load template structure
</process>
</component>

<component name="plan-generation">
<purpose>Generate complete, executable specification</purpose>
<process>
1. Apply template to context
2. Fill in all variables
3. Generate specific code examples
4. Define validation commands
5. Specify success criteria
</process>
</component>

<component name="validation">
<purpose>Verify generated plan is complete and correct</purpose>
<process>
1. Check all required sections present
2. Verify specificity (no placeholders)
3. Validate commands are runnable
4. Ensure success criteria measurable
</process>
</component>

<component name="output-formatting">
<purpose>Present plan in optimal format for execution</purpose>
<process>
1. Structure for agent consumption
2. Include all context agent needs
3. Make validation unambiguous
4. Write to file (not just chat)
</process>
</component>
</pattern-structure>

### Meta-Prompt Template

```markdown
# META-PROMPT: [Task Type]

## ROLE
You are a [domain] expert creating a comprehensive implementation plan.

## INPUT ANALYSIS

### Expected Input Formats
Handle these input variations:
1. **Minimal:** "[single word or phrase]"
2. **Basic:** "[action] [target]"
3. **Detailed:** "[action] [target] with [requirements]"

### Parsing Logic
```typescript
interface ParsedInput {
  action: string;        // create, fix, update, refactor
  target: string;        // what is being acted on
  requirements: string[]; // explicit requirements
  implied: string[];     // inferred requirements
}
```

## CONTEXT GATHERING

### Files to Read
```bash
[List of glob patterns or specific files]
```

### Information to Extract
- [Key pattern 1 to look for]
- [Key pattern 2 to look for]
- [Configuration details]
- [Naming conventions]

### Context Validation
Verify extracted context includes:
- [ ] [Critical element 1]
- [ ] [Critical element 2]
- [ ] [etc.]

## TEMPLATE SELECTION

### Decision Tree
```
If input matches [pattern A]:
  Use template: [template-a]
Else if input matches [pattern B]:
  Use template: [template-b]
Else:
  Ask for clarification on:
    - [ambiguity 1]
    - [ambiguity 2]
```

## PLAN GENERATION

### Structure
Generate plan with these sections:

#### 1. CONTEXT
- Current state of system
- Files involved (specific paths)
- Relevant patterns identified
- Constraints and dependencies

#### 2. REQUIREMENTS
- Explicit requirements (from input)
- Implicit requirements (inferred)
- Edge cases to handle
- Acceptance criteria

#### 3. IMPLEMENTATION
- Step-by-step instructions
- Specific code for each step
- File-by-file changes
- Testing requirements

#### 4. VALIDATION
- Commands to run (exact syntax)
- Expected output for each command
- Success criteria (measurable)
- Failure recovery steps

### Variable Substitution
Replace template variables with specific values:
- `[ResourceName]` → [actual resource name]
- `[ActionType]` → [actual action]
- `[Field1, Field2]` → [actual fields]

### Code Generation
For each code block in template:
1. Apply context-specific patterns
2. Use actual names from input
3. Follow conventions from codebase analysis
4. Include complete, runnable code

## VALIDATION RULES

### Completeness Check
Generated plan must have:
- [ ] All sections from template filled
- [ ] No placeholder variables remaining
- [ ] Specific file paths (not generic)
- [ ] Runnable commands (not pseudocode)
- [ ] Measurable success criteria

### Quality Check
- [ ] Code examples follow project conventions
- [ ] Validation commands are comprehensive
- [ ] Edge cases considered
- [ ] Rollback strategy defined

### Specificity Check
- [ ] "Update the component" → "Update UserProfile.tsx lines 23-45"
- [ ] "Add a test" → "Create UserProfile.test.tsx with tests for rendering, props, and interactions"
- [ ] "Run tests" → "npm run test -- UserProfile.test.tsx --coverage"

## OUTPUT FORMAT

### File Location
Write plan to: `/specs/[type]/[date]-[slug].md`

Example: `/specs/features/2024-09-30-add-user-profile-component.md`

### File Structure
```markdown
# [TYPE]: [Title]

**Created:** [ISO date]
**Status:** planned
**Type:** [chore|bug|feature|refactor]
**Estimated Time:** [X hours]

[Complete plan following template structure]
```

## ERROR HANDLING

### Insufficient Input
If input is too vague:
```
Your input "[input]" could mean:
1. [Interpretation 1]
2. [Interpretation 2]

Please specify:
- [Clarifying question 1]
- [Clarifying question 2]
```

### Missing Context
If required context not found:
```
Cannot generate plan: Missing required context
- [Missing item 1]: [Where to create it]
- [Missing item 2]: [Where to create it]

Please [action to resolve].
```

### Template Not Found
If no appropriate template:
```
No template found for: [input]

Closest matches:
- [Template 1]: [Why it might work]
- [Template 2]: [Why it might work]

Or describe your task in more detail.
```

## SELF-IMPROVEMENT

### Learn from Execution
After plan execution:
1. Did validation pass first time?
2. Were manual changes needed?
3. Was anything missing from plan?
4. Could plan be improved?

### Update Meta-Prompt
If patterns emerge:
- Add to input parsing
- Update context gathering
- Improve code generation
- Refine validation

## EXAMPLES

### Example 1: Minimal Input
**Input:** "Button"

**Analysis:**
- Action: create (implied)
- Target: Button component
- Requirements: (none explicit, infer from patterns)

**Context Gathered:**
- Recent components use functional style
- Props typically: children, onClick, disabled, variant
- Tests required with >80% coverage
- Storybook stories needed

**Generated Plan:**
[Complete 3-page specification for Button component]

### Example 2: Detailed Input
**Input:** "Create DataTable component with sorting, filtering, and pagination"

**Analysis:**
- Action: create (explicit)
- Target: DataTable component
- Requirements: sorting, filtering, pagination (explicit)

**Context Gathered:**
- Existing table components for pattern reference
- Pagination typically server-side
- Sorting state management approach
- Filter implementation pattern

**Generated Plan:**
[Complete 8-page specification for DataTable component with all requirements]

### Example 3: Bug Input
**Input:** "API returns 500 on POST /users"

**Analysis:**
- Action: fix (implied)
- Target: POST /users endpoint
- Requirements: stop 500 error (implied: return correct status)

**Context Gathered:**
- Recent changes to user endpoint
- Error logs for this endpoint
- User model and validation rules
- Related endpoint implementations

**Generated Plan:**
[Complete debugging and fix plan with investigation steps]
```

---

## SELF-GENERATING SPECIFICATIONS

### The Self-Generation Loop

<loop-structure>
<phase name="input">
<entry-point>Human provides minimal intent</entry-point>
<example>"Add user authentication"</example>
</phase>

<phase name="expansion">
<process>Meta-prompt expands intent into detailed requirements</process>
<example>
Authentication becomes:
- User registration
- User login
- Password hashing
- Session management
- JWT tokens
- Forgot password flow
- Email verification
- Role-based access control
</example>
</phase>

<phase name="specification">
<process>Requirements expand into implementation plan</process>
<example>
Each requirement becomes:
- Files to create/modify
- Code to write
- Tests to add
- Validation commands
- Success criteria
</example>
</phase>

<phase name="execution">
<process>Agent executes specification autonomously</process>
<example>
Agent:
- Creates all files
- Implements all logic
- Writes all tests
- Runs all validation
- Reports results
</example>
</phase>

<phase name="feedback">
<process>Results inform future specifications</process>
<example>
- What worked well?
- What needed manual intervention?
- How to improve meta-prompt?
</example>
</phase>
</loop-structure>

### Specification Quality Criteria

<quality-dimensions>
<dimension name="completeness">
<definition>All necessary information present</definition>
<check>Can agent execute without asking questions?</check>
<bad-example>"Add validation to the form"</bad-example>
<good-example>
"Add Zod validation to ContactForm.tsx:
- name: string, min 1, max 100
- email: string, email format
- message: string, min 10, max 1000
Display errors below each field in red text
Disable submit button until validation passes"
</good-example>
</dimension>

<dimension name="specificity">
<definition>Concrete details, not abstractions</definition>
<check>Are file paths, function names, variable names specified?</check>
<bad-example>"Update the authentication logic"</bad-example>
<good-example>
"In src/auth/login.ts, update validatePassword function (lines 45-67):
- Add bcrypt comparison
- Add rate limiting (5 attempts per 15 min)
- Add logging for failed attempts
- Return specific error messages"
</good-example>
</dimension>

<dimension name="testability">
<definition>Clear validation and success criteria</definition>
<check>Can success be verified automatically?</check>
<bad-example>"Make it work better"</bad-example>
<good-example>
"Validation:
```bash
npm run test -- login.test.ts
# All 12 tests must pass

npm run test:integration -- auth-flow
# Login flow completes in <500ms
# Failed attempts are logged
# Rate limiting blocks after 5 attempts
```"
</good-example>
</dimension>

<dimension name="contextuality">
<definition>Fits with existing codebase patterns</definition>
<check>Does it follow project conventions?</check>
<bad-example>"Use whatever auth library you want"</bad-example>
<good-example>
"Use existing AuthService pattern (see UserAuthService.ts example):
- Extend BaseAuthService
- Implement authenticate() method
- Use existing TokenManager for JWT
- Follow error handling pattern from LoginService"
</good-example>
</dimension>

<dimension name="executability">
<definition>Agent can execute without human in loop</definition>
<check>Are all steps actionable by agent?</check>
<bad-example>"Design a good user interface"</bad-example>
<good-example>
"Create LoginForm.tsx:
```tsx
// Exact component structure provided
import { FormField } from './FormField';
export const LoginForm = () => {
  return (
    <form onSubmit={handleSubmit}>
      <FormField name='email' type='email' />
      <FormField name='password' type='password' />
      <button type='submit'>Login</button>
    </form>
  );
};
```
Follow this structure exactly."
</good-example>
</dimension>
</quality-dimensions>

---

## TEMPLATE → META-PROMPT → PLAN → EXECUTION PIPELINE

### The Complete Pipeline

<pipeline>
<stage number="1" name="template-creation">
<input>Manual engineering process</input>
<process>Engineer documents workflow once</process>
<output>Reusable template</output>
<time>2-4 hours once</time>
</stage>

<stage number="2" name="meta-prompt-creation">
<input>Template</input>
<process>Encode template application logic</process>
<output>Meta-prompt that uses template</output>
<time>1-2 hours once</time>
</stage>

<stage number="3" name="invocation">
<input>Minimal user input</input>
<process>User provides 1-10 words</process>
<output>Meta-prompt triggered</output>
<time>5 seconds</time>
</stage>

<stage number="4" name="context-gathering">
<input>Meta-prompt + codebase</input>
<process>Agent reads relevant files, analyzes patterns</process>
<output>Complete context</output>
<time>10-30 seconds</time>
</stage>

<stage number="5" name="plan-generation">
<input>Meta-prompt + context + template</input>
<process>Agent generates comprehensive specification</process>
<output>5-20 page implementation plan</output>
<time>20-60 seconds</time>
</stage>

<stage number="6" name="plan-review">
<input>Generated plan</input>
<process>Human or automated review (optional)</process>
<output>Approved plan</output>
<time>0-5 minutes</time>
</stage>

<stage number="7" name="execution">
<input>Approved plan</input>
<process>Agent implements step by step</process>
<output>Working implementation</output>
<time>2-60 minutes</time>
</stage>

<stage number="8" name="validation">
<input>Implementation</input>
<process>Agent runs all validation commands</process>
<output>Test results, build status</output>
<time>1-5 minutes</time>
</stage>

<stage number="9" name="completion">
<input>Validation results</input>
<process>If pass: done. If fail: fix and re-validate</process>
<output>Production-ready code</output>
<time>0-30 minutes (depending on issues)</time>
</stage>
</pipeline>

### Pipeline Efficiency Analysis

<efficiency>
<traditional-approach>
<steps>
1. Human thinks about solution (15 min)
2. Human writes plan (optional, 20 min)
3. Human writes code (60 min)
4. Human writes tests (30 min)
5. Human runs validation (5 min)
6. Human fixes issues (20 min)
7. Human re-validates (5 min)
Total: 155 minutes
</steps>
</traditional-approach>

<meta-prompt-approach>
<steps>
1. Human provides input (5 sec)
2. Meta-prompt generates plan (30 sec)
3. Agent executes (20 min)
4. Agent validates (2 min)
5. Agent fixes if needed (5 min)
Total: 27 minutes
</steps>
</meta-prompt-approach>

<comparison>
Time savings: 155min - 27min = 128 minutes (83% reduction)
Human time: 155min vs 5 seconds (99.995% reduction)
Quality: Consistent (follows best practices encoded in template)
</comparison>
</efficiency>

---

## EXAMPLES: CHORE, BUG, FEATURE TEMPLATES

### Chore Meta-Prompt

```markdown
# META-PROMPT: Chore Executor

## ROLE
You are a senior DevOps engineer handling routine maintenance tasks.

## INPUT ANALYSIS

### Chore Types
- **dependency-update:** Update project dependencies
- **config-change:** Modify configuration
- **cleanup:** Remove unused code/files
- **format:** Apply code formatting
- **docs:** Update documentation
- **backup:** Create backups

### Input Patterns
1. "[chore-type]"
2. "[chore-type] [target]"
3. "[action] [target]"

### Parsing
```typescript
const chorePatterns = {
  'update deps': 'dependency-update',
  'update dependencies': 'dependency-update',
  'upgrade': 'dependency-update',
  'format code': 'format',
  'clean': 'cleanup',
  'backup': 'backup'
};
```

## CONTEXT GATHERING

### For dependency-update:
```bash
cat package.json
npm outdated
git log --since="1 week ago" -- package.json
cat CHANGELOG.md
```

Extract:
- Current versions
- Available updates
- Recent dependency changes
- Known issues from changelog

### For config-change:
```bash
find . -name "*.config.js" -o -name "*.config.ts"
cat [config-files]
git log --since="1 month ago" -- "*config*"
```

Extract:
- Configuration files
- Current settings
- Recent config changes

### For format:
```bash
cat .prettierrc
cat .eslintrc
npm run format -- --check
```

Extract:
- Formatter config
- Files needing formatting

## TEMPLATE SELECTION

```typescript
const templates = {
  'dependency-update': 'templates/chores/update-dependencies.md',
  'config-change': 'templates/chores/modify-config.md',
  'cleanup': 'templates/chores/cleanup-code.md',
  'format': 'templates/chores/format-code.md',
  'docs': 'templates/chores/update-docs.md',
  'backup': 'templates/chores/create-backup.md'
};
```

## PLAN GENERATION

### Example: dependency-update

**Input:** "update dependencies"

**Generated Plan:**
```markdown
# CHORE: Update Project Dependencies

**Created:** 2024-09-30
**Type:** chore
**Estimated Time:** 15 minutes

## CONTEXT
- Current Node.js: v18.17.0
- Package Manager: npm
- Dependencies: 47 total
- Outdated: 12 packages

## OUTDATED PACKAGES
| Package | Current | Latest | Type |
|---------|---------|--------|------|
| react | 18.2.0 | 18.3.1 | Minor |
| typescript | 5.1.6 | 5.3.2 | Minor |
| eslint | 8.45.0 | 8.56.0 | Minor |

## RISK ASSESSMENT
- Patch updates: 8 packages (low risk)
- Minor updates: 4 packages (medium risk)
- Major updates: 0 packages (no high risk)

## IMPLEMENTATION PLAN

### Phase 1: Patch Updates
```bash
npm update
```

### Phase 2: Minor Updates
```bash
npm install react@18.3.1
npm install typescript@5.3.2
npm install eslint@8.56.0
```

### Phase 3: Test After Each
```bash
npm run test
npm run type-check
npm run lint
npm run build
```

## VALIDATION
```bash
npm run test          # Expected: All pass
npm run type-check    # Expected: No errors
npm run lint          # Expected: No errors
npm run build         # Expected: Success
npm run start &       # Expected: App starts
sleep 5
curl http://localhost:3000/health  # Expected: 200 OK
kill %1
```

## SUCCESS CRITERIA
- [ ] All packages updated to latest
- [ ] All tests pass
- [ ] No type errors
- [ ] Build succeeds
- [ ] Application runs

## ROLLBACK
```bash
git checkout package.json package-lock.json
npm install
```
```

## OUTPUT FORMAT
Write to: `/specs/chores/2024-09-30-update-dependencies.md`

## VALIDATION RULES
- [ ] Specific versions listed
- [ ] Risk assessment included
- [ ] Validation commands complete
- [ ] Rollback plan present
```

### Bug Meta-Prompt

```markdown
# META-PROMPT: Bug Hunter

## ROLE
You are a senior debugging specialist with systematic problem-solving skills.

## INPUT ANALYSIS

### Bug Report Formats
1. **Error message:** "[Error text]"
2. **Symptom:** "[What's wrong]"
3. **Endpoint failure:** "[Method] [URL] returns [status]"
4. **Feature broken:** "[Feature] doesn't work"

### Severity Classification
```typescript
const severity = {
  '500 error': 'high',
  'crashes': 'critical',
  'incorrect behavior': 'medium',
  'typo': 'low',
  'performance': 'medium-high'
};
```

## CONTEXT GATHERING

### For API errors:
```bash
# Recent error logs
grep -i "error" logs/app.log | tail -100

# Recent changes to endpoint
git log --since="1 week ago" -- api/routes/*.ts

# Related test failures
npm run test -- --listTests | grep [endpoint]
```

### For UI bugs:
```bash
# Recent changes to component
git log --since="1 week ago" -- src/components/[Component]*

# Browser console errors
# (Manual: Ask user to check console)

# Related components
grep -r "import.*[Component]" src/
```

### For performance issues:
```bash
# Recent performance changes
git log --since="2 weeks ago" -- --grep="performance\|optimize"

# Slow queries
grep "SLOW_QUERY" logs/db.log
```

## TEMPLATE SELECTION

```typescript
const bugTemplates = {
  'api-error': 'templates/bugs/debug-api-error.md',
  'ui-bug': 'templates/bugs/debug-frontend-error.md',
  'performance': 'templates/bugs/fix-performance-issue.md',
  'security': 'templates/bugs/fix-security-vulnerability.md',
  'memory-leak': 'templates/bugs/fix-memory-leak.md'
};
```

## PLAN GENERATION

### Example: api-error

**Input:** "POST /users returns 500"

**Generated Plan:**
```markdown
# BUG: API 500 Error on User Creation

**Created:** 2024-09-30
**Type:** bug
**Severity:** high
**Estimated Time:** 30-60 minutes

## CONTEXT
**Endpoint:** POST /users
**Error:** HTTP 500 Internal Server Error
**First Seen:** 2024-09-30 09:15 UTC (4 hours ago)
**Frequency:** 100% of attempts
**Environment:** Production

**Recent Changes:**
- 2024-09-29: Updated email validation (commit a1b2c3d)
- 2024-09-28: Added user role field (commit d4e5f6g)

**Files Involved:**
- api/routes/users.ts
- api/controllers/userController.ts
- api/models/User.ts
- api/validation/userValidation.ts

## ERROR LOGS
```
[2024-09-30 09:15:23] ERROR: POST /users failed
ValidationError: User validation failed: role: Path `role` is required.
  at Model.Document.invalidate (/app/node_modules/mongoose/lib/document.js:2642:32)
  at /app/api/models/User.ts:45:12
```

## ROOT CAUSE HYPOTHESIS
Recent commit added `role` field as required, but:
1. Validation schema may not include it
2. Request body may not provide it
3. Default value may be missing

**Likelihood:** 90% - error message clearly points to role field

## INVESTIGATION STEPS

### Step 1: Verify Current Validation
```bash
cat api/validation/userValidation.ts
```
Expected: Check if `role` field is in validation schema

### Step 2: Check Model Definition
```bash
cat api/models/User.ts | grep -A 5 "role"
```
Expected: Verify if `role` is required and has default

### Step 3: Review Recent Changes
```bash
git show d4e5f6g
```
Expected: See what was changed in role commit

### Step 4: Test Locally
```bash
curl -X POST http://localhost:3000/api/users \
  -H "Content-Type: application/json" \
  -d '{"name":"Test","email":"test@example.com"}'
```
Expected: Reproduce error

## IMPLEMENTATION

### Option 1: Add to Validation (If missing)
```typescript
// api/validation/userValidation.ts
export const createUserSchema = z.object({
  name: z.string().min(1),
  email: z.string().email(),
  role: z.enum(['user', 'admin']).default('user')  // ADD THIS
});
```

### Option 2: Add Default to Model (If missing)
```typescript
// api/models/User.ts
const UserSchema = new Schema({
  name: { type: String, required: true },
  email: { type: String, required: true },
  role: { type: String, required: true, default: 'user' }  // ADD DEFAULT
});
```

### Option 3: Make Optional (If shouldn't be required)
```typescript
// api/models/User.ts
const UserSchema = new Schema({
  role: { type: String, required: false }  // CHANGE TO FALSE
});
```

## VALIDATION
```bash
# Unit test
npm run test -- userController.test.ts

# Integration test
npm run test:integration -- api/users

# Manual test
curl -X POST http://localhost:3000/api/users \
  -H "Content-Type: application/json" \
  -d '{"name":"Test","email":"test@example.com"}'
# Expected: 201 Created

# Test with role explicitly provided
curl -X POST http://localhost:3000/api/users \
  -H "Content-Type: application/json" \
  -d '{"name":"Test","email":"test@example.com","role":"admin"}'
# Expected: 201 Created

# Check logs
grep "POST /users" logs/app.log
# Expected: No errors
```

## SUCCESS CRITERIA
- [ ] POST /users returns 201 on valid input
- [ ] User created in database
- [ ] No 500 errors in logs
- [ ] Tests pass
- [ ] Works with and without role in request

## PREVENTION
1. Add test case for creating user without role
2. Add API documentation for all required fields
3. Add migration for existing users without role
4. Add monitoring alert for 500 errors on this endpoint
```

## VALIDATION RULES
- [ ] Root cause identified or hypothesis stated
- [ ] Investigation steps are specific
- [ ] Multiple solution options provided
- [ ] Prevention measures included
```

### Feature Meta-Prompt

```markdown
# META-PROMPT: Feature Builder

## ROLE
You are a senior full-stack architect building production-ready features.

## INPUT ANALYSIS

### Feature Request Formats
1. **Resource CRUD:** "Add [Resource]" or "[Resource] management"
2. **Specific feature:** "[Feature] that does [X]"
3. **Integration:** "Integrate with [Service]"
4. **Enhancement:** "Add [functionality] to [existing feature]"

### Complexity Classification
```typescript
const complexity = {
  'crud-api': 'medium',
  'custom-ui': 'medium-high',
  'auth-flow': 'high',
  'payment-integration': 'high',
  'simple-form': 'low'
};
```

## CONTEXT GATHERING

### For CRUD features:
```bash
# Existing similar resources
ls api/routes/*.ts
cat api/routes/[similar-resource].ts

# Database models
ls api/models/*.ts
cat api/models/[similar-model].ts

# Frontend components
ls src/components/*/*.tsx
```

### For UI features:
```bash
# Component patterns
find src/components -name "*.tsx" | head -5 | xargs cat

# State management
cat src/store/*.ts

# API client
cat src/api/client.ts
```

### For integrations:
```bash
# Existing integrations
ls integrations/*.ts

# Environment variables
grep "_KEY\|_SECRET\|_TOKEN" .env.example

# API documentation
cat docs/integrations/*.md
```

## TEMPLATE SELECTION

```typescript
const featureTemplates = {
  'crud-api': 'templates/features/add-crud-endpoint.md',
  'react-component': 'templates/features/add-react-component.md',
  'database-table': 'templates/features/add-database-table.md',
  'auth': 'templates/features/add-authentication.md',
  'integration': 'templates/features/add-integration.md'
};
```

## PLAN GENERATION

### Example: CRUD API

**Input:** "Add Product management"

**Generated Plan:**
```markdown
# FEATURE: Add Product Management API

**Created:** 2024-09-30
**Type:** feature
**Complexity:** medium
**Estimated Time:** 2-3 hours

## CONTEXT

**Resource:** Product
**Operations:** CRUD (Create, Read, Update, Delete, List)
**Authentication:** Required (JWT)
**Authorization:** Admin for Create/Update/Delete, Any authenticated for Read/List

**Similar Resources:** User, Order (for pattern reference)

**Database:** PostgreSQL with Prisma ORM

**Files to Create:**
- api/routes/products.ts
- api/controllers/productController.ts
- api/models/product.model.ts
- api/validation/productValidation.ts
- api/tests/products.test.ts

## REQUIREMENTS

### Functional
- Create new product (admin only)
- List products with pagination, filtering, sorting
- Get single product by ID
- Update product (admin only)
- Delete product (soft delete, admin only)
- Search products by name

### Non-Functional
- Response time <200ms
- Pagination max 100 items
- Input validation on all fields
- Proper error messages
- API documentation (OpenAPI)

### Fields
```typescript
interface Product {
  id: string;              // UUID
  name: string;            // 1-255 chars
  description: string;     // 0-2000 chars
  price: number;           // >0, max 2 decimals
  stock: number;           // >=0, integer
  category: string;        // enum: electronics, clothing, food, other
  imageUrl?: string;       // Optional, valid URL
  active: boolean;         // Default true
  createdAt: Date;
  updatedAt: Date;
  deletedAt?: Date;        // For soft delete
}
```

## IMPLEMENTATION PLAN

### Step 1: Database Model (5 min)
```typescript
// api/models/product.model.ts
import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

export class ProductModel {
  async create(data: ProductCreateInput) {
    return prisma.product.create({ data });
  }

  async findMany({ skip, take, where, orderBy }) {
    const [items, total] = await Promise.all([
      prisma.product.findMany({ skip, take, where, orderBy }),
      prisma.product.count({ where })
    ]);
    return { items, total };
  }

  async findById(id: string) {
    return prisma.product.findUnique({ where: { id } });
  }

  async update(id: string, data: ProductUpdateInput) {
    return prisma.product.update({ where: { id }, data });
  }

  async softDelete(id: string) {
    return prisma.product.update({
      where: { id },
      data: { deletedAt: new Date(), active: false }
    });
  }
}
```

### Step 2: Validation Schema (5 min)
```typescript
// api/validation/productValidation.ts
import { z } from 'zod';

const productCategories = ['electronics', 'clothing', 'food', 'other'] as const;

export const createProductSchema = z.object({
  body: z.object({
    name: z.string().min(1).max(255),
    description: z.string().max(2000).optional().default(''),
    price: z.number().positive().multipleOf(0.01),
    stock: z.number().int().min(0),
    category: z.enum(productCategories),
    imageUrl: z.string().url().optional(),
    active: z.boolean().optional().default(true)
  })
});

export const updateProductSchema = z.object({
  params: z.object({
    id: z.string().uuid()
  }),
  body: z.object({
    name: z.string().min(1).max(255).optional(),
    description: z.string().max(2000).optional(),
    price: z.number().positive().multipleOf(0.01).optional(),
    stock: z.number().int().min(0).optional(),
    category: z.enum(productCategories).optional(),
    imageUrl: z.string().url().optional(),
    active: z.boolean().optional()
  })
});

export const listProductsSchema = z.object({
  query: z.object({
    page: z.string().regex(/^\d+$/).transform(Number).optional().default('1'),
    limit: z.string().regex(/^\d+$/).transform(Number).optional().default('20'),
    category: z.enum(productCategories).optional(),
    active: z.enum(['true', 'false']).transform(v => v === 'true').optional(),
    search: z.string().optional()
  })
});
```

### Step 3: Controller (15 min)
```typescript
// api/controllers/productController.ts
import { Request, Response, NextFunction } from 'express';
import { ProductModel } from '../models/product.model';
import { ApiError } from '../utils/api-error';

const model = new ProductModel();

export class ProductController {
  async list(req: Request, res: Response, next: NextFunction) {
    try {
      const { page, limit, category, active, search } = req.query;

      const skip = (Number(page) - 1) * Number(limit);
      const where = {
        ...(category && { category }),
        ...(active !== undefined && { active }),
        ...(search && { name: { contains: search, mode: 'insensitive' } }),
        deletedAt: null
      };

      const result = await model.findMany({
        skip,
        take: Number(limit),
        where,
        orderBy: { createdAt: 'desc' }
      });

      res.json({
        success: true,
        data: result.items,
        meta: {
          page: Number(page),
          limit: Number(limit),
          total: result.total,
          pages: Math.ceil(result.total / Number(limit))
        }
      });
    } catch (error) {
      next(error);
    }
  }

  async get(req: Request, res: Response, next: NextFunction) {
    try {
      const product = await model.findById(req.params.id);

      if (!product || product.deletedAt) {
        throw new ApiError(404, 'Product not found');
      }

      res.json({
        success: true,
        data: product
      });
    } catch (error) {
      next(error);
    }
  }

  async create(req: Request, res: Response, next: NextFunction) {
    try {
      const product = await model.create(req.body);

      res.status(201).json({
        success: true,
        data: product
      });
    } catch (error) {
      next(error);
    }
  }

  async update(req: Request, res: Response, next: NextFunction) {
    try {
      const product = await model.update(req.params.id, req.body);

      res.json({
        success: true,
        data: product
      });
    } catch (error) {
      next(error);
    }
  }

  async delete(req: Request, res: Response, next: NextFunction) {
    try {
      await model.softDelete(req.params.id);

      res.status(204).send();
    } catch (error) {
      next(error);
    }
  }
}
```

### Step 4: Routes (10 min)
```typescript
// api/routes/products.ts
import { Router } from 'express';
import { ProductController } from '../controllers/productController';
import { authenticate } from '../middleware/auth';
import { authorize } from '../middleware/authorize';
import { validate } from '../middleware/validation';
import {
  createProductSchema,
  updateProductSchema,
  listProductsSchema
} from '../validation/productValidation';

const router = Router();
const controller = new ProductController();

router.get('/',
  authenticate,
  validate(listProductsSchema),
  controller.list
);

router.get('/:id',
  authenticate,
  controller.get
);

router.post('/',
  authenticate,
  authorize(['admin']),
  validate(createProductSchema),
  controller.create
);

router.put('/:id',
  authenticate,
  authorize(['admin']),
  validate(updateProductSchema),
  controller.update
);

router.delete('/:id',
  authenticate,
  authorize(['admin']),
  controller.delete
);

export default router;
```

### Step 5: Tests (30 min)
```typescript
// api/tests/products.test.ts
import request from 'supertest';
import app from '../app';
import { setupTestDB, teardownTestDB, createTestUser } from './helpers';

describe('Products API', () => {
  let adminToken: string;
  let userToken: string;

  beforeAll(async () => {
    await setupTestDB();
    const admin = await createTestUser({ role: 'admin' });
    const user = await createTestUser({ role: 'user' });
    adminToken = admin.token;
    userToken = user.token;
  });

  afterAll(async () => {
    await teardownTestDB();
  });

  describe('POST /api/products', () => {
    it('should create product as admin', async () => {
      const response = await request(app)
        .post('/api/products')
        .set('Authorization', `Bearer ${adminToken}`)
        .send({
          name: 'Test Product',
          description: 'Test Description',
          price: 29.99,
          stock: 100,
          category: 'electronics'
        })
        .expect(201);

      expect(response.body.success).toBe(true);
      expect(response.body.data).toHaveProperty('id');
      expect(response.body.data.name).toBe('Test Product');
    });

    it('should reject creation as non-admin', async () => {
      await request(app)
        .post('/api/products')
        .set('Authorization', `Bearer ${userToken}`)
        .send({
          name: 'Test Product',
          price: 29.99,
          stock: 100,
          category: 'electronics'
        })
        .expect(403);
    });

    it('should validate required fields', async () => {
      await request(app)
        .post('/api/products')
        .set('Authorization', `Bearer ${adminToken}`)
        .send({
          name: 'Test'
          // Missing price, stock, category
        })
        .expect(400);
    });

    it('should validate price is positive', async () => {
      await request(app)
        .post('/api/products')
        .set('Authorization', `Bearer ${adminToken}`)
        .send({
          name: 'Test',
          price: -10,
          stock: 100,
          category: 'electronics'
        })
        .expect(400);
    });
  });

  describe('GET /api/products', () => {
    // More tests...
  });

  // More describe blocks for other endpoints...
});
```

### Step 6: Register Routes (2 min)
```typescript
// api/app.ts or api/routes/index.ts
import productRoutes from './products';

app.use('/api/products', productRoutes);
```

### Step 7: Database Migration (5 min)
```prisma
// prisma/schema.prisma
model Product {
  id          String    @id @default(uuid())
  name        String    @db.VarChar(255)
  description String    @db.Text @default("")
  price       Decimal   @db.Decimal(10, 2)
  stock       Int
  category    String
  imageUrl    String?
  active      Boolean   @default(true)
  createdAt   DateTime  @default(now())
  updatedAt   DateTime  @updatedAt
  deletedAt   DateTime?

  @@index([category, active])
  @@index([name])
}
```

```bash
npx prisma migrate dev --name add-products
```

### Step 8: API Documentation (5 min)
```yaml
# docs/openapi.yaml
/products:
  get:
    summary: List products
    parameters:
      - in: query
        name: page
        schema:
          type: integer
          default: 1
      - in: query
        name: limit
        schema:
          type: integer
          default: 20
      - in: query
        name: category
        schema:
          type: string
          enum: [electronics, clothing, food, other]
    responses:
      200:
        description: Success
        content:
          application/json:
            schema:
              type: object
              properties:
                success:
                  type: boolean
                data:
                  type: array
                  items:
                    $ref: '#/components/schemas/Product'
                meta:
                  $ref: '#/components/schemas/PaginationMeta'
  # Other endpoints...
```

## VALIDATION

### Level 1: Type Check
```bash
npm run type-check
```
Expected: No errors

### Level 2: Lint
```bash
npm run lint
```
Expected: No errors

### Level 3: Unit Tests
```bash
npm run test -- products.test.ts
```
Expected: All tests pass, coverage >80%

### Level 4: Integration Tests
```bash
npm run test:integration
```
Expected: Full CRUD flow works

### Level 5: Manual API Testing
```bash
# Create product
curl -X POST http://localhost:3000/api/products \
  -H "Authorization: Bearer $ADMIN_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "iPhone 15",
    "description": "Latest iPhone",
    "price": 999.99,
    "stock": 50,
    "category": "electronics"
  }'
# Expected: 201 Created

# List products
curl http://localhost:3000/api/products \
  -H "Authorization: Bearer $USER_TOKEN"
# Expected: 200 OK with array

# Get single product
curl http://localhost:3000/api/products/$PRODUCT_ID \
  -H "Authorization: Bearer $USER_TOKEN"
# Expected: 200 OK with product

# Update product
curl -X PUT http://localhost:3000/api/products/$PRODUCT_ID \
  -H "Authorization: Bearer $ADMIN_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"price": 899.99}'
# Expected: 200 OK with updated product

# Delete product
curl -X DELETE http://localhost:3000/api/products/$PRODUCT_ID \
  -H "Authorization: Bearer $ADMIN_TOKEN"
# Expected: 204 No Content

# Verify soft delete (shouldn't appear in list)
curl http://localhost:3000/api/products \
  -H "Authorization: Bearer $USER_TOKEN"
# Expected: Deleted product not in list
```

### Level 6: Performance Test
```bash
npm run test:load -- /api/products
```
Expected: <200ms response time, handles 100 req/s

## SUCCESS CRITERIA

- [ ] All CRUD operations work
- [ ] Authentication required
- [ ] Authorization enforced (admin-only for write)
- [ ] Validation works for all inputs
- [ ] Pagination works correctly
- [ ] Filtering by category works
- [ ] Search by name works
- [ ] Soft delete works (items don't appear after delete)
- [ ] All tests pass with >80% coverage
- [ ] No TypeScript errors
- [ ] No lint errors
- [ ] API documentation generated
- [ ] Performance <200ms
- [ ] Handles error cases gracefully

## POST-IMPLEMENTATION

### Monitoring
- Add error tracking for products endpoints
- Set alert for error rate >5%
- Add performance monitoring

### Documentation
- Update API documentation
- Add to postman collection
- Update team in #engineering channel

### Next Steps
- Add product images upload (future feature)
- Add product reviews (future feature)
- Add product variants (future feature)
```

## VALIDATION RULES
- [ ] All files specified with exact paths
- [ ] Complete code provided (not snippets)
- [ ] All CRUD operations covered
- [ ] Authentication and authorization included
- [ ] Comprehensive tests (unit + integration + manual)
- [ ] Performance requirements specified
- [ ] Monitoring and documentation included
```

---

## CONCLUSION

<summary>
Meta-prompts are the ultimate leverage point in agentic coding. They compress human intent from words into comprehensive specifications, enabling autonomous execution at scale.

Key insights:
1. Meta-prompts encode the planning process itself
2. Input compression of 100-1000x is achievable
3. Time savings of 99%+ in human effort
4. Quality improves through encoded best practices
5. Templates + Meta-Prompts = Exponential scaling
</summary>

<implementation-path>
1. Start with templates for common work
2. Create meta-prompt for each template
3. Test on real work, measure results
4. Iterate based on failures
5. Build library of meta-prompts
6. Achieve autonomous execution
7. Scale exponentially
</implementation-path>

<remember>
"From one line to comprehensive plan in 30 seconds."

This is the power of meta-prompts. This is how engineering scales beyond human limits.
</remember>

---

<metadata>
<completion-criteria>
- [ ] Understand what meta-prompts are
- [ ] Can explain meta-prompt hierarchy
- [ ] Can create meta-prompt from template
- [ ] Can measure compression and time savings
- [ ] Can implement complete pipeline
- [ ] Can create self-improving systems
</completion-criteria>

<related-resources>
- template-engineering-guide.md
- lesson-03-success-is-planned.md
- lesson-10-prompt-engineering.md
</related-resources>
</metadata>