<metadata>
purpose: Complete system guide for template engineering in agentic coding
type: technical-reference
course: Tactical Agentic Coding
category: templates
difficulty: intermediate-advanced
dependencies: lesson-03-success-is-planned
last-updated: 2025-09-30
</metadata>

<overview>
This guide provides a comprehensive system for creating, organizing, and deploying templates in agentic coding. Templates encode engineering workflows into reusable units that solve entire problem classes, enabling exponential scaling of engineering output.
</overview>

# TEMPLATE ENGINEERING GUIDE

**Complete System for Agentic Template Engineering**

---

## WHAT ARE TEMPLATES?

### Definition

<definition>
A template is a structured, reusable prompt that encodes an engineering workflow for solving an entire class of problems. Templates combine context gathering, planning logic, implementation guidance, and validation criteria into a single executable unit.
</definition>

### Why Templates Matter

<impact>
<individual>
10-100x personal productivity through reuse
</individual>

<team>
10x × team_size productivity through knowledge sharing
</team>

<organization>
Compound improvements as templates reference templates
</organization>
</impact>

### Templates vs Other Approaches

<comparison>
<approach name="manual">
<description>Engineer does work from scratch each time</description>
<time-per-use>30-120 minutes</time-per-use>
<consistency>Low (varies by engineer, fatigue, experience)</consistency>
<knowledge-transfer>Slow (requires mentoring, documentation)</knowledge-transfer>
<scaling>Linear with engineer time</scaling>
</approach>

<approach name="documentation">
<description>Written instructions for engineers to follow</description>
<time-per-use>15-60 minutes (read + interpret + execute)</time-per-use>
<consistency>Medium (depends on doc quality and reader interpretation)</consistency>
<knowledge-transfer>Medium (requires reading and understanding)</knowledge-transfer>
<scaling>Better than manual, still requires human execution</scaling>
</approach>

<approach name="scripts">
<description>Automated scripts for specific tasks</description>
<time-per-use>1-5 minutes</time-per-use>
<consistency>High (deterministic execution)</consistency>
<knowledge-transfer>Fast (just run the script)</knowledge-transfer>
<scaling>Excellent for deterministic tasks, limited for creative work</scaling>
</approach>

<approach name="templates">
<description>Agent-executable plans for entire problem classes</description>
<time-per-use>30 seconds - 2 minutes</time-per-use>
<consistency>Very high (encoded best practices, validated output)</consistency>
<knowledge-transfer>Instant (use template, agent executes)</knowledge-transfer>
<scaling>Exponential (handles complex, creative work autonomously)</scaling>
</approach>
</comparison>

### When to Use Templates

<use-cases>
<use-case priority="high">
<scenario>Repetitive work done >5 times</scenario>
<examples>
- Adding CRUD endpoints
- Fixing similar bugs
- Updating dependencies
- Creating React components
</examples>
<roi>Break-even at 5 uses, massive savings after</roi>
</use-case>

<use-case priority="high">
<scenario>Work requiring consistency across team</scenario>
<examples>
- Architecture patterns
- Code style enforcement
- Security best practices
- Testing requirements
</examples>
<roi>Prevents inconsistency costs, technical debt</roi>
</use-case>

<use-case priority="medium">
<scenario>Complex workflows with many steps</scenario>
<examples>
- Multi-file refactorings
- Database migrations
- Feature implementations
- System integrations
</examples>
<roi>Reduces errors, missed steps, debugging time</roi>
</use-case>

<use-case priority="medium">
<scenario>Knowledge preservation</scenario>
<examples>
- Expert engineer workflows
- Lessons learned from incidents
- Optimized solutions
- Domain-specific patterns
</examples>
<roi>Prevents knowledge loss, reduces ramp-up time</roi>
</use-case>

<use-case priority="low">
<scenario>One-off tasks</scenario>
<examples>
- Unique migrations
- Experimental features
- Project-specific hacks
</examples>
<roi>Not worth templating, do manually</roi>
</use-case>
</use-cases>

---

## TEMPLATE STRUCTURE

### Core Components

<template-anatomy>
<component name="metadata" required="true">
<purpose>Identify and categorize the template</purpose>
<elements>
- Template name and version
- Problem class it solves
- Complexity level
- Estimated time
- Prerequisites
- Last updated
</elements>
<example>
```markdown
# API Endpoint Template v2.1

**Type:** Feature
**Complexity:** Medium
**Estimated Time:** 45 minutes
**Prerequisites:** Database models exist
**Last Updated:** 2024-09-30
```
</example>
</component>

<component name="overview" required="true">
<purpose>Explain what this template does</purpose>
<elements>
- Brief description
- When to use it
- What it produces
</elements>
<example>
```markdown
## Overview
This template creates a production-ready REST API endpoint
with full CRUD operations, validation, error handling,
and comprehensive tests.

Use this when: Adding new resource to API
Produces: Endpoint implementation + tests + documentation
```
</example>
</component>

<component name="input-schema" required="true">
<purpose>Define what information is needed</purpose>
<elements>
- Required inputs
- Optional inputs with defaults
- Input validation
</elements>
<example>
```markdown
## Input Required

### Required
- **Resource Name** (singular): e.g., "User", "Product"
- **Database Table**: e.g., "users", "products"
- **Fields**: List of fields with types

### Optional
- **Authentication**: Default true
- **Pagination**: Default true
- **Soft Delete**: Default false
```
</example>
</component>

