<metadata>
purpose: Complete lesson on Template Engineering and planning as foundational tactic
type: educational-content
course: Tactical Agentic Coding
lesson: 3
difficulty: intermediate
dependencies: lesson-01, lesson-02
last-updated: 2025-09-30
</metadata>

<overview>
Lesson 3 introduces the fundamental shift from solving individual problems to solving entire problem classes through template engineering. This lesson reveals why success in agentic coding is primarily a planning discipline, and how templates encode engineering workflows into reusable, scalable units.
</overview>

# LESSON 3: SUCCESS IS PLANNED

**Course:** Tactical Agentic Coding
**Level:** INTERMEDIATE
**Core Principle:** "Great planning is great prompting."

---

## THE PROMPT IS EVERYTHING

### The Fundamental Truth

In agentic coding, the prompt is the fundamental unit of engineering.

**Phase 1 (AI Coding):**
- Prompt = Single instruction
- Agent = Code completion assistant
- Scale = Linear with human input

**Phase 2 (Agentic Coding):**
- Prompt = Comprehensive plan
- Agent = Autonomous executor
- Scale = Exponential with templates

### Why Prompts Scale

**SINGLE PROMPT:**
```
"Add dark mode to the application"
```

**WHAT HAPPENS:**
- Agent asks clarifying questions
- Human provides more details
- Back and forth 10+ times
- Final implementation after many iterations

**Result:** In-loop engineering, slow scaling.

---

**PLANNED PROMPT (Template-Generated):**
```
# TASK: Implement Dark Mode Toggle

## CONTEXT
Files involved:
- /app/layout.tsx (add provider)
- /components/theme-toggle.tsx (create new)
- /styles/globals.css (add dark theme variables)
- /lib/theme-context.tsx (state management)

## CURRENT STATE
- Application uses light theme only
- No theme management exists
- Tailwind CSS configured

## DESIRED OUTCOME
- User can toggle between light/dark themes
- Preference persists in localStorage
- All components support both themes
- Smooth transition animations

## IMPLEMENTATION PLAN
1. Create theme context with React Context API
2. Build theme toggle component with moon/sun icons
3. Define CSS variables for both themes
4. Wrap app in theme provider
5. Add theme class to html element
6. Store preference in localStorage

## VALIDATION
Run these commands to verify:
```bash
npm run lint
npm run type-check
npm run test -- theme
npm run build
```

Expected behavior:
- Toggle switches themes immediately
- Preference persists across page loads
- No console errors
- Build succeeds

## ARCHITECTURE NOTES
- Use React Context to avoid prop drilling
- CSS variables for easy theme switching
- localStorage for persistence
- Tailwind dark: variant for components
```

**Result:** Agent executes autonomously, first-time success.

---

## PLANS ARE SCALED PROMPTS

### The Planning Hierarchy

```
SINGLE WORD
    ↓
SIMPLE PROMPT
    ↓
DETAILED PROMPT
    ↓
COMPREHENSIVE PLAN
    ↓
EXECUTABLE SPECIFICATION
```

### What Makes a Plan Different

**PROMPT (Inadequate):**
- "Fix the login bug"
- "Add API endpoint for users"
- "Refactor the database code"

**PLAN (Effective):**
- **WHAT** - Specific problem definition
- **WHERE** - Exact files and locations
- **WHY** - Root cause and context
- **HOW** - Step-by-step implementation
- **VALIDATE** - Commands to verify success

### The Plan Structure

<plan-structure>
<section name="context">
  - What files are involved
  - Current state of the system
  - Relevant architecture patterns
  - Dependencies and constraints
</section>

<section name="problem">
  - Exact issue or requirement
  - Expected behavior vs actual
  - User impact
  - Acceptance criteria
</section>

<section name="solution">
  - Implementation approach
  - Step-by-step changes
  - Code examples where helpful
  - Edge cases to handle
</section>

<section name="validation">
  - Specific commands to run
  - Expected outputs
  - How to verify success
  - Rollback if needed
</section>
</plan-structure>

---

## SUCCESS IS PLANNED (PHILOSOPHY)

### The Core Insight

**"Planning alone is expensive. Templates make planning free."**

### Manual Planning Cost

**WITHOUT TEMPLATES:**
- Engineer spends 30-60 minutes writing comprehensive plan
- Plan is used once
- Next similar problem requires new plan
- Each team member writes their own plans
- Knowledge not transferred

**Cost:** 30 minutes × every occurrence

### Template Planning Cost

**WITH TEMPLATES:**
- Engineer spends 2 hours creating comprehensive template once
- Template generates plans instantly
- All similar problems use same template
- Entire team benefits
- Knowledge encoded and transferred

**Cost:** 2 hours ÷ infinite uses = effectively zero

### The ROI Calculation

```
MANUAL PLANNING:
- Bug fix plan: 30 minutes
- 10 bugs per month: 5 hours
- 12 months: 60 hours annually

TEMPLATE PLANNING:
- Create bug template once: 2 hours
- 120 bugs per year: ~2 minutes total
- Annual savings: 58 hours

ROI: 2900% return on time invested
```

**Multiply by team size and problem types.**

---

## THE 80-20 OF AGENTIC CODING

### The Three Core Tactics

**These three tactics deliver 80% of agentic coding value:**

<tactic number="1">
<name>STOP CODING</name>
<impact>Forces mindset shift from typer to orchestrator</impact>
<result>Frees mental cycles for higher-level work</result>
</tactic>

<tactic number="2">
<name>ADOPT YOUR AGENT'S PERSPECTIVE</name>
<impact>Ensures agents have everything needed for success</impact>
<result>Dramatically reduces iteration cycles</result>
</tactic>

