# CLAUDE.md - Infinite Loop Variant 3: Pluggable Agent Task Templates

This file provides guidance to Claude Code when working with the pluggable agent task template system.

## Project Overview

This is an advanced infinite loop variant that uses **pluggable agent task templates** - reusable, parameterized blueprints for agent behavior. The system loads templates, substitutes parameters, and deploys parallel agents with complete, unambiguous instructions.

### Core Innovation

Instead of hardcoding agent instructions in orchestrator commands, this system:
1. Stores reusable task templates in `.claude/templates/`
2. Uses parameter substitution (`{{PARAMETER}}` syntax)
3. Instantiates templates with specific values per iteration
4. Deploys agents with fully formed, explicit instructions
5. Follows Anthropic's "be clear and direct" prompt engineering principles

## Key Commands

### Running the Infinite Templated Loop

```bash
# Web-enhanced generation (5 iterations)
/infinite-templated web-research-generator specs/example_spec.md viz_output 5

# Pure code generation (10 iterations)
/infinite-templated code-generator specs/example_spec.md viz_output 10

# Infinite mode (continuous waves)
/infinite-templated web-research-generator specs/example_spec.md viz_output infinite params/url_strategy.json

# Analysis of existing artifacts
/infinite-templated analyzer specs/analysis_criteria.md reports/analysis.md 1 params/analysis_params.json

# Validation of artifacts
/infinite-templated validator specs/validation_rules.md reports/validation.md 1
```

### Creating New Templates

```bash
# Interactive template creation
/create-template my-template-name generation "What this template does"

# Example: Create API testing template
/create-template api-tester testing "Tests REST APIs and generates test reports"
```

## How to Work with Templates

### Reading Templates

Templates are in `.claude/templates/` directory. When examining a template:

1. **Understand the structure**: Templates have 11 required sections
2. **Identify parameters**: Look for `{{PARAMETER}}` placeholders
3. **Review execution steps**: 3-7 numbered steps define agent behavior
4. **Check parameter table**: All parameters documented with types and examples

### Creating Templates

Follow this process (or use `/create-template`):

1. **Start with base-template.md**: Copy structure
2. **Define agent role**: What expertise and responsibilities?
3. **Write execution steps**: 3-7 clear, sequential steps
4. **Document parameters**: Create reference table
5. **Provide example**: Show concrete usage
6. **Add validation**: Checklist for agents
7. **Follow spec**: See `specs/template_spec.md`

### Modifying Templates

When updating existing templates:

1. **Read current version**: Understand existing structure
2. **Maintain sections**: Don't remove required sections
3. **Update parameters**: Keep parameter table in sync
4. **Test substitution**: Ensure no unintended placeholders
5. **Update version**: Increment version number
6. **Update examples**: Keep examples current

## Template System Architecture

### Directory Structure

```
.claude/
├── commands/
│   ├── infinite-templated.md   # Orchestrator - loads and instantiates templates
│   └── create-template.md      # Template creation utility
├── templates/
│   ├── base-template.md        # Template for making templates
│   ├── web-research-generator.md
│   ├── code-generator.md
│   ├── analyzer.md
│   └── validator.md
└── settings.json

specs/
├── example_spec.md             # Example visualization spec
└── template_spec.md            # Requirements for creating templates

docs/
└── template_guide.md           # Template creation guide

examples/
└── template_usage.md           # Concrete usage examples
```

### Orchestrator Workflow

The `/infinite-templated` command:

1. **Phase 1: Template Loading**
   - Reads template from `.claude/templates/{{name}}.md`
   - Parses structure and parameters
   - Validates template completeness

2. **Phase 2: Context Preparation**
   - Loads specification file
   - Analyzes existing iterations
   - Prepares URL strategy (for web templates)

3. **Phase 3: Task Instantiation**
   - For each iteration:
     - Creates parameter mapping
     - Substitutes all `{{PARAMETER}}` placeholders
     - Verifies uniqueness
     - Results in complete agent task

4. **Phase 4: Parallel Deployment**
   - Launches agents with instantiated tasks
   - Agents work independently
   - Collects results

5. **Phase 5: Wave Management** (infinite mode)
   - Analyzes wave completion
   - Prepares next batch
   - Continues until context limits

6. **Phase 6: Summary**
   - Reports results
   - Quality checks
   - Lists generated files

### Parameter Substitution Mechanism

Templates use `{{PARAMETER}}` syntax:

```markdown
**Template:**
Read file: `{{SPEC_FILE}}`
Generate output in: `{{OUTPUT_DIR}}/{{FILE_NAME}}`
Learn from: `{{WEB_URL}}`
```

**Orchestrator creates mapping:**
```json
{
  "SPEC_FILE": "specs/example_spec.md",
  "OUTPUT_DIR": "viz_output",
  "FILE_NAME": "viz_network_001.html",
  "WEB_URL": "https://d3js.org/d3-force"
}
```

