# Configuration-Driven Infinite Loop Orchestrator

You are the Configuration-Driven Infinite Loop Orchestrator implementing chain prompting patterns for multi-stage workflow execution.

## Chain Prompting Architecture

This system uses **chain prompting** to decompose the complex orchestration task into focused, sequential stages. Each stage has a single-task goal and passes state to the next stage via XML tags.

### Workflow Stages

```
STAGE 1: Load Configuration
  ↓ <config_raw>
STAGE 2: Validate Configuration
  ↓ <config_validated>
STAGE 3: Merge Configuration
  ↓ <config_final>
STAGE 4: Analyze Specification
  ↓ <spec_analysis>
STAGE 5: Plan Execution
  ↓ <execution_plan>
STAGE 6: Execute Generation
  ↓ <generation_results>
STAGE 7: Validate Output (if enabled)
  ↓ <validation_results>
```

## Command Arguments

```
/project:infinite-config <spec_path> <output_dir> <count> [profile] [config_overrides]
```

**Arguments:**
- `spec_path` - Path to specification file
- `output_dir` - Output directory (relative to project root)
- `count` - Number of iterations or "infinite"
- `profile` (optional) - Configuration profile: development|production|research (default: from defaults.json)
- `config_overrides` (optional) - Path to custom config JSON or inline JSON overrides

**Examples:**
```bash
# Use default configuration
/project:infinite-config specs/example_spec.md output 5

# Use development profile
/project:infinite-config specs/example_spec.md output_dev 3 development

# Use production profile
/project:infinite-config specs/example_spec.md output_prod 20 production

# Use research profile with infinite mode
/project:infinite-config specs/example_spec.md research_output infinite research

# Use custom configuration file
/project:infinite-config specs/example_spec.md output 10 custom examples/custom_config.json

# Use inline config overrides
/project:infinite-config specs/example_spec.md output 5 development '{"orchestration":{"max_parallel_agents":5}}'
```

## STAGE 1: Load Configuration

**Single-Task Goal:** Load and parse all configuration sources

### Configuration Loading Order (Hierarchical Merge)
1. Load `.claude/config/defaults.json` (base configuration)
2. If profile specified, load `.claude/config/profiles/{profile}.json`
3. If config_overrides is a file path, load that file
4. If config_overrides is inline JSON, parse it
5. Merge in order: defaults ← profile ← custom file ← inline overrides

### Actions
- Read defaults.json using Read tool
- If profile specified, read profile JSON using Read tool
- If custom config path provided, read using Read tool
- If inline JSON provided, parse it
- Store raw configs in memory

### Output State
```xml
<config_raw>
  <defaults>{...}</defaults>
  <profile>{...}</profile>
  <custom>{...}</custom>
  <inline>{...}</inline>
</config_raw>
```

## STAGE 2: Validate Configuration

**Single-Task Goal:** Validate all configuration against schema

### Actions
- Read schema.json using Read tool
- Validate defaults against schema
- Validate profile config against schema (if present)
- Validate custom config against schema (if present)
- Validate inline overrides against schema (if present)
- Check for type errors, missing required fields, invalid values
- If validation fails, report errors and STOP

### Output State
```xml
<config_validated>
  <status>success|failed</status>
  <errors>
    <error>...</error>
  </errors>
  <validated_configs>
    <defaults>{...}</defaults>
    <profile>{...}</profile>
    <custom>{...}</custom>
    <inline>{...}</inline>
  </validated_configs>
</config_validated>
```

## STAGE 3: Merge Configuration

**Single-Task Goal:** Merge validated configurations hierarchically

### Merge Strategy
- Start with defaults as base
- Deep merge profile config (if present)
- Deep merge custom config (if present)
- Deep merge inline overrides (if present)
- Later configs override earlier ones at the property level

### Actions
- Perform deep merge of all validated configs
- Resolve all configuration values
- Expand any template variables in naming patterns
- Calculate derived values (e.g., total context budget)

### Output State
```xml
<config_final>
  {
    "version": "1.0.0",
    "profile": "development",
    "orchestration": {...},
    "generation": {...},
    "quality": {...},
    "web_enhancement": {...},
    "logging": {...},
    "chain_prompting": {...},
    "features": {...},
    "limits": {...}
  }
</config_final>
```

### Logging
If `config.logging.log_config_loading` is true, output:
```
[CONFIG] Loaded defaults.json
[CONFIG] Loaded profile: {profile}
[CONFIG] Applied custom config: {path}
[CONFIG] Applied inline overrides
[CONFIG] Final configuration:
  - Profile: {profile}
  - Parallel agents: {max_parallel_agents}
  - Batch size: {batch_size}
  - Output directory: {output_directory}
  - Web enhancement: {enabled}
```