<tactic number="3">
<name>TEMPLATE YOUR ENGINEERING</name>
<impact>Solves problem classes, not individual problems</impact>
<result>Exponential scaling through reuse</result>
</tactic>

### Why These Three

**TACTIC #1** removes the bottleneck (your fingers)
**TACTIC #2** removes the blindness (agent context)
**TACTIC #3** removes the repetition (encode once, use forever)

Together they create a multiplicative effect:

```
LINEAR ENGINEER:
Output = Time × Skill

AGENTIC ENGINEER:
Output = Time × Skill × Agent_Speed × Context_Quality × Template_Reuse

Where:
- Agent_Speed ≈ 10-100x human typing
- Context_Quality ≈ 2-5x success rate
- Template_Reuse ≈ 10-1000x efficiency

Total multiplier: 200-500,000x
```

---

## TACTIC #3: TEMPLATE YOUR ENGINEERING

### What is a Template?

<definition>
A template is a reusable prompt structure that encodes your engineering workflow for solving an entire class of problems.
</definition>

### Template vs Prompt

**PROMPT:**
- Solves one specific problem
- Written for immediate use
- Discarded after execution
- No reuse value

**TEMPLATE:**
- Solves all problems in a class
- Written for infinite reuse
- Improves with each use
- Massive reuse value

### The Template Transformation

**SCENARIO: Bug in authentication flow**

**WITHOUT TEMPLATE (Manual):**
```
You: "The login isn't working"
Agent: "What error are you seeing?"
You: "Users can't log in with Google OAuth"
Agent: "What files handle OAuth?"
You: "Um, let me check... /auth/oauth.ts I think"
Agent: "What's the current behavior?"
You: "It redirects but then errors"
Agent: "What error message?"
You: "Let me check the logs..."

[15 minutes of back and forth]

Finally: Agent attempts fix, fails, tries again...
```

**WITH TEMPLATE (Automated):**
```
You: "bug: oauth login fails on redirect"

Template expands to comprehensive plan:
1. Context gathered automatically
2. Relevant files identified
3. Log analysis performed
4. Root cause determined
5. Fix implemented
6. Tests run
7. Validation complete

[2 minutes, autonomous execution]
```

### Template Structure

<template-anatomy>
<component name="metadata">
  - Template name and version
  - Problem class it solves
  - Required inputs
  - Expected outputs
</component>

<component name="context-gathering">
  - What information agent needs
  - Where to find it
  - How to validate it
</component>

<component name="planning-process">
  - Analysis steps
  - Decision points
  - Implementation approach
</component>

<component name="execution-guidance">
  - Step-by-step instructions
  - Code patterns to follow
  - Testing requirements
</component>

<component name="validation-criteria">
  - Commands to run
  - Expected results
  - Success metrics
</component>
</template-anatomy>

---

## SOLVING PROBLEM CLASSES, NOT PROBLEMS

### The Paradigm Shift

**OLD MINDSET:**
- "I need to fix this specific bug"
- "I need to add this one feature"
- "I need to refactor this particular file"

**NEW MINDSET:**
- "We need a system for fixing all authentication bugs"
- "We need a system for adding all CRUD features"
- "We need a system for refactoring any technical debt"

### Problem Classes in Software

<problem-class type="chore">
<examples>
  - Dependency updates
  - Configuration changes
  - Documentation updates
  - Code formatting
</examples>
<template-value>
  Chores follow predictable patterns. One template handles thousands of chores.
</template-value>
</problem-class>

<problem-class type="bug">
<examples>
  - Logic errors
  - Integration failures
  - Performance issues
  - Security vulnerabilities
</examples>
<template-value>
  Bugs require investigation workflow. Template guides systematic debugging.
</template-value>
</problem-class>

<problem-class type="feature">
<examples>
  - New API endpoints
  - UI components
  - User workflows
  - Integrations
</examples>
<template-value>
  Features follow architecture patterns. Template ensures consistency.
</template-value>
</problem-class>

<problem-class type="refactor">
<examples>
  - Code cleanup
  - Performance optimization
  - Architecture improvements
  - Technical debt reduction
</examples>
<template-value>
  Refactors need safety guarantees. Template includes comprehensive testing.
</template-value>
</problem-class>

### The 80-20 of Problem Classes

**INSIGHT:** 80% of engineering work falls into ~10 problem classes.

**YOUR TASK:** Identify your top 10 problem classes and create templates for each.

**Example for Web Application:**
1. CRUD API endpoint (feature)
2. React component with state (feature)
3. Database schema change (chore)
4. Bug in API logic (bug)
5. Frontend bug (bug)
6. Dependency upgrade (chore)
7. Performance optimization (refactor)
8. Add integration test (chore)
9. Refactor for clarity (refactor)
10. Security vulnerability fix (bug)

**With these 10 templates, you've templated 80% of your work.**

---

## TEMPLATES FOR TEAM LEVERAGE

### Individual vs Team Impact

**INDIVIDUAL USE:**
- You create template for your own work
- 10x personal productivity
- Significant value

**TEAM USE:**
- You create template for entire team
- 10x × team_size productivity
- Exponential value

### Knowledge Transfer Through Templates

**TRADITIONAL KNOWLEDGE TRANSFER:**
```
Junior: "How do I add a new API endpoint?"
Senior: "Well, first you need to..."
[30 minute explanation]
[Junior still unclear]
[Repeats for each new junior]
```