<component name="context-gathering" required="true">
<purpose>Specify what context agent needs</purpose>
<elements>
- Files to read
- Information to extract
- Dependencies to check
</elements>
<example>
```markdown
## Context Gathering

### Files to Analyze
- `/src/models/*.ts` (existing model patterns)
- `/src/routes/*.ts` (routing conventions)
- `/src/middleware/*.ts` (available middleware)
- `package.json` (dependencies)

### Information to Extract
- Database ORM used (Prisma, TypeORM, etc.)
- Error handling pattern
- Validation library
- Testing framework
- API versioning approach
```
</example>
</component>

<component name="planning-steps" required="true">
<purpose>Guide agent through analysis and design</purpose>
<elements>
- Analysis phase
- Design decisions
- Risk assessment
- Implementation approach
</elements>
<example>
```markdown
## Planning Process

### 1. Analyze Existing Patterns
- Review 3 most recent endpoint implementations
- Extract common patterns
- Identify deviations to avoid

### 2. Design Decisions
- REST vs GraphQL (default: REST)
- Versioning strategy
- Response format
- Error codes to use

### 3. Risk Assessment
- Database schema changes needed?
- Breaking changes to existing API?
- Performance implications?
```
</example>
</component>

<component name="implementation-guidance" required="true">
<purpose>Provide step-by-step implementation</purpose>
<elements>
- Ordered steps
- Code patterns
- File structure
- Best practices
</elements>
<example>
```markdown
## Implementation Steps

### Step 1: Create Model (if not exists)
```typescript
// src/models/[resource].model.ts
import { Model } from './base.model';

export class [Resource]Model extends Model {
  // Fields here
}
```

### Step 2: Create Validation Schema
```typescript
// src/validation/[resource].validation.ts
import { z } from 'zod';

export const create[Resource]Schema = z.object({
  // Validation rules
});
```

### Step 3: Create Controller
[Detailed implementation]
```
</example>
</component>

<component name="validation-suite" required="true">
<purpose>Define how to verify success</purpose>
<elements>
- Test commands
- Expected outputs
- Success criteria
- Failure handling
</elements>
<example>
```markdown
## Validation

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

### Level 2: Unit Tests
```bash
npm run test -- [resource].test.ts
```
Expected: 100% coverage, all pass

### Level 3: Integration Tests
```bash
npm run test:integration -- [resource]
```
Expected: All CRUD operations work

### Level 4: Manual API Test
```bash
curl -X POST http://localhost:3000/api/[resource] \
  -H "Content-Type: application/json" \
  -d '{"test":"data"}'
```
Expected: 201 Created
```
</example>
</component>

<component name="success-criteria" required="true">
<purpose>Define what "done" means</purpose>
<elements>
- Measurable outcomes
- Checklist format
- No ambiguity
</elements>
<example>
```markdown
## Success Criteria
- [ ] Endpoint responds to all CRUD operations
- [ ] Validation rejects invalid input
- [ ] Authentication required (if configured)
- [ ] All tests pass with >80% coverage
- [ ] Error handling returns proper status codes
- [ ] API documentation generated
- [ ] No console errors in logs
```
</example>
</component>

<component name="troubleshooting" required="false">
<purpose>Handle common issues</purpose>
<elements>
- Common errors
- Debug steps
- Solutions
</elements>
</component>

<component name="post-implementation" required="false">
<purpose>What to do after completion</purpose>
<elements>
- Documentation updates
- Monitoring setup
- Team notification
</elements>
</component>

<component name="version-history" required="false">
<purpose>Track template evolution</purpose>
<elements>
- Version changes
- Improvements made
- Lessons learned
</elements>
</component>
</template-anatomy>

### Example: Complete Template

```markdown
# Add CRUD API Endpoint v3.2

**Type:** Feature
**Complexity:** Medium
**Estimated Time:** 45-60 minutes
**Prerequisites:** Database model exists, API framework setup
**Last Updated:** 2024-09-30

## Overview
Creates a production-ready RESTful CRUD endpoint with validation,
authentication, error handling, comprehensive tests, and API documentation.

Use when: Adding new resource to REST API
Produces: Complete endpoint implementation

## Input Required

### Required
- **Resource Name**: Singular form (e.g., "User", "Product")
- **Plural Name**: Plural form (e.g., "Users", "Products")
- **Route Path**: URL path (e.g., "/users", "/products")

### Optional
- **Authentication**: Require auth? (default: true)
- **Pagination**: Enable pagination? (default: true)
- **Soft Delete**: Use soft delete? (default: false)
- **Rate Limiting**: Requests per minute (default: 100)

## Context Gathering

### Read These Files
```bash
src/models/*.model.ts       # Model patterns
src/routes/*.route.ts       # Routing patterns
src/controllers/*.controller.ts  # Controller patterns
src/middleware/auth.ts      # Auth middleware
package.json                # Dependencies
```

### Extract This Information
- ORM: Prisma | TypeORM | Sequelize
- Validation: Zod | Joi | Yup
- Testing: Jest | Vitest | Mocha
- Auth: JWT | Session | OAuth
- Error handling pattern
- Response format convention

## Planning Process

### 1. Analyze Existing Code
Review last 3 endpoints created:
- File naming convention
- Folder structure
- Import patterns
- Code style

### 2. Design Decisions

**Routes:**
```
GET    /api/v1/[resources]      - List with pagination
GET    /api/v1/[resources]/:id  - Get single
POST   /api/v1/[resources]      - Create
PUT    /api/v1/[resources]/:id  - Update
DELETE /api/v1/[resources]/:id  - Delete
```

**Status Codes:**
- 200: Success (GET, PUT)
- 201: Created (POST)
- 204: No Content (DELETE)
- 400: Bad Request (validation)
- 401: Unauthorized (auth)
- 404: Not Found
- 500: Server Error

**Response Format:**
```json
{
  "success": true,
  "data": {...},
  "meta": {
    "page": 1,
    "limit": 20,
    "total": 100
  }
}
```

### 3. Risk Assessment
- [ ] Breaking changes to existing API?
- [ ] Database migration needed?
- [ ] Performance impact (N+1 queries)?
- [ ] Security implications?

## Implementation Steps

### Step 1: Create Route File
```typescript
// src/routes/[resource].route.ts
import { Router } from 'express';
import { [Resource]Controller } from '../controllers/[resource].controller';
import { authenticate } from '../middleware/auth';
import { validate } from '../middleware/validation';
import { [resource]Schemas } from '../validation/[resource].validation';

const router = Router();
const controller = new [Resource]Controller();

// List with pagination
router.get('/',
  authenticate,
  controller.list
);

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

// Create
router.post('/',
  authenticate,
  validate([resource]Schemas.create),
  controller.create
);

// Update
router.put('/:id',
  authenticate,
  validate([resource]Schemas.update),
  controller.update
);

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

export default router;
```

### Step 2: Create Validation Schema
```typescript
// src/validation/[resource].validation.ts
import { z } from 'zod';

export const [resource]Schemas = {
  create: z.object({
    body: z.object({
      // Add fields based on model
      name: z.string().min(1).max(255),
      email: z.string().email().optional(),
    })
  }),

  update: z.object({
    params: z.object({
      id: z.string().uuid()
    }),
    body: z.object({
      // Same as create but all optional
      name: z.string().min(1).max(255).optional(),
      email: z.string().email().optional(),
    })
  }),

  delete: z.object({
    params: z.object({
      id: z.string().uuid()
    })
  })
};
```

### Step 3: Create Controller
```typescript
// src/controllers/[resource].controller.ts
import { Request, Response, NextFunction } from 'express';
import { [Resource]Service } from '../services/[resource].service';
import { ApiError } from '../utils/api-error';

export class [Resource]Controller {
  private service = new [Resource]Service();

  list = async (req: Request, res: Response, next: NextFunction) => {
    try {
      const page = parseInt(req.query.page as string) || 1;
      const limit = parseInt(req.query.limit as string) || 20;

      const result = await this.service.list({ page, limit });

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

  get = async (req: Request, res: Response, next: NextFunction) => {
    try {
      const item = await this.service.getById(req.params.id);

      if (!item) {
        throw new ApiError(404, '[Resource] not found');
      }

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

  create = async (req: Request, res: Response, next: NextFunction) => {
    try {
      const item = await this.service.create(req.body);

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

  update = async (req: Request, res: Response, next: NextFunction) => {
    try {
      const item = await this.service.update(req.params.id, req.body);

      if (!item) {
        throw new ApiError(404, '[Resource] not found');
      }

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

  delete = async (req: Request, res: Response, next: NextFunction) => {
    try {
      await this.service.delete(req.params.id);

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

### Step 4: Create Service
```typescript
// src/services/[resource].service.ts
import { [Resource]Model } from '../models/[resource].model';

export class [Resource]Service {
  async list({ page, limit }: { page: number; limit: number }) {
    const offset = (page - 1) * limit;

    const [items, total] = await Promise.all([
      [Resource]Model.findMany({
        skip: offset,
        take: limit,
        orderBy: { createdAt: 'desc' }
      }),
      [Resource]Model.count()
    ]);

    return { items, total };
  }

  async getById(id: string) {
    return [Resource]Model.findUnique({ where: { id } });
  }

  async create(data: any) {
    return [Resource]Model.create({ data });
  }

  async update(id: string, data: any) {
    return [Resource]Model.update({
      where: { id },
      data
    });
  }

  async delete(id: string) {
    return [Resource]Model.delete({ where: { id } });
  }
}
```

### Step 5: Create Tests
```typescript
// src/tests/[resource].test.ts
import request from 'supertest';
import app from '../app';
import { setupTestDB, teardownTestDB } from './helpers/db';

describe('[Resource] API', () => {
  beforeAll(async () => {
    await setupTestDB();
  });

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

  describe('POST /api/v1/[resources]', () => {
    it('should create a new [resource]', async () => {
      const response = await request(app)
        .post('/api/v1/[resources]')
        .send({
          name: 'Test [Resource]'
        })
        .expect(201);

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

    it('should validate required fields', async () => {
      const response = await request(app)
        .post('/api/v1/[resources]')
        .send({})
        .expect(400);

      expect(response.body.success).toBe(false);
      expect(response.body.error).toBeDefined();
    });

    it('should require authentication', async () => {
      const response = await request(app)
        .post('/api/v1/[resources]')
        .send({ name: 'Test' })
        .expect(401);
    });
  });

  // Additional tests for GET, PUT, DELETE...
});
```

### Step 6: Register Route
```typescript
// src/app.ts or src/routes/index.ts
import [resource]Routes from './routes/[resource].route';

// Add to routes
app.use('/api/v1/[resources]', [resource]Routes);
```

### Step 7: Generate API Documentation
```bash
npm run docs:generate
```

## Validation Suite

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

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

### Level 3: Integration Tests
```bash
npm run test:integration
```
Expected: All CRUD operations work end-to-end

### Level 4: Manual API Testing

**Create:**
```bash
TOKEN="your-test-token"
curl -X POST http://localhost:3000/api/v1/[resources] \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"name":"Test Item"}'
```
Expected: 201 Created, returns item with ID

**List:**
```bash
curl http://localhost:3000/api/v1/[resources] \
  -H "Authorization: Bearer $TOKEN"
```
Expected: 200 OK, returns array with pagination

**Get Single:**
```bash
curl http://localhost:3000/api/v1/[resources]/[id] \
  -H "Authorization: Bearer $TOKEN"
```
Expected: 200 OK, returns single item

**Update:**
```bash
curl -X PUT http://localhost:3000/api/v1/[resources]/[id] \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"name":"Updated"}'
```
Expected: 200 OK, returns updated item

**Delete:**
```bash
curl -X DELETE http://localhost:3000/api/v1/[resources]/[id] \
  -H "Authorization: Bearer $TOKEN"
```
Expected: 204 No Content

### Level 5: Smoke Test
```bash
npm run build
npm run start:prod &
sleep 5
curl http://localhost:3000/health
kill %1
```
Expected: Server starts, health check passes

## Success Criteria

- [ ] All routes respond correctly
- [ ] Validation rejects invalid input
- [ ] Authentication enforced (if enabled)
- [ ] Pagination works correctly
- [ ] All tests pass with >80% coverage
- [ ] No TypeScript errors
- [ ] No linter errors
- [ ] API documentation generated
- [ ] Error handling returns proper status codes
- [ ] No console errors in development
- [ ] Build succeeds
- [ ] Health check passes

## Troubleshooting

### Issue: Tests failing with "Cannot find module"
**Solution:**
```bash
npm run build
npm run test
```

### Issue: 401 Unauthorized in tests
**Solution:** Add mock authentication in test setup

### Issue: Database queries timing out
**Solution:** Check database connection, add indexes if needed

### Issue: Pagination returning incorrect total
**Solution:** Verify count query doesn't include pagination params

## Post-Implementation

### Update API Documentation
```bash
npm run docs:generate
git add docs/api.md
```

### Add Monitoring
- Set up error tracking for endpoint
- Add performance monitoring
- Set alert for error rate >5%

### Team Notification
- Announce new endpoint in team chat
- Update API changelog
- Link to documentation

## Version History

- **v3.2** (2024-09-30): Added soft delete support
- **v3.1** (2024-09-15): Improved error handling
- **v3.0** (2024-09-01): Major refactor, added services layer
- **v2.0** (2024-08-01): Added comprehensive testing
- **v1.0** (2024-07-01): Initial version
```

---

## TEMPLATE TYPES

### Classification System

<template-categories>
<category name="chore">
<description>Routine maintenance tasks</description>
<characteristics>
- Predictable steps
- Low risk
- High frequency
- Automatable
</characteristics>
<examples>
- Update dependencies
- Format code
- Add environment variable
- Update documentation
- Run database backup
</examples>
</category>

<category name="bug">
<description>Debugging and fixing issues</description>
<characteristics>
- Investigation required
- Root cause analysis
- Testing critical
- Regression prevention
</characteristics>
<examples>
- API returning errors
- UI not rendering
- Performance degradation
- Memory leak
- Security vulnerability
</examples>
</category>

<category name="feature">
<description>Adding new functionality</description>
<characteristics>
- Creative implementation
- Architecture decisions
- Multiple files
- Comprehensive testing
</characteristics>
<examples>
- New API endpoint
- UI component
- Database table
- Authentication method
- Third-party integration
</examples>
</category>

<category name="refactor">
<description>Improving existing code</description>
<characteristics>
- Behavior preservation critical
- Extensive testing
- Performance monitoring
- Rollback plan needed
</characteristics>
<examples>
- Extract function
- Optimize query
- Modernize syntax
- Improve error handling
- Reduce complexity
</examples>
</category>
</template-categories>

### Chore Template Pattern

```markdown
# [Chore Name] Template

## Type: Chore
## Frequency: [Daily|Weekly|Monthly|As-needed]
## Automation Potential: [High|Medium|Low]

## Overview
[What this chore accomplishes]

## When to Run
- [Trigger condition 1]
- [Trigger condition 2]

## Prerequisites
- [ ] [Requirement 1]
- [ ] [Requirement 2]

## Steps
1. [Step 1]
2. [Step 2]
3. [Verification]

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

## Rollback
```bash
[If something goes wrong]
```

## Automation Note
[How this could be automated in future]
```

**Example: Update Dependencies**
```markdown
# Update Project Dependencies v2.0

## Type: Chore
## Frequency: Weekly
## Automation Potential: High (could run in CI)

## Overview
Updates all project dependencies to latest compatible versions,
runs full test suite, and verifies build succeeds.

## When to Run
- Every Monday morning
- Before major releases
- When security vulnerability discovered

## Prerequisites
- [ ] All tests currently passing
- [ ] No uncommitted changes
- [ ] On main branch
- [ ] CI/CD pipeline green

## Steps

### 1. Check Outdated Packages
```bash
npm outdated
```

### 2. Update Patch Versions (Lowest Risk)
```bash
npm update
```

### 3. Run Tests
```bash
npm run test
npm run type-check
npm run lint
```

### 4. Update Minor Versions (Medium Risk)
```bash
npm install package-name@latest
```
Repeat for each package with minor update available.
Run tests after each.

### 5. Review Major Versions (High Risk)
For each package with major update:
```bash
# Check changelog
npm view package-name versions
npm view package-name@latest
# Read breaking changes
# Update code if needed
npm install package-name@latest
npm run test
```

### 6. Verify Build
```bash
npm run build
```

### 7. Commit Changes
```bash
git add package.json package-lock.json
git commit -m "chore: update dependencies

- Updated X packages
- All tests passing
- Build succeeds"
```

## Validation
```bash
npm run test
npm run type-check
npm run lint
npm run build
npm run start:prod &
sleep 5
curl http://localhost:3000/health
kill %1
```

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

## Success Criteria
- [ ] All packages updated
- [ ] Zero test failures
- [ ] Build succeeds
- [ ] Application starts correctly
- [ ] Health check passes
- [ ] Changes committed

## Automation Note
This could be fully automated:
1. Dependabot opens PRs
2. CI runs all tests
3. If green, auto-merge
4. Weekly summary report
```

### Bug Template Pattern

```markdown
# [Bug Type] Debugging Template

## Type: Bug
## Severity: [Critical|High|Medium|Low]
## Complexity: [High|Medium|Low]

## Symptoms
[What the user/system experiences]

## Context to Gather
- Error messages and stack traces
- Recent changes (git log)
- Affected files
- Environment information

## Investigation Steps
1. [Reproduce]
2. [Gather logs]
3. [Analyze root cause]
4. [Identify fix]

## Root Cause Analysis Framework
[Systematic approach to finding cause]

## Implementation
[How to fix once cause identified]

## Validation
[Verify fix works, no regression]

## Prevention
[How to prevent similar bugs]
```

**Example: API 500 Error**
```markdown
# API 500 Error Debugging Template v2.5

## Type: Bug
## Severity: High
## Complexity: Medium

## Symptoms
- API endpoint returns 500 Internal Server Error
- Request that should succeed fails
- May affect single or multiple endpoints

## Input Required
- **Endpoint:** [URL path]
- **Method:** [GET|POST|PUT|DELETE]
- **Request Body:** [If applicable]
- **Error First Seen:** [Timestamp]

## Context to Gather

### 1. Error Details
```bash
# Get full error from logs
grep -A 20 "500" logs/error.log | tail -100

# Or if using logging service
curl "https://api.logging-service.com/logs?level=error&since=1h"
```

### 2. Recent Changes
```bash
# Changes in last 24 hours
git log --since="24 hours ago" --oneline

# Changes to specific endpoint
git log --since="1 week ago" -- api/routes/[endpoint].ts
```

### 3. Environment Info
```bash
node --version
npm list
echo $NODE_ENV
```

## Investigation Steps

### Step 1: Reproduce Error
```bash
curl -X [METHOD] http://localhost:3000[endpoint] \
  -H "Content-Type: application/json" \
  -d '[request-body]'
```

Expected: 500 error
Actual: [Result]

### Step 2: Check Server Logs
```bash
tail -f logs/error.log
```

Trigger error again, watch logs for:
- Stack trace
- Error message
- File and line number

### Step 3: Add Debug Logging
```typescript
// In suspected file
import { logger } from './utils/logger';

// Before error point
logger.debug('Request received:', { body: req.body });
logger.debug('Processing step 1');
logger.debug('Variable state:', { var1, var2 });
```

Restart server, reproduce error, check logs.

### Step 4: Check Database
```bash
# If database-related
npm run db:check-connection
npm run db:show-tables
npm run db:describe-table [table-name]
```

### Step 5: Test in Isolation
```bash
# Run unit test for specific function
npm run test -- [file].test.ts

# If no test exists, create one
# [Create test that reproduces error]
```

## Root Cause Analysis

### Check These Common Causes (Priority Order)

**1. Database Issues (40% of 500 errors)**
- [ ] Connection pool exhausted
- [ ] Query syntax error
- [ ] Missing table/column
- [ ] Constraint violation
- [ ] Timeout

**2. Unhandled Exceptions (30%)**
- [ ] Missing try-catch
- [ ] Async/await error
- [ ] Promise rejection
- [ ] Null pointer

**3. Dependency Issues (15%)**
- [ ] External API down
- [ ] Service unavailable
- [ ] Network timeout
- [ ] SSL/TLS error

**4. Input Validation (10%)**
- [ ] Unexpected data type
- [ ] Missing required field
- [ ] Schema mismatch
- [ ] Injection attack

**5. Resource Exhaustion (5%)**
- [ ] Out of memory
- [ ] Disk full
- [ ] File descriptors exhausted
- [ ] CPU maxed

## Implementation (Based on Root Cause)

### If Database Issue:
```typescript
// Add connection check
try {
  await db.$queryRaw`SELECT 1`;
} catch (error) {
  logger.error('Database connection failed:', error);
  throw new ServiceUnavailableError('Database offline');
}

// Add query timeout
const result = await db.query(sql, {
  timeout: 5000
});

// Close connections properly
try {
  // Query
} finally {
  await connection.close();
}
```

### If Unhandled Exception:
```typescript
// Wrap in try-catch
try {
  const result = await riskyOperation();
  return result;
} catch (error) {
  logger.error('Operation failed:', error);
  throw new ApiError(500, 'Operation failed', error);
}

// Handle promise rejections
Promise.resolve(asyncOp())
  .catch(error => {
    logger.error('Async op failed:', error);
    throw error;
  });
```

### If Dependency Issue:
```typescript
// Add timeout and retry
const response = await fetch(externalAPI, {
  timeout: 5000,
  retry: 3,
  retryDelay: 1000
});

// Add circuit breaker
const result = await circuitBreaker.execute(
  () => externalService.call()
);
```

### If Input Validation:
```typescript
// Add validation before processing
const schema = z.object({
  field: z.string().min(1).max(255)
});

const validated = schema.parse(req.body);
// Now safe to use validated data
```

## Validation Suite

### 1. Unit Test for Bug
```typescript
// Create test that reproduces bug
test('should handle [scenario] without 500 error', async () => {
  const response = await endpoint([problem-input]);
  expect(response.status).not.toBe(500);
  expect(response.status).toBe([expected-status]);
});
```

### 2. Run All Tests
```bash
npm run test
npm run test:integration
```

### 3. Manual Verification
```bash
# Original failing request
curl [original-failing-request]

# Expected: Success response
```

### 4. Load Test (Ensure no resource leak)
```bash
npm run test:load -- [endpoint]
```

### 5. Monitor Logs
```bash
# Run app, check for errors
npm run dev &
sleep 5
curl [endpoint]
grep -i error logs/app.log
kill %1
```

## Success Criteria

- [ ] Original error no longer occurs
- [ ] Endpoint returns expected status code
- [ ] Unit test added for this scenario
- [ ] All existing tests still pass
- [ ] No new errors in logs
- [ ] Load test shows no resource leaks
- [ ] Error handling improved
- [ ] Logging added for debugging

## Prevention

### Add to Codebase
1. **Test case** for this scenario
2. **Error handling** where it was missing
3. **Logging** for future debugging
4. **Monitoring alert** for this error type

### Add to Process
1. **Code review checklist** item
2. **Testing requirement** for similar changes
3. **Documentation** of this pattern

### Update Template
Add this root cause to common causes list if new pattern discovered.

## Version History
- **v2.5** (2024-09-30): Added resource exhaustion category
- **v2.0** (2024-08-01): Restructured with priority order
- **v1.0** (2024-06-01): Initial version
```

### Feature Template Pattern

```markdown
# Add [Feature Type] Template

## Type: Feature
## Complexity: [High|Medium|Low]
## Files Modified: [Estimated number]
## Time Estimate: [Hours]

## Overview
[What this feature adds]

## Input Required
[Specific information needed]

## Architecture Analysis
[How this fits into existing system]

## Implementation Plan
[Step by step, file by file]

## Testing Strategy
[Unit, integration, E2E tests]

## Validation
[How to verify it works]

## Documentation
[What docs to update]
```

(See complete API endpoint example above for detailed feature template)

### Refactor Template Pattern

```markdown
# Refactor [Component] Template

## Type: Refactor
## Risk Level: [High|Medium|Low]
## Behavior Change: [Yes|No]

## Current State
[What exists now]

## Target State
[What it should become]

## Motivation
[Why refactor]

## Approach
[How to refactor safely]

## Testing Strategy
[How to ensure no behavior change]

## Rollback Plan
[How to undo if needed]
```

**Example: Extract Function Refactor**
```markdown
# Extract Function Refactoring Template v1.5

## Type: Refactor
## Risk Level: Low-Medium
## Behavior Change: No (must preserve exact behavior)

## Overview
Extracts complex logic into separate, testable, reusable functions.
Improves readability, maintainability, and testability.

## When to Use
- Function >50 lines
- Repeated logic
- Complex nested conditions
- Difficult to test
- Poor readability

## Input Required
- **File Path:** [Path to file]
- **Function Name:** [Current function]
- **Lines to Extract:** [Line range]
- **New Function Name:** [Descriptive name]

## Current State Analysis

### 1. Read Current Implementation
```bash
cat [file-path]
```

### 2. Identify Extracted Code
Lines [X-Y] will become new function.

### 3. Identify Dependencies
What does extracted code depend on?
- Variables from parent scope
- Imports
- External state

### 4. Identify Return Value
What does extracted code produce/modify?

## Refactoring Steps

### Step 1: Write Tests for Current Behavior
```typescript
// Create test BEFORE refactoring
test('current implementation works', () => {
  const result = originalFunction(testInput);
  expect(result).toBe(expectedOutput);
});
```

Run test, ensure passes:
```bash
npm run test -- [file].test.ts
```

### Step 2: Extract Function
```typescript
// New function with extracted logic
function newFunctionName(param1: Type1, param2: Type2): ReturnType {
  // [Extracted code]
  return result;
}
```

### Step 3: Replace Original with Call
```typescript
function originalFunction(input: InputType) {
  // Before extracted section

  // Replace extracted code with function call
  const result = newFunctionName(dep1, dep2);

  // After extracted section
  return finalResult;
}
```

### Step 4: Run Tests Again
```bash
npm run test -- [file].test.ts
```

Expected: All tests still pass (behavior unchanged)

### Step 5: Add Tests for New Function
```typescript
test('extracted function works independently', () => {
  const result = newFunctionName(input1, input2);
  expect(result).toBe(expected);
});
```

### Step 6: Improve New Function
Now that it's extracted:
- Add better parameter names
- Add JSDoc documentation
- Add input validation
- Add error handling

### Step 7: Final Validation
```bash
npm run test
npm run type-check
npm run lint
```

## Validation Suite

### 1. Behavior Preservation
```bash
# All tests must still pass
npm run test
```

### 2. No Type Errors
```bash
npm run type-check
```

### 3. No Lint Issues
```bash
npm run lint
```

### 4. Coverage Maintained or Improved
```bash
npm run test:coverage
```

### 5. Manual Testing
Run application, test affected feature manually.

## Success Criteria

- [ ] Extracted function has clear, descriptive name
- [ ] Function has single responsibility
- [ ] All parameters explicitly passed (no hidden dependencies)
- [ ] Return value is clear and typed
- [ ] All original tests still pass
- [ ] New tests added for extracted function
- [ ] No behavior change (verified by tests)
- [ ] Code coverage maintained or improved
- [ ] Lint passes
- [ ] Type check passes
- [ ] JSDoc added to new function

## Rollback Plan

```bash
# If anything goes wrong
git checkout [file-path]
npm install
npm run test
```

## Common Pitfalls

**Pitfall 1: Hidden Dependencies**
- Extracted function accesses parent scope variables
- Solution: Pass all dependencies as parameters

**Pitfall 2: Side Effects**
- Extracted function modifies external state
- Solution: Return values instead of mutating

**Pitfall 3: Over-Extraction**
- Creating too many tiny functions
- Solution: Extract when >10 lines or repeated

**Pitfall 4: Poor Naming**
- New function name doesn't describe what it does
- Solution: Name clearly describes the action/result

## Version History
- **v1.5** (2024-09-30): Added common pitfalls section
- **v1.0** (2024-07-01): Initial version
```

---

## HOW TO CREATE TEMPLATES FOR ANY PROBLEM CLASS

### The Template Creation Process

<process>
<phase name="identification">
<step number="1">Identify repetitive work</step>
<questions>
- What do I do more than 5 times?
- What takes significant time?
- What requires consistency?
- What knowledge should be preserved?
</questions>
</phase>

<phase name="documentation">
<step number="2">Do the work once, perfectly</step>
<capture>
- Every step taken
- Every decision made
- Every file touched
- Every command run
- Every pitfall encountered
</capture>
</phase>

<phase name="generalization">
<step number="3">Extract the pattern</step>
<transform>
- Specific → General
- Example → Variables
- One case → All cases
- Implicit → Explicit
</transform>
</phase>

<phase name="validation">
<step number="4">Define success criteria</step>
<specify>
- Commands to run
- Expected outputs
- How to verify
- What "done" means
</specify>
</phase>

<phase name="meta-prompt-creation">
<step number="5">Create meta-prompt</step>
<enable>
- Minimal input → Comprehensive plan
- Context gathering automated
- Plan generation logic
- Output format defined
</enable>
</phase>

<phase name="iteration">
<step number="6">Test and improve</step>
<refine>
- Use on real work
- Identify gaps
- Add edge cases
- Update template
</refine>
</phase>
</process>

### Detailed Walkthrough: Creating a Template

**SCENARIO: You need to create a template for "Add React Component"**

#### Step 1: Identify the Pattern

**Observations:**
- You create React components frequently (20+ times per month)
- Each component follows similar structure
- Variations: functional vs class, with/without state, with/without props
- Time per component: 15-30 minutes
- Opportunity: Template could reduce to 2 minutes

#### Step 2: Do It Once Perfectly

**Task:** Create a UserProfile component

**Document everything:**

```
STEP 1: Create component file
- Location: src/components/UserProfile/UserProfile.tsx
- Naming: PascalCase, matches folder name

STEP 2: Set up basic structure
- Import React
- Define props interface
- Create functional component
- Export default

STEP 3: Add TypeScript types
- Props interface with JSDoc
- Proper typing for all variables

STEP 4: Implement logic
- State management if needed
- Event handlers
- Side effects (useEffect)

STEP 5: Add styling
- Import styles
- Apply className

STEP 6: Create tests
- File: src/components/UserProfile/UserProfile.test.tsx
- Test rendering
- Test interactions
- Test edge cases

STEP 7: Create Storybook story
- File: src/components/UserProfile/UserProfile.stories.tsx
- Default story
- Variations (different props)

STEP 8: Update index
- Export from src/components/index.ts

STEP 9: Validate
- npm run test
- npm run type-check
- npm run lint
- npm run storybook (manual check)
```

**Files created:**
- `UserProfile.tsx` (component)
- `UserProfile.test.tsx` (tests)
- `UserProfile.stories.tsx` (storybook)
- `index.ts` (updated export)

**Time taken:** 25 minutes

#### Step 3: Extract the Pattern

**Generalize from specific:**

```
UserProfile → [ComponentName]
src/components/UserProfile → src/components/[ComponentName]
user profile → [component purpose]
name, email, avatar → [props needed]
```

**Identify variations:**
- With/without props
- With/without state
- With/without effects
- Presentational vs container

#### Step 4: Create Template Structure

```markdown
# Add React Component Template v1.0

## Type: Feature
## Complexity: Low-Medium
## Time Estimate: 2-5 minutes

## Input Required

### Required
- **Component Name:** PascalCase (e.g., "UserProfile", "Button")
- **Component Purpose:** Brief description (e.g., "Display user information")

### Optional
- **Props:** List of props with types (default: none)
- **State:** Does it need state? (default: no)
- **Effects:** Does it need useEffect? (default: no)
- **Styling:** CSS Modules | Styled Components | Tailwind (default: CSS Modules)

## Context to Gather

### Read These Files
```bash
src/components/*/*.tsx    # Component patterns
src/components/index.ts   # Export structure
package.json              # Dependencies (styled-components?)
.storybook/main.js        # Storybook config
```

## Implementation Steps

### Step 1: Create Component File
```bash
mkdir -p src/components/[ComponentName]
touch src/components/[ComponentName]/[ComponentName].tsx
```

### Step 2: Generate Component Code
```typescript
// src/components/[ComponentName]/[ComponentName].tsx
import React from 'react';
import styles from './[ComponentName].module.css';