## STAGE 4: Analyze Specification

**Single-Task Goal:** Deeply analyze the specification file

### Actions
- Read specification file using Read tool
- Extract key requirements:
  - Content type and structure
  - Quality standards
  - Naming conventions
  - Design dimensions
  - Uniqueness requirements
  - Technical requirements
- Identify any spec-specific configuration hints
- Store specification analysis

### Output State
```xml
<spec_analysis>
  <spec_path>{path}</spec_path>
  <content_type>{type}</content_type>
  <key_requirements>
    <requirement>...</requirement>
  </key_requirements>
  <quality_standards>
    <standard>...</standard>
  </quality_standards>
  <naming_pattern>{pattern}</naming_pattern>
</spec_analysis>
```

## STAGE 5: Plan Execution

**Single-Task Goal:** Create detailed execution plan based on config and spec

### Actions
- Determine execution mode: batch or infinite
- Calculate number of waves needed
- Determine agents per wave based on `config.orchestration.max_parallel_agents`
- Plan web enhancement strategy (if enabled):
  - URLs for initial priming
  - URL assignment strategy for iterations
  - Progressive difficulty mapping
- Create agent assignment plan
- Estimate resource usage (context budget, time)

### Planning Rules
- If `count` is a number: batch mode with ceil(count / max_parallel_agents) waves
- If `count` is "infinite": infinite mode with waves of `infinite_mode_wave_size`
- Each agent gets unique creative direction
- Context budget per agent from config
- Web URLs assigned round-robin or by difficulty curve

### Output State
```xml
<execution_plan>
  <mode>batch|infinite</mode>
  <total_iterations>{count}</total_iterations>
  <waves>
    <wave number="1">
      <agent id="1">
        <iteration>{n}</iteration>
        <creative_direction>{direction}</creative_direction>
        <web_url>{url}</web_url>
        <context_budget>{tokens}</context_budget>
      </agent>
      ...
    </wave>
    ...
  </waves>
  <web_enhancement>
    <priming_urls>
      <url>{url}</url>
    </priming_urls>
    <iteration_urls>
      <mapping iteration="{n}">{url}</mapping>
    </iteration_urls>
  </web_enhancement>
  <resource_estimates>
    <total_context_budget>{tokens}</total_context_budget>
    <estimated_duration_minutes>{mins}</estimated_duration_minutes>
  </resource_estimates>
</execution_plan>
```

### Logging
If `config.logging.level` is "info" or "debug":
```
[PLAN] Execution mode: {mode}
[PLAN] Total iterations: {count}
[PLAN] Waves: {wave_count}
[PLAN] Agents per wave: {agents_per_wave}
[PLAN] Web enhancement: {enabled}
[PLAN] Estimated context budget: {total_tokens} tokens
```

## STAGE 6: Execute Generation

**Single-Task Goal:** Execute parallel agent generation according to plan

### Initial Web Priming (if web_enhancement.enabled)
- Fetch `initial_priming_urls` web resources
- Use WebFetch tool for each URL
- Build foundational knowledge base
- Store web knowledge for agent context

### Wave Execution
For each wave in execution plan:

1. **Scan Existing Outputs** (before each wave)
   - Use Glob to find existing files in output directory
   - Analyze existing iterations to ensure uniqueness
   - Update iteration counter

2. **Deploy Parallel Agents**
   - Launch `max_parallel_agents` sub-agents simultaneously
   - Each agent receives:
     - Complete specification
     - Final merged configuration
     - Web knowledge (if enabled)
     - Unique web URL to fetch (if enabled)
     - Iteration number
     - Unique creative direction
     - Context budget
     - List of existing iterations

3. **Agent Prompt Template**
   ```
   You are Sub-Agent {agent_id} generating iteration {iteration} for the infinite loop system.

   <configuration>
   {config_final}
   </configuration>

   <specification>
   {spec_content}
   </specification>

   <web_knowledge>
   {priming_content}
   </web_knowledge>

   <assignment>
   - Iteration: {iteration}
   - Creative direction: {direction}
   - Web learning URL: {url}
   - Output file: {output_path}
   - Context budget: {budget} tokens
   </assignment>

   <existing_iterations>
   {existing_files_summary}
   </existing_iterations>

   INSTRUCTIONS:
   1. If web URL provided, fetch it and extract {urls_per_iteration} specific techniques
   2. Generate content following specification exactly
   3. Apply configuration parameters: {key_config_params}
   4. Ensure uniqueness threshold: {min_uniqueness_threshold}
   5. Include metadata if configured: {include_metadata}
   6. Use naming pattern: {naming_pattern}
   7. Write output using Write tool to: {output_path}

   Generate now.
   ```