**TEMPLATE-BASED TRANSFER:**
```
Junior: "How do I add a new API endpoint?"
Senior: "Use the add-api-endpoint template"
Junior: [Executes template]
Junior: [Autonomous success]
[Knowledge encoded, no repetition needed]
```

### Template Library Structure

<template-library>
<directory name="chores">
  - update-dependencies.md
  - add-environment-variable.md
  - update-documentation.md
  - format-code.md
</directory>

<directory name="bugs">
  - debug-api-error.md
  - debug-frontend-error.md
  - fix-performance-issue.md
  - fix-security-vulnerability.md
</directory>

<directory name="features">
  - add-crud-endpoint.md
  - add-react-component.md
  - add-database-table.md
  - add-third-party-integration.md
</directory>

<directory name="refactors">
  - extract-function.md
  - optimize-query.md
  - improve-error-handling.md
  - modernize-syntax.md
</directory>
</template-library>

---

## PLANNING ALONE IS EXPENSIVE

### The Hidden Cost of Manual Planning

**TIME COST:**
- Writing comprehensive plan: 30-60 minutes
- Number of times you solve similar problems: 10-1000+
- Total time without template: 5-1000 hours
- Total time with template: 2 hours (creation) + ~5 minutes (all uses)

**COGNITIVE COST:**
- Mental energy to plan each time
- Context switching overhead
- Risk of forgetting steps
- Inconsistency across implementations

**QUALITY COST:**
- Plans degrade over time (fatigue)
- Junior engineers write incomplete plans
- Important steps get skipped
- Knowledge not preserved

### Why Engineers Avoid Planning

**THE TRAP:**
1. Planning takes time upfront
2. Engineer wants to "just fix it quick"
3. Skips planning, jumps to coding
4. Implementation takes 10x longer
5. Final solution is suboptimal
6. Tech debt created

**THE PATTERN:**
```
Skip planning → Longer implementation → More bugs → More fixes → More tech debt

Time saved: -30 minutes
Time cost: +5 hours
Net: -4.5 hours
```

### Templates Break the Trap

**WITH TEMPLATES:**
1. Template generates plan instantly (30 seconds)
2. Plan is comprehensive and battle-tested
3. Agent executes autonomously
4. Implementation is correct first time
5. No tech debt created

**THE PATTERN:**
```
Use template → Instant plan → Fast implementation → Correct result → No debt

Time saved: 30 minutes planning + 4 hours fixing
Time cost: 30 seconds
Net: +29.5 hours saved
```

---

## TEMPLATES ENCODE PROBLEM SOLVING

### What Gets Encoded

<encoded-knowledge>
<element name="workflow">
  The step-by-step process for solving this problem class
</element>

<element name="context">
  What information is needed and where to find it
</element>

<element name="patterns">
  Code patterns and architecture decisions that work
</element>

<element name="validation">
  How to verify the solution is correct
</element>

<element name="edge-cases">
  Common pitfalls and how to avoid them
</element>

<element name="lessons-learned">
  Accumulated wisdom from previous attempts
</element>
</encoded-knowledge>

### Template Evolution

**VERSION 1 (Initial):**
```markdown
## Bug Fix Template

1. Read the error
2. Find the file
3. Fix the code
4. Test it
```

**VERSION 5 (Battle-Tested):**
```markdown
## Bug Fix Template v5

### Context Gathering
1. Extract full error message with stack trace
2. Identify all files in stack trace
3. Review recent changes to these files (git log)
4. Check for related open issues
5. Verify reproduction steps

### Root Cause Analysis
1. Add debug logging to trace execution
2. Verify assumptions about data flow
3. Check for edge cases
4. Review error handling
5. Identify exact failure point

### Fix Implementation
1. Write failing test that reproduces bug
2. Implement minimal fix
3. Verify test passes
4. Check for similar bugs in codebase
5. Add defensive coding if needed

### Validation
Run in order:
```bash
npm run test:unit
npm run test:integration
npm run lint
npm run type-check
npm run build
```

### Prevention
1. Add test to prevent regression
2. Update error messages to be clearer
3. Add logging for future debugging
4. Document the fix in CHANGELOG
```

**IMPROVEMENT SOURCE:**
- Each bug fix reveals new edge cases
- Template updated to include learnings
- Next bug benefits from all previous fixes
- Compound improvement over time

---

## REUSABLE PROMPTS AS TIME SAVERS

### The Reuse Multiplier

<reuse-calculation>
<variables>
time_to_create_template = 2 hours
time_to_use_template = 2 minutes
time_for_manual_work = 30 minutes
number_of_uses = N
</variables>

<breakeven>
2 hours = N × (30 minutes - 2 minutes)
2 hours = N × 28 minutes
N = 4.3

Break-even point: 5 uses
</breakeven>

<roi>
After 10 uses:
- Time with template: 2 hours + (10 × 2 min) = 2h 20m
- Time without: 10 × 30 min = 5 hours
- Savings: 2h 40m (53% reduction)

After 100 uses:
- Time with template: 2 hours + (100 × 2 min) = 5h 20m
- Time without: 100 × 30 min = 50 hours
- Savings: 44h 40m (89% reduction)

After 1000 uses:
- Time with template: 2 hours + (1000 × 2 min) = 35h 20m
- Time without: 1000 × 30 min = 500 hours
- Savings: 464h 40m (93% reduction)
</roi>
</reuse-calculation>

### Organizational Impact

**INDIVIDUAL REUSE:**
- You use template 50 times/year
- Personal savings: 23 hours/year

**TEAM REUSE:**
- 10 engineers × 50 uses/year = 500 uses
- Team savings: 233 hours/year
- Equivalent to: 6 weeks of engineer time