/**
 * [ComponentName] - [Component Purpose]
 */
export interface [ComponentName]Props {
  [Add props here based on input]
}

export const [ComponentName]: React.FC<[ComponentName]Props> = ({
  [destructure props]
}) => {
  [Add state if requested]

  [Add effects if requested]

  return (
    <div className={styles.container}>
      {/* Component JSX */}
    </div>
  );
};

export default [ComponentName];
```

### Step 3: Create Styles
```css
/* src/components/[ComponentName]/[ComponentName].module.css */
.container {
  /* Styles here */
}
```

### Step 4: Create Tests
```typescript
// src/components/[ComponentName]/[ComponentName].test.tsx
import { render, screen } from '@testing-library/react';
import { [ComponentName] } from './[ComponentName]';

describe('[ComponentName]', () => {
  it('renders without crashing', () => {
    render(<[ComponentName] />);
    expect(screen.getByRole([appropriate-role])).toBeInTheDocument();
  });

  it('displays [expected behavior]', () => {
    render(<[ComponentName] [props] />);
    expect(screen.getByText([expected-text])).toBeInTheDocument();
  });
});
```

### Step 5: Create Storybook Story
```typescript
// src/components/[ComponentName]/[ComponentName].stories.tsx
import type { Meta, StoryObj } from '@storybook/react';
import { [ComponentName] } from './[ComponentName]';