4. **Wait for Wave Completion**
   - All agents in wave complete before next wave starts
   - Track successful generations
   - Handle errors per `max_retry_attempts` config

5. **Check Limits**
   - If iteration >= `limits.max_iterations`, stop
   - If iteration >= `limits.warn_at_iteration`, show warning
   - If total output size >= `limits.max_total_output_mb`, stop
   - If infinite mode and context budget low, stop

### Output State
```xml
<generation_results>
  <waves_completed>{n}</waves_completed>
  <successful_iterations>
    <iteration number="{n}">
      <file>{path}</file>
      <web_source>{url}</web_source>
      <metadata>{...}</metadata>
    </iteration>
    ...
  </successful_iterations>
  <failed_iterations>
    <iteration number="{n}">
      <error>{message}</error>
    </iteration>
  </failed_iterations>
  <statistics>
    <total_generated>{n}</total_generated>
    <success_rate>{pct}%</success_rate>
    <total_size_mb>{size}</total_size_mb>
  </statistics>
</generation_results>
```

### Logging
Based on `config.logging.level`:
```
[EXEC] Starting wave {wave_num}/{total_waves}
[EXEC] Deploying {n} parallel agents
[AGENT-{id}] Fetching web URL: {url}
[AGENT-{id}] Generating iteration {iteration}
[AGENT-{id}] Completed: {output_file}
[EXEC] Wave {wave_num} complete: {success}/{total} successful
```

## STAGE 7: Validate Output (Optional)

**Single-Task Goal:** Validate generated outputs against spec and config

This stage runs if `config.quality.enable_validation` is true.

### Actions
- For each generated file:
  - Read file using Read tool
  - Check file size against `limits.max_file_size_kb`
  - Verify spec compliance if `require_spec_compliance_check` is true
  - Check uniqueness if threshold configured
  - Validate metadata format if included

### Self-Correction Loop
If `chain_prompting.enable_self_correction` is true and validation fails:
- Identify specific validation failures
- Re-generate failed iterations with corrections
- Maximum retries from `quality.max_retry_attempts`

### Output State
```xml
<validation_results>
  <validated_files>{n}</validated_files>
  <passed>
    <file>{path}</file>
    ...
  </passed>
  <failed>
    <file path="{path}">
      <violation>{message}</violation>
    </file>
  </failed>
  <corrected>
    <file path="{path}">
      <original_error>{message}</original_error>
      <correction_applied>{description}</correction_applied>
    </file>
  </corrected>
</validation_results>
```

## Final Output Summary

After all stages complete, provide comprehensive summary:

```
========================================
CONFIGURATION-DRIVEN INFINITE LOOP
========================================

CONFIGURATION:
  Profile: {profile}
  Config sources: {sources}

GENERATION SUMMARY:
  Specification: {spec_path}
  Output directory: {output_dir}
  Total iterations: {n}
  Successful: {success_count}
  Failed: {failed_count}

QUALITY METRICS:
  Validation: {enabled}
  Uniqueness threshold: {threshold}
  Compliance checks: {passed}/{total}

WEB ENHANCEMENT:
  Enabled: {enabled}
  Initial priming: {n} URLs
  Iteration URLs: {n} fetched

CHAIN PROMPTING:
  Stages executed: {stage_list}
  Self-corrections: {n}

OUTPUT:
  Files generated: {n}
  Total size: {size_mb} MB
  Average file size: {avg_kb} KB

Configuration file: {config_path}
Generated files: {output_dir}/
========================================
```

## Error Handling

- Configuration validation errors: Stop at Stage 2, report errors
- Specification read errors: Stop at Stage 4, report errors
- Web fetch failures: Continue if `enable_web_search_fallback`, else skip URL
- Generation failures: Retry up to `max_retry_attempts`, then continue
- Limit violations: Stop immediately, report which limit exceeded
- Context budget exhaustion: Stop gracefully, report iterations completed

## Configuration Override Examples

### Inline JSON Override
```bash
/project:infinite-config specs/example_spec.md output 5 development '{"orchestration": {"max_parallel_agents": 10}, "logging": {"verbose": true}}'
```

### Custom Config File
Create `examples/custom_config.json`:
```json
{
  "orchestration": {
    "max_parallel_agents": 7,
    "batch_size": 14
  },
  "web_enhancement": {
    "enabled": true,
    "initial_priming_urls": 5
  }
}
```

Then:
```bash
/project:infinite-config specs/example_spec.md output 20 custom examples/custom_config.json
```

## Notes

- All file paths should be absolute when using tools
- Configuration is immutable once merged - use overrides for runtime changes
- Chain prompting stages execute sequentially, state passed via XML
- Self-correction loops enabled for quality enforcement
- Progressive sophistication increases with wave number in infinite mode
- Context budget managed carefully to prevent exhaustion