**COMPANY REUSE:**
- 100 engineers × 50 uses/year = 5,000 uses
- Company savings: 2,333 hours/year
- Equivalent to: 58 weeks of engineer time
- Equivalent value: $150K+ at loaded costs

### Template Network Effects

**DIRECT VALUE:** Time saved per use
**NETWORK VALUE:** Templates reference other templates
**COMPOUND VALUE:** Templates improve with use

**Example Network:**
```
add-api-endpoint
├── uses: add-database-table
├── uses: add-api-test
└── uses: update-documentation

Each template contains references to related templates,
creating a web of reusable engineering knowledge.
```

---

## META-PROMPTS: PROMPTS THAT BUILD PROMPTS

### What is a Meta-Prompt?

<definition>
A meta-prompt is a prompt that generates another prompt. In the context of templates, a meta-prompt takes minimal input and generates a comprehensive plan.
</definition>

### The Meta-Prompt Pattern

**LEVEL 1: Direct Prompt**
```
"Add dark mode toggle to settings page"
[Agent attempts implementation]
[Multiple iterations required]
```

**LEVEL 2: Template Prompt**
```
"Use feature-template to add dark mode toggle"
[Template provides structure]
[Agent follows structure]
[Better result, fewer iterations]
```

**LEVEL 3: Meta-Prompt**
```
Input: "dark mode toggle"
Meta-Prompt: Generates comprehensive plan
Output: 5-page specification with:
  - Architecture analysis
  - Component breakdown
  - State management approach
  - Testing strategy
  - Validation commands

[Agent executes plan autonomously]
[One-shot success]
```

### How Meta-Prompts Work

<meta-prompt-process>
<step number="1">
<name>Input Capture</name>
<description>Minimal user input (often one line)</description>
<example>Feature name, bug description, refactor target</example>
</step>

<step number="2">
<name>Context Extraction</name>
<description>Meta-prompt gathers all relevant context</description>
<example>Analyze codebase, read configs, check dependencies</example>
</step>

<step number="3">
<name>Plan Generation</name>
<description>Meta-prompt applies template logic</description>
<example>Create step-by-step implementation plan</example>
</step>

<step number="4">
<name>Specification Output</name>
<description>Comprehensive, executable plan</description>
<example>Complete with validation and success criteria</example>
</step>
</meta-prompt-process>

### Meta-Prompt Structure

```markdown
# META-PROMPT: [Template Name]

## ROLE
You are a senior engineering architect creating an implementation plan.

## INPUT
Receive: [Minimal user input]
Parse: [Extract key information]

## CONTEXT GATHERING
Read these files:
- [List of relevant files]
- [Configuration files]
- [Documentation]

Analyze:
- [Current architecture]
- [Existing patterns]
- [Dependencies]

## PLAN GENERATION
Create comprehensive plan including:

1. CONTEXT SECTION
   - Current state
   - Files involved
   - Architecture patterns

2. REQUIREMENTS SECTION
   - Acceptance criteria
   - Edge cases
   - Constraints

3. IMPLEMENTATION SECTION
   - Step-by-step changes
   - Code examples
   - Testing requirements

4. VALIDATION SECTION
   - Commands to run
   - Expected outputs
   - Success metrics

## OUTPUT FORMAT
[Structured specification format]

## VALIDATION
Before outputting plan:
- [ ] All required sections present
- [ ] Specific file paths included
- [ ] Validation commands defined
- [ ] Success criteria clear
```

### Meta-Prompt Example: Bug Fix

**USER INPUT:**
```
"API returns 500 on POST /users"
```

**META-PROMPT GENERATES:**
```markdown
# BUG FIX PLAN: API 500 Error on User Creation

## CONTEXT
**Endpoint:** POST /users
**Error:** HTTP 500 Internal Server Error
**Files Involved:**
- /api/routes/users.ts (main handler)
- /api/controllers/userController.ts (business logic)
- /api/models/User.ts (database model)
- /api/middleware/validation.ts (input validation)

**Recent Changes:**
- 2 days ago: Added email validation
- 1 day ago: Updated database schema

## INVESTIGATION PLAN

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

Expected: 500 error
Actual: [Agent will test]

### Step 2: Check Server Logs
```bash
tail -100 logs/error.log | grep "POST /users"
```

Look for:
- Stack traces
- Database errors
- Validation errors

### Step 3: Review Recent Changes
```bash
git log --since="3 days ago" --oneline -- api/
git diff HEAD~2 api/routes/users.ts
```

Hypothesis: Email validation or schema change caused regression

### Step 4: Add Debug Logging
```typescript
// In userController.ts
logger.debug('Creating user:', { name, email });
logger.debug('Validation result:', validationResult);
logger.debug('Database query:', query);
```

### Step 5: Test Incrementally
```bash
npm run test -- users.test.ts
npm run test:integration -- api/users
```

## LIKELY ROOT CAUSES (Prioritized)

1. **Schema Mismatch** (80% probability)
   - New validation expects fields not in schema
   - Check: Does User model match validation rules?

2. **Database Connection** (15% probability)
   - Connection pool exhausted
   - Check: Are connections being closed?

3. **Validation Logic** (5% probability)
   - New validation throws instead of returning error
   - Check: Is error handling present?

## IMPLEMENTATION APPROACH

### If Schema Mismatch:
1. Update User model to include required fields
2. Run migration if needed
3. Update validation to match schema

### If Database Connection:
1. Add connection pool monitoring
2. Ensure connections released in finally blocks
3. Add timeout configuration

### If Validation Logic:
1. Wrap validation in try-catch
2. Return proper error response
3. Add validation tests

## VALIDATION COMMANDS

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

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

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

# Expected: 201 Created with user object

# Load test (ensure no connection leaks)
npm run test:load -- endpoints/users

# Check logs
npm run logs:check
```