**Instantiated task:**
```markdown
Read file: `specs/example_spec.md`
Generate output in: `viz_output/viz_network_001.html`
Learn from: `https://d3js.org/d3-force`
```

## Available Templates

### 1. web-research-generator

**Purpose:** Fetch web resources, extract techniques, generate artifacts with applied learning

**Key Features:**
- WebFetch or WebSearch integration
- Technique extraction and documentation
- Progressive learning support
- Web source attribution

**Use When:**
- Learning from documentation
- Implementing from tutorials
- Applying best practices from web
- Progressive skill building

**Parameters:**
- `WEB_URL`: URL to fetch
- `LEARNING_FOCUS`: What to extract
- `MIN_TECHNIQUES`: Minimum techniques to apply
- `OUTPUT_DIR`, `SPEC_FILE`, `FILE_NAME`, etc.

### 2. code-generator

**Purpose:** Generate code artifacts from specifications without web dependencies

**Key Features:**
- Theme-based variation
- Uniqueness assurance
- Creative interpretation
- Specification compliance

**Use When:**
- Creating variations of components
- Exploring creative themes
- Generating diverse implementations
- No external learning needed

**Parameters:**
- `THEME`: Unique theme for iteration
- `UNIQUE_FEATURES`: Distinguishing characteristics
- `OUTPUT_DIR`, `SPEC_FILE`, `FILE_NAME`, etc.

### 3. analyzer

**Purpose:** Analyze artifacts to extract patterns, metrics, and insights

**Key Features:**
- Systematic analysis
- Pattern detection
- Metrics collection
- Comprehensive reporting

**Use When:**
- Assessing quality across iterations
- Identifying patterns or trends
- Collecting metrics
- Generating analysis reports

**Parameters:**
- `TARGET_PATTERN`: Files to analyze
- `CRITERIA_FILE`: Analysis criteria
- `METRICS`: Metrics to collect
- `OUTPUT_FILE`: Report destination

### 4. validator

**Purpose:** Validate artifacts against requirements and standards

**Key Features:**
- Specification compliance checking
- Evidence-based pass/fail
- Remediation guidance
- Detailed reporting

**Use When:**
- Checking spec compliance
- Pre-deployment validation
- Quality assurance
- Standard adherence verification

**Parameters:**
- `VALIDATION_SPEC`: Validation rules
- `TARGET_PATTERN`: Files to validate
- `CRITERIA_LIST`: Specific criteria
- `OUTPUT_FILE`: Report destination

## Template Design Principles

Templates in this system follow Anthropic's "Be Clear and Direct" prompt engineering guidance:

### 1. Contextual Clarity

Templates provide complete context:
- **Task purpose**: Why is this task being performed?
- **Workflow position**: Where does it fit in larger process?
- **Success criteria**: What defines success?
- **Constraints**: What must the agent avoid or respect?

### 2. Explicit Instructions

Every template uses:
- **Numbered steps**: Sequential, ordered execution
- **Step names**: Clear description of what step does
- **Detailed instructions**: Exact actions to take
- **Expected outputs**: What each step should produce

### 3. "New Employee" Approach

Templates treat agents as capable but uninformed:
- Explain norms and styles
- Don't assume prior knowledge
- Provide examples
- Define all terms

### 4. Precision and Clarity

Templates are:
- Unambiguous (one interpretation)
- Specific (exact requirements)
- Complete (no missing information)
- Testable (verifiable success)

## Working with Specifications

Specifications define WHAT to generate; templates define HOW to generate it.

### Specification Requirements

Good specs for template system:
- Clear file naming patterns with placeholders
- Explicit structure requirements
- Quality standards defined
- Success criteria measurable
- Template parameter mappings provided

### Spec-Template Relationship

```
Specification (example_spec.md)
    ↓
Defines: naming, structure, quality standards
    ↓
Template (web-research-generator.md)
    ↓
Defines: process, steps, agent behavior
    ↓
Orchestrator
    ↓
Combines spec + template + parameters
    ↓
Instantiated Agent Task
    ↓
Generated Artifact
```

## Parameter Files

Optional JSON files provide additional parameters:

### Structure

```json
{
  "PROJECT_NAME": "Project name here",
  "PROJECT_DESCRIPTION": "Description",
  "MIN_TECHNIQUES": 3,
  "URL_STRATEGY": {
    "foundation": ["url1", "url2"],
    "intermediate": ["url3"],
    "advanced": ["url4", "url5"]
  },
  "CUSTOM_PARAMETER": "value"
}
```

### Usage

```bash
/infinite-templated template_name spec.md output_dir count params.json
```

Parameters from file merged with auto-generated parameters.

### URL Strategy (for web-research-generator)

Progressive learning approach:

```json
{
  "URL_STRATEGY": {
    "foundation": [
      "https://example.com/getting-started",
      "https://example.com/basics"
    ],
    "intermediate": [
      "https://example.com/advanced-guide",
      "https://example.com/api-docs"
    ],
    "advanced": [
      "https://example.com/expert-techniques",
      "https://example.com/optimization"
    ]
  }
}
```

Orchestrator assigns URLs based on iteration sophistication.

## Best Practices

### When Creating Templates

1. **Start simple**: 3 steps, add complexity as needed
2. **Be specific**: "Generate HTML file" > "create output"
3. **Show examples**: Concrete examples clarify instructions
4. **Test mentally**: Walk through as if you're the agent
5. **Document everything**: All parameters in reference table
6. **Follow spec**: Use `specs/template_spec.md` as guide

### When Using Templates

1. **Choose right template**: Match template to task type
2. **Provide parameters**: Required parameters must be provided
3. **Use parameter files**: Complex configs in JSON files
4. **Check existing iterations**: Avoid duplication
5. **Review outputs**: Spot-check for quality

### When Modifying System

1. **Read existing code**: Understand current patterns
2. **Maintain compatibility**: Don't break existing templates
3. **Update documentation**: Keep docs in sync
4. **Test thoroughly**: Verify templates still work
5. **Follow conventions**: Parameter naming, file structure, etc.

## Common Patterns

### Creating Visualization Series

```bash
# Generate 20 visualizations with web learning
/infinite-templated web-research-generator specs/viz_spec.md viz_output 20 params/d3_urls.json
```

### Quality Assurance Pipeline

```bash
# 1. Generate artifacts
/infinite-templated code-generator specs/component_spec.md components 10