const meta: Meta<typeof [ComponentName]> = {
  title: 'Components/[ComponentName]',
  component: [ComponentName],
  tags: ['autodocs'],
};

export default meta;
type Story = StoryObj<typeof [ComponentName]>;

export const Default: Story = {
  args: {
    [default props]
  },
};

[Additional stories for variations]
```

### Step 6: Update Exports
```typescript
// src/components/index.ts
// Add export
export { [ComponentName] } from './[ComponentName]/[ComponentName]';
export type { [ComponentName]Props } from './[ComponentName]/[ComponentName]';
```

## 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: Tests
```bash
npm run test -- [ComponentName].test.tsx
```
Expected: All tests pass

### Level 4: Storybook
```bash
npm run storybook
```
Manual: Verify component renders correctly in Storybook

### Level 5: Integration
```bash
npm run build
```
Expected: Build succeeds, component exported

## Success Criteria

- [ ] Component file created with proper structure
- [ ] Props interface defined and documented
- [ ] Component renders without errors
- [ ] Tests created and passing
- [ ] Storybook story created
- [ ] Exported from index.ts
- [ ] No TypeScript errors
- [ ] No lint errors
- [ ] Follows project conventions
- [ ] Documentation (JSDoc) present

## Version History
- **v1.0** (2024-09-30): Initial version
```