## SUCCESS CRITERIA

- [ ] POST /users returns 201 on valid input
- [ ] User created in database
- [ ] No error logs
- [ ] All tests pass
- [ ] Load test shows no connection leaks
- [ ] Similar endpoints still work (regression check)

## PREVENTION

After fix:
1. Add integration test for this scenario
2. Add monitoring alert for 500 errors on this endpoint
3. Document validation requirements
4. Add database schema validation to CI
```

**FROM ONE LINE TO COMPREHENSIVE PLAN IN 30 SECONDS.**

---

## PLANS WRITTEN TO SPECS DIRECTORY

### The Specs Architecture

<directory-structure>
/specs
  ├── chores/
  │   ├── 2024-09-30-update-dependencies.md
  │   └── 2024-09-28-add-env-var.md
  ├── bugs/
  │   ├── 2024-09-30-api-500-error.md
  │   └── 2024-09-29-login-redirect-fail.md
  ├── features/
  │   ├── 2024-09-30-dark-mode-toggle.md
  │   └── 2024-09-27-user-export-csv.md
  └── refactors/
      ├── 2024-09-29-extract-auth-logic.md
      └── 2024-09-26-optimize-db-queries.md
</directory-structure>

### Why Write Plans to Files

<benefits>
<benefit name="persistence">
Plans don't disappear from chat history
</benefit>

<benefit name="reviewability">
Team can review plans before execution
</benefit>

<benefit name="traceability">
Clear record of what was planned vs executed
</benefit>

<benefit name="improvability">
Plans can be updated and refined
</benefit>

<benefit name="reusability">
Similar future work references existing plans
</benefit>

<benefit name="documentation">
Plans become project documentation automatically
</benefit>
</benefits>

### Spec File Format

```markdown
# [TYPE]: [Brief Description]

**Created:** 2024-09-30
**Status:** planned | in-progress | completed | blocked
**Assignee:** @username (can be agent or human)
**Estimated Time:** 2 hours
**Actual Time:** [filled after completion]

## CONTEXT
[Background and current state]

## REQUIREMENTS
[What needs to be accomplished]

## IMPLEMENTATION PLAN
[Step-by-step approach]

## VALIDATION
[How to verify success]

## NOTES
[Additional information, learnings, issues encountered]
```

### The Workflow Integration

<workflow>
<phase name="planning">
1. User provides input (one line or detailed)
2. Meta-prompt generates comprehensive plan
3. Plan written to /specs/[type]/[date]-[name].md
4. Plan reviewed (by human or agent)
5. Plan approved or revised
</phase>

<phase name="execution">
6. Agent loads plan from file
7. Agent executes step by step
8. Agent updates status in plan file
9. Agent notes any deviations or issues
</phase>

<phase name="completion">
10. Agent runs all validation commands
11. Agent updates plan status to "completed"
12. Agent records actual time taken
13. Agent adds lessons learned to notes
</phase>
</workflow>

### Plan as Living Document

**DURING EXECUTION:**
```markdown
## IMPLEMENTATION PLAN

1. ✅ Create theme context
   - Completed in 2 minutes
   - Added dark/light/system modes

2. 🔄 Build theme toggle component
   - In progress
   - Using Radix UI for accessibility

3. ⏸️ Define CSS variables
   - Waiting for design tokens from team

4. ⏳ Wrap app in provider
   - Not started
```

**AFTER COMPLETION:**
```markdown
## NOTES

### Issues Encountered
- Tailwind config needed dark mode: 'class' setting
- Initial implementation had flash of unstyled content
- localStorage caused hydration mismatch in SSR

### Solutions Applied
- Updated tailwind.config.js
- Added ThemeScript component to prevent FOUC
- Moved localStorage read to useEffect

### Lessons Learned
- Always test SSR compatibility with client-side storage
- Theme provider should be as high as possible in tree
- Consider system preference as default

### Time Analysis
- Estimated: 2 hours
- Actual: 1.5 hours
- Efficiency: 125%
- Reason for difference: Template included SSR pattern
```

---

## BUILT-IN VALIDATION COMMANDS

### Why Validation Must Be Specified

**WITHOUT VALIDATION:**
```markdown
## Plan
1. Update API endpoint
2. Deploy to production
```

**What happens:**
- Agent makes changes
- Changes look correct
- Agent reports success
- Production breaks
- No one knows until users complain

**WITH VALIDATION:**
```markdown
## Plan
1. Update API endpoint
2. Run validation:
   ```bash
   npm run test:api
   npm run test:integration
   npm run lint
   npm run type-check
   curl -X POST localhost:3000/api/test
   ```
