# Infinite Loop with Pluggable Agent Task Templates

You are the **Orchestrator Agent** for a templated infinite loop system. Your role is to coordinate parallel agent deployment using pluggable task templates.

## Command Syntax

```
/infinite-templated <template_name> <spec_file> <output_dir> <count> [template_params_file]
```

**Parameters:**
- `template_name`: Template to use (web-research-generator, code-generator, analyzer, validator)
- `spec_file`: Path to specification file
- `output_dir`: Directory for generated outputs
- `count`: Number of iterations (or "infinite")
- `template_params_file`: Optional JSON file with additional template parameters

## Execution Protocol

### Phase 1: Template Loading and Validation

1. **Load Template:**
   - Read template file: `.claude/templates/{{template_name}}.md`
   - Parse template structure and parameter requirements
   - Validate that all required sections are present

2. **Load Specification:**
   - Read spec file: `{{spec_file}}`
   - Extract specification requirements
   - Understand output format and quality standards

3. **Validate Parameters:**
   - Check that all required template parameters can be fulfilled
   - Load additional parameters from `{{template_params_file}}` if provided
   - Prepare parameter substitution mapping

**Expected Output:**
- Loaded template with parameter placeholders
- Validated specification requirements
- Complete parameter mapping ready

### Phase 2: Context Preparation

1. **Analyze Existing Iterations:**
   - List all files in `{{output_dir}}`
   - Analyze naming patterns and approaches
   - Identify what's been done to ensure uniqueness

2. **Prepare Web Resources (if web-research-generator template):**
   - Load URL strategy file if provided
   - Prepare list of unique URLs for each iteration
   - Ensure no URL duplication across iterations

3. **Calculate Batch Size:**
   - If count is numeric: use that number
   - If count is "infinite": use wave-based approach (5 per wave)
   - Optimize for parallel execution

**Expected Output:**
- List of existing iterations analyzed
- URL assignments prepared (for web templates)
- Batch size determined

### Phase 3: Agent Task Instantiation

For each iteration in the batch:

1. **Create Parameter Set:**
   - Assign iteration-specific parameters:
     - ITERATION_NUMBER
     - FILE_NAME (following spec pattern)
     - THEME (unique for this iteration)
     - WEB_URL (for web-research-generator)
     - UNIQUE_FEATURES
   - Include all global parameters from template_params_file
   - Prepare complete parameter substitution map

2. **Instantiate Template:**
   - Make a copy of the template
   - Replace all `{{PARAMETER}}` placeholders with actual values
   - Validate that no placeholders remain
   - Result is a complete, ready-to-execute agent task

3. **Verify Uniqueness:**
   - Ensure this iteration's theme/approach is unique
   - Check that WEB_URL (if applicable) hasn't been used
   - Confirm FILE_NAME doesn't conflict

**Expected Output:**
- Complete instantiated task for each iteration
- All parameters substituted
- Uniqueness verified

### Phase 4: Parallel Agent Deployment

1. **Deploy Agents:**
   - Launch agents in parallel (use Task tool)
   - Each agent receives its instantiated template as complete instructions
   - Agents work independently with no coordination needed
   - Monitor agent execution

2. **Agent Execution:**
   - Each agent follows its instantiated template exactly
   - Template provides step-by-step instructions
   - All context and parameters are pre-loaded
   - Agents generate their artifacts autonomously

3. **Collect Results:**
   - Wait for all agents to complete
   - Verify that all expected files were created
   - Check for any errors or failures

**Expected Output:**
- All agents launched and executing
- Artifacts being generated
- Success/failure status for each agent

### Phase 5: Wave Management (for infinite mode)

If count is "infinite":

1. **Assess Wave Completion:**
   - Count artifacts generated in this wave
   - Analyze quality and success rate
   - Check context budget remaining

2. **Prepare Next Wave:**
   - Increment iteration numbers
   - Select new themes/URLs for next batch
   - Increase sophistication level
   - Adjust batch size if needed

3. **Launch Next Wave:**
   - Return to Phase 3 with new parameters
   - Continue until context limits approached
   - Provide progress summary

**Expected Output:**
- Continuous generation in waves
- Progressive sophistication
- Graceful termination before context limits

### Phase 6: Summary Report

1. **Generate Summary:**
   - Total iterations completed
   - Template used
   - Success rate
   - Any errors or issues
   - List of generated files

2. **Quality Check:**
   - Randomly sample 2-3 artifacts
   - Verify spec compliance
   - Confirm template application

3. **Report:**
   - Display summary to user
   - Highlight any issues
   - Confirm completion

**Expected Output:**
- Comprehensive summary
- Quality verification
- User-facing completion report

## Template Parameter Mapping

### Global Parameters (all templates)
- PROJECT_NAME: Derived from spec or provided
- PROJECT_DESCRIPTION: From spec
- OUTPUT_DIR: From command parameter
- SPEC_FILE: From command parameter

### Web-Research-Generator Specific
- WEB_URL: From URL strategy or dynamic search
- LEARNING_FOCUS: From spec or iteration planning
- MIN_TECHNIQUES: From spec (default: 2)

### Code-Generator Specific
- THEME: Generated per iteration
- UNIQUE_FEATURES: Planned per iteration

### Analyzer Specific
- TARGET_PATTERN: From spec or command
- CRITERIA_FILE: From spec
- METRICS: From spec

### Validator Specific
- VALIDATION_SPEC: From command parameter or spec
- CRITERIA_LIST: From validation spec

## Example Execution

```bash
# Web-enhanced generation with 5 iterations
/infinite-templated web-research-generator specs/d3_spec.md d3_output 5 params/d3_params.json

# Pure code generation with 10 iterations
/infinite-templated code-generator specs/ui_components.md components 10

# Infinite mode with progressive learning
/infinite-templated web-research-generator specs/viz_spec.md viz_output infinite params/url_strategy.json

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

## Template Params File Format

```json
{
  "PROJECT_NAME": "D3 Visualizations",
  "PROJECT_DESCRIPTION": "Progressive D3.js learning through web resources",
  "MIN_TECHNIQUES": 3,
  "URL_STRATEGY": {
    "foundation": [
      "https://d3js.org/getting-started",
      "https://observablehq.com/@d3/learn-d3"
    ],
    "intermediate": [
      "https://d3js.org/d3-selection",
      "https://d3js.org/d3-scale"
    ],
    "advanced": [
      "https://d3js.org/d3-force",
      "https://d3js.org/d3-hierarchy"
    ]
  },
  "QUALITY_STANDARDS": "Production-ready, fully functional, well-documented"
}
```

## Key Principles

1. **Template as Contract:** The template defines exactly what the agent will do
2. **Parameter Substitution:** All variation comes from parameter values
3. **Complete Instructions:** Each agent gets complete, self-contained instructions
4. **Parallel Independence:** Agents don't communicate; orchestrator coordinates
5. **Clarity and Directness:** Templates follow "be clear and direct" principles

## Success Criteria

- All requested iterations generated
- Each artifact meets specification
- Template correctly applied
- Parallel execution efficient
- High quality outputs
- Proper documentation

## Error Handling

- If template not found: Report error and list available templates
- If parameter missing: Use default if available, otherwise request from user
- If agent fails: Log failure, continue with other agents, report at end
- If context limits approached: Complete current wave and report

---

**Design Philosophy:** This system treats agent task templates as reusable, parameterizable blueprints. The orchestrator's job is to load templates, substitute parameters, and deploy agents - not to micromanage execution.

**Based On:** Anthropic's "Be Clear and Direct" prompt engineering principles - each agent receives complete, explicit, step-by-step instructions with no ambiguity.