#### Step 5: Create Meta-Prompt

```markdown
# META-PROMPT: Generate React Component

## Role
You are a senior React developer creating a new component following best practices.

## Input Format
Receive one of:
1. Minimal: "[ComponentName]"
2. Detailed: "[ComponentName] that [does X] with props [Y, Z]"

## Process

### 1. Parse Input
Extract:
- Component name (PascalCase)
- Component purpose
- Required props
- State needs
- Effect needs

### 2. Analyze Codebase
```bash
# Find similar components
ls src/components/*/
# Check most recent component for patterns
cat src/components/[most-recent]/*.tsx
# Check export structure
cat src/components/index.ts
```

### 3. Generate Comprehensive Plan
Use "Add React Component Template" with all context filled in.

### 4. Output Specification
Write complete implementation plan to:
`specs/features/[date]-add-[component-name]-component.md`

## Output Format
```markdown
# Feature: Add [ComponentName] Component

[Use full template structure]
[Fill in all sections based on analysis]
[Include specific code for this component]
```

## Validation
Before outputting:
- [ ] Component name is valid PascalCase
- [ ] All props have types
- [ ] Test cases are specific
- [ ] Storybook args match props
- [ ] Follows existing patterns
```

#### Step 6: Test the Template

**Test Case 1: Minimal Input**
```
Input: "Button"

Output: Complete plan for Button component
- Functional component
- Props: children, onClick, disabled, variant
- Tests for all interactions
- Storybook with multiple variants
- Accessible (proper role, aria-labels)

Time: 30 seconds to generate, 2 minutes for agent to execute
Result: Success ✓
```

**Test Case 2: Complex Input**
```
Input: "DataTable that displays paginated data with sorting and filtering"

Output: Complete plan for DataTable component
- Props: data, columns, onSort, onFilter, pagination
- State: currentPage, sortColumn, filters
- Effects: data fetching when page changes
- Tests: rendering, sorting, filtering, pagination
- Storybook: various data sets and configurations

Time: 45 seconds to generate, 8 minutes for agent to execute
Result: Success ✓
```

**Test Case 3: Edge Case**
```
Input: "UserAuthForm"

Output: Plan detected this needs:
- Form state management (formik or react-hook-form)
- Validation schema
- API integration
- Error handling
- Loading states

Time: 1 minute to generate, 12 minutes for agent to execute
Result: Success ✓, but identified missing dependency
```

#### Step 7: Improve Based on Testing

**Improvements Needed:**
1. Template should detect form components and include form library
2. Add option for component composition (compound components)
3. Add accessibility checks to validation
4. Include performance considerations for large lists

**Updated Template v1.1:**
- Added form component detection
- Added accessibility validation
- Added performance guidance for lists
- Added compound component pattern option

---

## TEMPLATE LIBRARY ORGANIZATION

### Directory Structure

<directory-structure>
/templates
  ├── README.md                    # Template library index
  ├── meta-prompts/               # Meta-prompts for each template
  │   ├── chore-meta.md
  │   ├── bug-meta.md
  │   ├── feature-meta.md
  │   └── refactor-meta.md
  ├── chores/
  │   ├── update-dependencies.md
  │   ├── format-code.md
  │   ├── add-environment-variable.md
  │   ├── update-documentation.md
  │   └── database-backup.md
  ├── bugs/
  │   ├── debug-api-error.md
  │   ├── debug-frontend-error.md
  │   ├── fix-performance-issue.md
  │   ├── fix-security-vulnerability.md
  │   └── fix-memory-leak.md
  ├── features/
  │   ├── add-crud-endpoint.md
  │   ├── add-react-component.md
  │   ├── add-database-table.md
  │   ├── add-authentication.md
  │   ├── add-third-party-integration.md
  │   └── add-api-versioning.md
  ├── refactors/
  │   ├── extract-function.md
  │   ├── optimize-query.md
  │   ├── improve-error-handling.md
  │   ├── modernize-syntax.md
  │   ├── add-types.md
  │   └── reduce-complexity.md
  └── custom/                      # Project-specific templates
      ├── deploy-to-production.md
      ├── create-migration.md
      └── add-feature-flag.md
</directory-structure>

### Template Library README

```markdown
# Template Library

## Overview
This directory contains reusable templates for all common engineering tasks.
Each template encodes best practices and enables autonomous agent execution.

## Usage

### Quick Start
1. Identify problem class (chore, bug, feature, refactor)
2. Find appropriate template
3. Use meta-prompt to generate plan
4. Agent executes autonomously

### Example
```bash
# Problem: Need to add new API endpoint
# Template: features/add-crud-endpoint.md

# Generate plan:
claude-code "Use add-crud-endpoint template for Products resource"

# Agent will:
# 1. Read template
# 2. Analyze codebase
# 3. Generate comprehensive plan
# 4. Execute implementation
# 5. Run all validations
# 6. Report success
```

## Template Index

### Chores (Routine Maintenance)
| Template | Frequency | Time | Automation |
|----------|-----------|------|------------|
| update-dependencies | Weekly | 15m | High |
| format-code | On-demand | 2m | High |
| add-environment-variable | As-needed | 5m | Medium |
| update-documentation | As-needed | 10m | Low |
| database-backup | Daily | 5m | High |

### Bugs (Debugging & Fixes)
| Template | Severity | Complexity | Time |
|----------|----------|------------|------|
| debug-api-error | High | Medium | 30-60m |
| debug-frontend-error | Medium | Medium | 20-45m |
| fix-performance-issue | Medium | High | 1-3h |
| fix-security-vulnerability | Critical | High | 1-4h |
| fix-memory-leak | High | High | 2-6h |

### Features (New Functionality)
| Template | Complexity | Files | Time |
|----------|------------|-------|------|
| add-crud-endpoint | Medium | 4-6 | 45m |
| add-react-component | Low | 3-4 | 15m |
| add-database-table | Medium | 2-3 | 30m |
| add-authentication | High | 10+ | 3-5h |
| add-third-party-integration | High | 5-10 | 2-4h |

### Refactors (Code Improvement)
| Template | Risk | Behavior Change | Time |
|----------|------|-----------------|------|
| extract-function | Low | No | 15m |
| optimize-query | Medium | No | 30m |
| improve-error-handling | Low | Yes (better) | 45m |
| modernize-syntax | Low | No | 20m |
| add-types | Low | No | 1h |

## Creating New Templates

See `/docs/template-creation-guide.md` for detailed process.

### Quick Checklist
- [ ] Template has clear purpose
- [ ] Input schema defined
- [ ] Context gathering specified
- [ ] Implementation steps detailed
- [ ] Validation suite complete
- [ ] Success criteria measurable
- [ ] Meta-prompt created
- [ ] Tested on real work

## Template Versioning

Templates use semantic versioning:
- **Major (v2.0):** Breaking changes to input/output format
- **Minor (v1.1):** New features, improved guidance
- **Patch (v1.0.1):** Bug fixes, clarifications

## Contributing

To add a new template:
1. Create template following structure guide
2. Test on real work (minimum 3 uses)
3. Create meta-prompt
4. Update this README
5. Submit for review

## Maintenance

### Monthly Review
- Check template usage statistics
- Identify templates needing updates
- Remove unused templates
- Add new templates for emerging patterns

### Quarterly Audit
- Validate all templates still work
- Update for new dependencies
- Consolidate similar templates
- Improve based on feedback

## Metrics

### Template Effectiveness
- **Usage Count:** How many times used
- **Success Rate:** First-time success percentage
- **Time Saved:** Avg time saved per use
- **Team Adoption:** Percentage of team using

### Goals
- 80% of work covered by templates
- 80% first-time success rate
- 90% team adoption
- 10x time savings

## Support

Questions about templates?
- Check template README
- See examples in /examples
- Ask in #engineering-templates channel
- Tag @template-maintainers
```

### Template Discovery System

**Problem:** How do engineers find the right template?

**Solution 1: Template Selector Meta-Prompt**
```markdown
# META-PROMPT: Template Selector

## Role
You analyze the user's request and recommend the appropriate template.

## Process

### 1. Analyze Request
Classify by:
- Type: chore, bug, feature, refactor
- Complexity: low, medium, high
- Domain: API, frontend, database, infrastructure

### 2. Search Template Library
```bash
ls templates/*/
cat templates/README.md
```

### 3. Recommend Template
Output:
- **Primary Template:** [name and path]
- **Why:** [explanation]
- **Alternatives:** [if applicable]
- **Estimated Time:** [based on template]

## Examples

Input: "Add endpoint for managing orders"
Output:
- Primary: templates/features/add-crud-endpoint.md
- Why: Standard REST CRUD endpoint
- Alternatives: None needed
- Time: 45 minutes

Input: "Users getting 500 error on checkout"
Output:
- Primary: templates/bugs/debug-api-error.md
- Why: Server error investigation needed
- Alternatives: templates/bugs/fix-performance-issue.md if load-related
- Time: 30-60 minutes
```