3. All pass? Deploy to production
4. If any fail? Fix and repeat validation
```

**What happens:**
- Agent makes changes
- Agent runs all validation
- Tests catch regression
- Agent fixes issue
- All validation passes
- Safe to deploy

### Validation Command Categories

<validation-categories>
<category name="syntax">
<purpose>Ensure code is syntactically correct</purpose>
<commands>
- npm run lint
- npm run type-check
- python -m pylint
- cargo check
</commands>
</category>

<category name="unit-tests">
<purpose>Verify function-level correctness</purpose>
<commands>
- npm run test:unit
- pytest tests/unit
- go test ./...
- mvn test
</commands>
</category>

<category name="integration-tests">
<purpose>Verify component interactions</purpose>
<commands>
- npm run test:integration
- pytest tests/integration
- npm run test:api
</commands>
</category>

<category name="build">
<purpose>Ensure production build succeeds</purpose>
<commands>
- npm run build
- cargo build --release
- python -m build
- go build ./cmd/app
</commands>
</category>

<category name="manual-verification">
<purpose>Test actual behavior</purpose>
<commands>
- curl commands for APIs
- Specific UI interactions
- Database queries
- Log checks
</commands>
</category>
</validation-categories>

### Validation in Templates

**TEMPLATE EXAMPLE:**
```markdown
## Validation Section

Run these commands in order:

### 1. Syntax Check
```bash
npm run lint
npm run type-check
```
Expected: No errors

### 2. Unit Tests
```bash
npm run test -- [component].test
```
Expected: All tests pass, coverage >80%

### 3. Integration Tests
```bash
npm run test:integration -- [feature]
```
Expected: End-to-end flow works

### 4. Build
```bash
npm run build
```
Expected: Build succeeds, no warnings

### 5. Manual Test
```bash
# Start dev server
npm run dev

# In another terminal
curl -X POST http://localhost:3000/api/[endpoint] \
  -H "Content-Type: application/json" \
  -d '{"test":"data"}'
```
Expected: [Specific response]

### 6. Check Logs
```bash
grep -i error logs/app.log
```
Expected: No new errors

## If Any Validation Fails

1. Read the error message carefully
2. Identify the root cause
3. Make the minimal fix
4. Re-run ALL validations from the beginning
5. Repeat until all pass
```

### Progressive Validation

**PRINCIPLE:** Validate incrementally, not all at end.

<progressive-validation>
<level number="1" name="syntax">
Fast feedback, catches basic errors
Run after: Every file change
</level>

<level number="2" name="unit">
Medium feedback, catches logic errors
Run after: Every function implementation
</level>

<level number="3" name="integration">
Slower feedback, catches interaction errors
Run after: Every feature component
</level>

<level number="4" name="end-to-end">
Slowest feedback, catches flow errors
Run after: Complete feature
</level>
</progressive-validation>

**AGENT WORKFLOW:**
```
Write function
    ↓
Run syntax check → Fix if needed
    ↓
Run unit test → Fix if needed
    ↓
Write next function
    ↓
[Repeat until feature complete]
    ↓
Run integration tests → Fix if needed
    ↓
Run E2E tests → Fix if needed
    ↓
Done
```

---

## FROM ONE LINE TO COMPREHENSIVE PLAN

### The Transformation Examples

<example number="1">
<input>
"update dependencies"
</input>

<meta-prompt-output>
# CHORE: Update Project Dependencies

## CONTEXT
**Project:** [Detected from package.json]
**Package Manager:** npm
**Current Node:** v18.17.0
**Dependencies:** 47 total (12 outdated)

## OUTDATED PACKAGES
```bash
Package                Current    Wanted     Latest
react                  18.2.0     18.2.0     18.3.1
typescript             5.1.6      5.1.6      5.3.2
@types/node            18.16.0    18.18.0    20.10.0
eslint                 8.45.0     8.56.0     8.56.0
```

## RISK ASSESSMENT
- **Low Risk:** Patch updates (18.2.0 → 18.2.1)
- **Medium Risk:** Minor updates (18.2 → 18.3)
- **High Risk:** Major updates (18 → 19)

## IMPLEMENTATION PLAN

### Phase 1: Patch Updates (Low Risk)
```bash
npm update
```

### Phase 2: Minor Updates (Medium Risk)
```bash
npm install react@18.3.1
npm install typescript@5.3.2
```

### Phase 3: Major Updates (High Risk)
```bash
# Review breaking changes first
npm install @types/node@20.10.0
```

## VALIDATION
After each phase:
```bash
npm run test
npm run type-check
npm run build
npm run test:integration
```

If any fail:
1. Review changelog for breaking changes
2. Update code to match new API
3. Re-run validation
4. If still failing, revert that update

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

## SUCCESS CRITERIA
- [ ] All dependencies updated
- [ ] All tests pass
- [ ] Build succeeds
- [ ] No new type errors
- [ ] Application runs correctly
</meta-prompt-output>
</example>

<example number="2">
<input>
"users can't log in with Google"
</input>

<meta-prompt-output>
# BUG: Google OAuth Login Failure

## CONTEXT
**Affected Flow:** OAuth login with Google
**Symptom:** Users redirected but authentication fails
**Frequency:** 100% of attempts
**First Reported:** 2024-09-30 09:15 UTC
**Environment:** Production
**Recent Changes:** OAuth config updated 2024-09-29

## FILES INVOLVED
- /auth/oauth/google.ts (OAuth handler)
- /auth/strategies/google.strategy.ts (Passport strategy)
- /config/oauth.config.ts (Configuration)
- /.env (Environment variables)

## INVESTIGATION STEPS

### 1. Check Server Logs
```bash
grep -A 10 "google oauth" logs/auth.log | tail -50
```
Look for: Error messages, stack traces, redirect URLs

### 2. Verify OAuth Configuration
```bash
cat .env | grep GOOGLE
```
Verify:
- GOOGLE_CLIENT_ID present and correct
- GOOGLE_CLIENT_SECRET present and correct
- GOOGLE_CALLBACK_URL matches Google Console

### 3. Check Google Console Settings
Visit: https://console.cloud.google.com/apis/credentials
Verify:
- Authorized redirect URIs include our callback
- OAuth consent screen configured
- API not disabled

### 4. Test OAuth Flow Manually
```bash
# Get authorization URL
curl http://localhost:3000/auth/google