# 2. Analyze quality
/infinite-templated analyzer specs/analysis_criteria.md reports/analysis.md 1

# 3. Validate compliance
/infinite-templated validator specs/validation_rules.md reports/validation.md 1
```

### Progressive Learning Campaign

```bash
# Infinite mode with progressive URL difficulty
/infinite-templated web-research-generator specs/learning_spec.md output infinite params/progressive_urls.json
```

## Troubleshooting

### Template Not Found

**Error:** "Template {{name}} not found"

**Solution:**
- Check `.claude/templates/` directory
- Verify file name matches (kebab-case)
- List available templates

### Missing Parameters

**Error:** "Required parameter {{PARAM}} not provided"

**Solution:**
- Check parameter reference table in template
- Provide via parameter file
- Check if parameter should be auto-generated

### Instantiation Failure

**Error:** "Failed to substitute parameters"

**Solution:**
- Verify parameter file is valid JSON
- Check for circular parameter references
- Ensure all required parameters provided

### Agent Execution Failure

**Error:** Agent fails during execution

**Solution:**
- Review agent's instantiated task
- Check if instructions are ambiguous
- Verify all required files/resources exist
- Update template to be more explicit

## File Naming Conventions

- **Templates**: `kebab-case.md` (e.g., `web-research-generator.md`)
- **Commands**: `kebab-case.md` (e.g., `infinite-templated.md`)
- **Specs**: `snake_case.md` (e.g., `example_spec.md`)
- **Parameters**: `UPPER_SNAKE_CASE` (e.g., `WEB_URL`, `OUTPUT_DIR`)

## Development Workflow

### Adding New Template Type

1. Design template following `specs/template_spec.md`
2. Create template file in `.claude/templates/`
3. Test with `/infinite-templated`
4. Document in `docs/template_guide.md`
5. Add example to `examples/template_usage.md`
6. Update README.md available templates section

### Extending Orchestrator

1. Read `.claude/commands/infinite-templated.md`
2. Understand 6-phase workflow
3. Identify extension point
4. Implement changes
5. Test with existing templates
6. Update documentation

### Creating Domain-Specific System

1. Clone this variant as starting point
2. Create domain-specific templates
3. Create domain-specific specs
4. Customize parameter files
5. Test workflow end-to-end
6. Document domain-specific usage

## Key Differences from Other Variants

### vs. Original Infinite Loop
- **Original**: Agent instructions hardcoded in orchestrator
- **This**: Agent instructions in reusable templates

### vs. Web-Enhanced Loop
- **Web-Enhanced**: Web learning built into orchestrator
- **This**: Web learning as one template option among many

### vs. Pipeline Variant
- **Pipeline**: Sequential stages with fixed workflow
- **This**: Parallel agents with pluggable task templates

### Unique Value Proposition

**Maximum flexibility through template pluggability while maintaining maximum clarity through structured, explicit instructions based on prompt engineering best practices.**

## Resources

- **Anthropic Documentation**: https://docs.claude.com/en/docs/build-with-claude/prompt-engineering/be-clear-and-direct
- **Template Spec**: `specs/template_spec.md`
- **Template Guide**: `docs/template_guide.md`
- **Usage Examples**: `examples/template_usage.md`
- **Base Template**: `.claude/templates/base-template.md`

## Quick Reference

### Command Syntax
```bash
/infinite-templated <template> <spec> <output_dir> <count> [params]
/create-template <name> <category> <description>
```

### Template Sections (Required)
1. Metadata header
2. Template overview
3. Agent role definition
4. Task context
5. Execution instructions (3-7 steps)
6. Output specifications
7. Template parameters reference
8. Example usage
9. Validation checklist
10. Notes and best practices
11. Footer

### Parameter Syntax
- In templates: `{{PARAMETER}}`
- Naming: `UPPER_SNAKE_CASE`
- Types: string, number, path, url, list, object, glob

### Template Categories
- generation
- analysis
- quality-assurance
- research
- testing
- documentation

---

**Remember**: Templates are contracts. Write them as if instructing a brilliant but completely uninformed colleague. Be explicit, provide context, show examples, and define success clearly.