**Solution 2: Template Tags**
```markdown
# Template: Add CRUD Endpoint

**Tags:** #api #crud #rest #feature #backend #database
**Complexity:** medium
**Time:** 45m
**Prerequisites:** #database-model #api-framework
```

Search by tag:
```bash
grep -r "#api" templates/
grep -r "#crud" templates/
```

---

## TEAM ADOPTION STRATEGIES

### Phase 1: Pilot (Week 1-2)

<pilot-phase>
<goals>
- Create 3-5 core templates
- Test with 2-3 early adopters
- Prove value with metrics
</goals>

<actions>
1. Identify top 3 repetitive tasks
2. Create templates with early adopters
3. Track time savings
4. Gather feedback
5. Iterate rapidly
</actions>

<success-criteria>
- Templates work first time 80%+
- Time savings 10x+ demonstrated
- Early adopters enthusiastic
</success-criteria>
</pilot-phase>

### Phase 2: Expansion (Week 3-6)

<expansion-phase>
<goals>
- Expand to 10-15 templates
- Onboard half the team
- Establish template creation process
</goals>

<actions>
1. Template creation workshop
2. Each engineer creates 1 template
3. Build template library
4. Create discovery system
5. Measure team adoption
</actions>

<success-criteria>
- 50% of team using templates
- 15+ templates in library
- Team creating new templates independently
</success-criteria>
</expansion-phase>