# Follow through manually to see where it breaks
```

### 5. Compare with Working Version
```bash
git diff HEAD~2 auth/oauth/google.ts
git log --since="2 days ago" -- auth/
```

## LIKELY ROOT CAUSES

1. **Redirect URI Mismatch** (60% probability)
   - Callback URL in code doesn't match Google Console
   - Recent change to domain or routing

2. **Expired/Invalid Credentials** (25% probability)
   - Client secret rotated but not updated in .env
   - API access revoked in Google Console

3. **Scope Changes** (10% probability)
   - Requested scopes not approved in consent screen
   - New scope requires verification

4. **Session/Cookie Issues** (5% probability)
   - Session middleware not preserving state
   - Cookie settings blocking OAuth flow

## IMPLEMENTATION

### If Redirect URI Mismatch:
1. Log actual callback URL agent receives
2. Compare with Google Console settings
3. Update Google Console or code to match
4. Test OAuth flow

### If Expired Credentials:
1. Generate new credentials in Google Console
2. Update .env file
3. Restart application
4. Test OAuth flow

### If Scope Changes:
1. Review requested scopes in code
2. Verify all scopes approved in consent screen
3. Submit for verification if needed
4. Test with approved scopes only

### If Session Issues:
1. Add debug logging to session middleware
2. Verify session store working
3. Check cookie settings (secure, sameSite)
4. Test flow with cookies enabled

## VALIDATION

```bash
# Unit tests
npm run test -- auth/oauth

# Integration test
npm run test:integration -- auth-flow

# Manual test
# 1. Open incognito browser
# 2. Go to http://localhost:3000/login
# 3. Click "Sign in with Google"
# 4. Authorize application
# 5. Verify successful login and redirect

# Check logs for errors
tail -f logs/auth.log &
# Perform test login
# Ctrl+C to stop tail
```

## SUCCESS CRITERIA
- [ ] User can initiate Google OAuth flow
- [ ] User redirected to Google consent screen
- [ ] After approval, user redirected back to app
- [ ] User successfully logged in
- [ ] User session persists
- [ ] No errors in logs

## MONITORING
After fix:
- Add uptime check for OAuth endpoint
- Set alert for OAuth failure rate >5%
- Add detailed logging for OAuth flow
- Create dashboard for auth metrics
</meta-prompt-output>
</example>

<example number="3">
<input>
"add dark mode"
</input>

<meta-prompt-output>
[See earlier example - comprehensive 5-page plan]
</meta-prompt-output>
</example>

### The Power Law

<power-law-observation>
INPUT: 1 line (5 words)
TEMPLATE: 2 hours to create
OUTPUT: 5 pages (2,000 words)
EXECUTION: Autonomous, first-time success

Compression ratio: 400:1
Time multiplier: 60:1
Success rate improvement: 5-10x
</power-law-observation>

---

## PRACTICAL IMPLEMENTATION

### Creating Your First Template

<template-creation-process>
<step number="1">
<name>Identify Problem Class</name>
<action>What type of work do you do repeatedly?</action>
<examples>
- Add API endpoint
- Fix bug
- Update dependency
- Add React component
</examples>
</step>

<step number="2">
<name>Solve One Perfectly</name>
<action>Do the work once, manually, perfectly</action>
<document>
- Every step taken
- Every file touched
- Every command run
- Every decision made
</document>
</step>

<step number="3">
<name>Extract the Pattern</name>
<action>Generalize from specific to template</action>
<convert>
- Specific file names → [component-name]
- Specific values → [user-input]
- Project-specific → Generic pattern
</convert>
</step>

<step number="4">
<name>Add Validation</name>
<action>Define how to verify success</action>
<include>
- Test commands
- Expected outputs
- Success criteria
- Failure recovery
</include>
</step>

<step number="5">
<name>Create Meta-Prompt</name>
<action>Write prompt that uses template</action>
<structure>
- Input requirements
- Context gathering
- Plan generation
- Output format
</structure>
</step>

<step number="6">
<name>Test and Refine</name>
<action>Use template on real work</action>
<iterate>
- Does it work first time?
- What's missing?
- What's unnecessary?
- Update template
</iterate>
</step>
</template-creation-process>

### Template Starter Kit

**MINIMAL TEMPLATE:**
```markdown
# [Template Name]

## Input Required
- [What information is needed]

## Context to Gather
- [What files/information to read]

## Steps
1. [First step]
2. [Second step]
3. [etc.]

## Validation
```bash
[Commands to verify success]
```

## Success Criteria
- [ ] [Specific outcome 1]
- [ ] [Specific outcome 2]
```

**COMPREHENSIVE TEMPLATE:**
```markdown
# [Template Name] v[X.Y]

## Metadata
- **Type:** Chore | Bug | Feature | Refactor
- **Complexity:** Low | Medium | High
- **Estimated Time:** [X hours]
- **Prerequisites:** [Other templates or setup needed]

## Overview
[Brief description of what this template solves]

## Input Schema
<required>
  - [field_name]: [description]
</required>

<optional>
  - [field_name]: [description] (default: [value])
</optional>

## Context Gathering

### Files to Analyze
- [Path pattern 1]
- [Path pattern 2]

### Information to Extract
- [What to look for]
- [What matters]

### Validation of Context
- [ ] [Context check 1]
- [ ] [Context check 2]

## Planning Process

### Analysis Phase
1. [What to analyze first]
2. [What to look for]
3. [Decisions to make]

### Design Phase
1. [Approach options]
2. [Trade-offs to consider]
3. [Pattern to follow]

### Risk Assessment
- **Low Risk:** [Scenarios]
- **Medium Risk:** [Scenarios]
- **High Risk:** [Scenarios]

## Implementation Steps

### Preparation
```bash
[Setup commands]
```

### Core Implementation
1. **[Step 1 Name]**
   ```[language]
   [Code example or pattern]
   ```
   Verify: [How to check this step worked]

2. **[Step 2 Name]**
   [Detailed instructions]
   Verify: [How to check this step worked]

### Edge Cases
- **Case:** [Scenario]
  **Handling:** [Approach]

### Cleanup
```bash
[Cleanup commands]
```

## Validation Suite

### Level 1: Syntax
```bash
[Linter, type checker]
```
Expected: No errors

### Level 2: Unit Tests
```bash
[Unit test commands]
```
Expected: All pass

### Level 3: Integration Tests
```bash
[Integration test commands]
```
Expected: [Specific outcomes]

### Level 4: Manual Verification
```bash
[Commands to test behavior]
```
Expected: [Specific results]

### Level 5: Smoke Test
```bash
[Overall system check]
```
Expected: Everything still works

## Failure Recovery

### If Validation Fails
1. [First troubleshooting step]
2. [Second troubleshooting step]
3. [When to rollback]

### Rollback Procedure
```bash
[Commands to undo changes]
```

## Success Criteria
- [ ] [Measurable outcome 1]
- [ ] [Measurable outcome 2]
- [ ] [Measurable outcome 3]
- [ ] All validations pass
- [ ] No regressions
- [ ] Documentation updated

## Post-Implementation

### Monitoring
- [What to watch]
- [Alerts to set]

### Documentation
- [What to document]
- [Where to document]

### Learnings
- [What to record]
- [Template improvements]

## Version History
- **v1.0** (2024-09-30): Initial version
- **v1.1** (2024-10-01): Added [improvement]
```

---

## KEY INSIGHTS

<insights>
<insight number="1">
<principle>Success in agentic coding is primarily a planning discipline</principle>
<reason>Agents execute plans perfectly, but need plans to be comprehensive</reason>
</insight>

<insight number="2">
<principle>Templates solve classes, not instances</principle>
<reason>One template handles infinite similar problems</reason>
</insight>

<insight number="3">
<principle>Planning alone is expensive, templates make it free</principle>
<reason>2 hours once ÷ infinite uses ≈ zero cost per use</reason>
</insight>

<insight number="4">
<principle>Meta-prompts compress human effort 100-1000x</principle>
<reason>One line input → comprehensive plan → autonomous execution</reason>
</insight>

<insight number="5">
<principle>Validation must be specified, not assumed</principle>
<reason>Agents can't know how to verify success without explicit commands</reason>
</insight>

<insight number="6">
<principle>Templates improve with use</principle>
<reason>Each execution reveals edge cases and improvements</reason>
</insight>

<insight number="7">
<principle>The 80-20 rule applies to problem classes</principle>
<reason>~10 templates cover 80% of engineering work</reason>
</insight>
</insights>

---

## NEXT STEPS

### Immediate Actions

1. **Identify your top 3 problem classes**
   - What do you do repeatedly?
   - What takes significant time?
   - What could be templated?

2. **Create your first template**
   - Choose the simplest problem class
   - Follow the template creation process
   - Test on real work

3. **Measure the impact**
   - Time to use template vs manual
   - Success rate first attempt
   - Number of reuses

### Building Your Template Library

**Week 1:** Create 3 basic templates (chore, bug, feature)
**Week 2:** Add validation and meta-prompts
**Week 3:** Test on real work, refine based on results
**Week 4:** Share with team, collect feedback

**Month 2:** Expand to 10 templates covering 80% of work
**Month 3:** Achieve 80% one-shot success rate
**Month 6:** Full template coverage, autonomous execution

### Advanced Template Engineering

**After mastering basics:**
- Templates that reference other templates
- Meta-prompts that choose appropriate templates
- Self-improving templates that update based on failures
- Team-wide template libraries
- Template generation from examples (meta-meta-prompts)

---

## CONCLUSION

**The Core Truth:**

> "Engineering was never about writing code.
> It was always about solving problems at scale.
> Templates let you solve problem classes once
> and benefit infinitely."

**Your mission:**
1. Stop solving the same problems repeatedly
2. Encode your expertise into templates
3. Scale your impact 100-1000x
4. Become the engineer they can't replace

**Remember:**
- Great planning is great prompting
- Templates are scaled prompts
- Success is planned, not improvised
- The 80-20 rule: Focus on high-value templates first

**Next Lesson:** AFK Agents - Let Your Product Build Itself

---

<lesson-metadata>
<completion-criteria>
  - [ ] Understand why planning is fundamental to agentic coding
  - [ ] Can explain difference between prompt, plan, and template
  - [ ] Can identify problem classes in your work
  - [ ] Can create basic template with validation
  - [ ] Can write meta-prompt for template
  - [ ] Can calculate ROI of template creation
</completion-criteria>

<estimated-time>
Initial read: 45 minutes
Create first template: 2 hours
Test and refine: 1 hour
Total: 4 hours
</estimated-time>

<prerequisites>
- Lesson 1: Hello Agentic Coding
- Lesson 2: The 12 Leverage Points
- Understanding of your typical engineering workflows
</prerequisites>

<next-lesson>
Lesson 4: AFK Agents
</next-lesson>
</lesson-metadata>