### Phase 3: Standardization (Week 7-12)

<standardization-phase>
<goals>
- Full team adoption
- Templates as standard practice
- Continuous improvement system
</goals>

<actions>
1. Make templates required for common tasks
2. Add template usage to code review
3. Monthly template review meeting
4. Metrics dashboard
5. Template champions program
</actions>

<success-criteria>
- 90%+ team adoption
- 80%+ work uses templates
- Measurable productivity gains
- Self-sustaining improvement
</success-criteria>
</standardization-phase>

### Adoption Tactics

<tactic name="show-dont-tell">
**Instead of:** "Here's documentation on templates"
**Do:** Live demo showing one-line input → autonomous completion
**Impact:** Immediate understanding of value
</tactic>

<tactic name="start-small">
**Instead of:** "Template everything"
**Do:** Start with most painful repetitive task
**Impact:** Quick win builds momentum
</tactic>

<tactic name="measure-everything">
**Instead of:** "This feels faster"
**Do:** Track exact time savings, success rates
**Impact:** Concrete proof of value
</tactic>

<tactic name="make-it-easy">
**Instead of:** "Read the template guide"
**Do:** Meta-prompts that do the work
**Impact:** Zero friction adoption
</tactic>

<tactic name="celebrate-wins">
**Instead of:** Silent improvements
**Do:** Share success stories in team channel
**Impact:** Social proof drives adoption
</tactic>

<tactic name="empower-creators">
**Instead of:** Central template team
**Do:** Anyone can create templates
**Impact:** Bottom-up organic growth
</tactic>

### Overcoming Resistance

<resistance type="time-concern">
<objection>"I don't have time to create templates"</objection>
<response>
"Creating a template takes 2 hours once. Using it saves 28 minutes each time.
Break-even at 5 uses. After 10 uses, you've saved 2.5 hours net.
After 100 uses (1 per week for 2 years), you've saved 44 hours."
</response>
<proof>Show ROI calculation</proof>
</resistance>

<resistance type="not-invented-here">
<objection>"My work is unique, templates won't work"</objection>
<response>
"Let's try it once. Pick your most repetitive task.
I'll help create a template. We'll time the next 3 times you do it.
If it doesn't save time, we stop."
</response>
<proof>Pilot on their specific work</proof>
</resistance>

<resistance type="loss-of-control">
<objection>"I want to control exactly how it's done"</objection>
<response>
"You create the template - it encodes exactly how YOU want it done.
The template ensures YOUR approach is used consistently,
even when you're not available or working on something else."
</response>
<proof>They author the template</proof>
</resistance>

<resistance type="agent-skepticism">
<objection>"Agents make mistakes, I need to review everything"</objection>
<response>
"Templates include comprehensive validation.
Agent runs tests, type-check, lint, build - must pass all.
You review once when creating template, then validation ensures quality.
Think: automated code review built into the process."
</response>
<proof>Show validation suite in action</proof>
</resistance>

<resistance type="learning-curve">
<objection>"I don't know how to write templates"</objection>
<response>
"Start with the template for creating templates (meta!).
Or pair with someone who's created one.
Or just document your process next time - that's 80% of a template."
</response>
<proof>Provide starter kit and examples</proof>
</resistance>

### Success Metrics

<metrics>
<metric name="adoption-rate">
<measurement>Percentage of team using templates regularly</measurement>
<target>90% within 3 months</target>
<tracking>Weekly survey: "Did you use a template this week?"</tracking>
</metric>

<metric name="coverage">
<measurement>Percentage of work types covered by templates</measurement>
<target>80% of common tasks have templates</target>
<tracking>Categorize all work, count templates available</tracking>
</metric>

<metric name="time-savings">
<measurement>Average time saved per template use</measurement>
<target>20+ minutes per use</target>
<tracking>Compare template time vs manual time</tracking>
</metric>

<metric name="success-rate">
<measurement>Percentage of template uses that succeed first time</measurement>
<target>80% one-shot success</target>
<tracking>Log template executions, track validation passes</tracking>
</metric>

<metric name="creation-velocity">
<measurement>New templates created per month</measurement>
<target>5+ new templates per month initially, then stabilizing</target>
<tracking>Count new template files added</tracking>
</metric>

<metric name="quality">
<measurement>Average validation failures per template use</measurement>
<target><1 failure per use</target>
<tracking>Log validation results</tracking>
</metric>
</metrics>

### Scaling Patterns

**Small Team (2-5 engineers):**
- Shared template library in repo
- Weekly sync on new templates
- Informal process
- 10-20 templates sufficient

**Medium Team (5-20 engineers):**
- Dedicated templates repo
- Template review process
- Monthly template retrospective
- Template champions for each domain
- 20-50 templates needed

**Large Team (20+ engineers):**
- Template platform/system
- Formal template governance
- Automated template testing
- Template metrics dashboard
- Template discovery tools
- 50-200+ templates needed

**Multi-Team Organization:**
- Shared core templates
- Team-specific template libraries
- Template sharing mechanism
- Cross-team template working group
- Template certification program

---

## ADVANCED CONCEPTS

### Templates That Reference Templates

<concept>
Templates can include other templates as steps, creating composable workflows.
</concept>

**Example:**
```markdown
# Deploy Full-Stack Feature Template

## Step 1: Backend
Use template: `features/add-crud-endpoint.md`

## Step 2: Frontend
Use template: `features/add-react-component.md`

## Step 3: Integration
Use template: `chores/update-api-client.md`

## Step 4: Testing
Use template: `chores/add-e2e-test.md`

## Step 5: Documentation
Use template: `chores/update-api-docs.md`

## Step 6: Deployment
Use template: `custom/deploy-to-staging.md`
```

### Self-Improving Templates

<concept>
Templates that learn from failures and update themselves.
</concept>

**Implementation:**
```markdown
## Post-Execution Analysis

After each template use:

### 1. Collect Metrics
- Time taken
- Validations passed/failed
- Manual interventions needed
- User satisfaction (1-5)

### 2. Identify Issues
If validation failed or manual intervention needed:
- What went wrong?
- Was it in the template?
- Missing context?
- Unclear instruction?

### 3. Suggest Improvement
Generate PR to template with:
- Issue description
- Proposed fix
- Expected improvement

### 4. Review and Merge
Template maintainer reviews and merges improvement.

### 5. Track Evolution
Version history shows continuous improvement over time.
```

### Template Generation from Examples

<concept>
Meta-meta-prompts that generate templates by analyzing examples.
</concept>

**Process:**
```markdown
# META-META-PROMPT: Generate Template from Examples

## Input
User provides 3-5 examples of similar work they've done.

## Process

### 1. Analyze Examples
Extract:
- Common steps
- Variations
- Decision points
- Files involved
- Commands run

### 2. Identify Pattern
Determine:
- What's always the same?
- What varies?
- What are the inputs?
- What are the outputs?
- How is success measured?

### 3. Generalize
Convert specific examples to general template:
- Specifics → Variables
- Examples → Patterns
- Instances → Classes

### 4. Generate Template
Create complete template following standard structure.

### 5. Validate
Test generated template on new example not in training set.

### 6. Refine
Improve based on test results.

## Output
Production-ready template.
```

### Domain-Specific Template Languages

<concept>
Create DSLs for common template patterns in your domain.
</concept>

**Example: API Endpoint DSL**
```yaml
# api-endpoint.yaml
endpoint:
  resource: User
  operations: [create, read, update, delete, list]
  auth: required
  validation:
    create: schemas/user-create.zod
    update: schemas/user-update.zod
  pagination: true
  rate-limit: 100/min
  soft-delete: true

tests:
  unit: true
  integration: true
  coverage-min: 80

docs:
  openapi: true
  examples: true
```

This DSL expands to full template with all implementation details.

---

## CONCLUSION

<summary>
Template engineering is the cornerstone of scaling agentic coding. By encoding engineering workflows into reusable units, you:

1. **Solve problem classes, not instances**
2. **Scale expertise across team**
3. **Achieve one-shot success rates**
4. **Free engineers for higher-level work**
5. **Compound improvements over time**

The investment in creating templates pays exponential dividends through reuse, consistency, and autonomous execution.
</summary>

<next-steps>
1. Identify your top 3 repetitive tasks
2. Create templates using the process in this guide
3. Test on real work, measure time savings
4. Share with team, iterate based on feedback
5. Build comprehensive template library
6. Achieve 80% work coverage
7. Enable autonomous agentic execution
</next-steps>

<remember>
"Planning alone is expensive. Templates make planning free."

Every template you create is an investment that pays dividends infinitely.
Every problem class you template is a class of problems you never have to manually solve again.
Every team member who adopts templates multiplies your impact.

This is how you become the engineer they can't replace.
</remember>

---

<metadata>
<completion-criteria>
- [ ] Understand what templates are and why they matter
- [ ] Can identify problem classes suitable for templating
- [ ] Can create basic template following structure guide
- [ ] Can create meta-prompt for template
- [ ] Can organize template library
- [ ] Can calculate ROI of template creation
- [ ] Can facilitate team adoption
</completion-criteria>

<related-resources>
- lesson-03-success-is-planned.md
- meta-prompt-architecture.md
- 80-20-fundamentals.md
- lesson-10-prompt-engineering.md
</related-resources>
</metadata>