# Infinite Loop with Cross-Iteration Pattern Synthesis

Generate iterations using cumulative pattern learning from successful examples.

## Usage

```bash
/project:infinite-synthesis <spec_file> <output_dir> <count|infinite> [pattern_library_path]
```

## Arguments

1. `spec_file` - Path to specification file defining what to generate
2. `output_dir` - Directory for generated output files
3. `count` - Number of iterations (or "infinite" for continuous generation)
4. `pattern_library_path` - Optional: Path to existing pattern library JSON (default: `pattern_library/patterns.json`)

## Examples

```bash
# Generate 5 iterations with pattern synthesis
/project:infinite-synthesis specs/example_spec.md output 5

# Continuous generation with pattern accumulation
/project:infinite-synthesis specs/example_spec.md output infinite

# Use custom pattern library
/project:infinite-synthesis specs/example_spec.md output 10 pattern_library/custom_patterns.json
```

## How It Works

This command enhances the infinite loop with **cross-iteration pattern synthesis** - a technique inspired by multi-shot prompting that enables cumulative learning:

### Pattern Synthesis Workflow

1. **Wave 1 (Cold Start)**: Generate initial iterations without patterns
2. **Pattern Extraction**: Analyze all iterations to extract successful patterns
3. **Pattern Library Update**: Add new patterns to growing library (3-5 best examples)
4. **Wave 2+ (Pattern-Guided)**: Generate new iterations using pattern library as examples
5. **Continuous Improvement**: Each wave refines and expands the pattern library

### Multi-Shot Prompting Integration

Based on [Claude's multi-shot prompting documentation](https://docs.claude.com/en/docs/build-with-claude/prompt-engineering/multishot-prompting), this system applies:

- **Example-Based Learning**: Pattern library serves as concrete examples (3-5 per pattern type)
- **Consistency Enforcement**: Examples demonstrate uniform structure and style
- **Edge Case Coverage**: Diverse patterns prevent misinterpretation
- **Progressive Refinement**: Library grows with each wave, improving subsequent outputs

### Pattern Library Structure

Patterns are extracted across multiple dimensions:
- **Structural Patterns**: File organization, naming conventions, architecture
- **Content Patterns**: Writing style, documentation approach, code structure
- **Innovation Patterns**: Creative techniques, unique approaches, problem-solving
- **Quality Patterns**: Testing strategies, validation methods, best practices

## Implementation

You are the orchestrator agent. Follow these steps:

### Phase 1: Setup and Context Loading

```bash
# Read the specification file
Read spec_file

# Check output directory for existing iterations
Bash: ls -la output_dir (if exists)

# Load or initialize pattern library
Read pattern_library_path (if exists) or initialize empty
```

### Phase 2: Calculate Wave Parameters

```python
if count == "infinite":
    wave_size = 5  # Generate 5 iterations per wave
    total_waves = "until context limit"
else:
    count_int = int(count)
    if count_int <= 5:
        waves = 1
        wave_size = count_int
    elif count_int <= 15:
        waves = 2
        wave_size = count_int // 2
    else:
        waves = count_int // 5
        wave_size = 5
```

### Phase 3: Wave 1 - Cold Start Generation

For the first wave, generate iterations without pattern library:

```markdown
For each iteration in wave 1:
  1. Analyze spec requirements
  2. Review existing iterations (if any) for uniqueness
  3. Generate unique output following spec
  4. Save to output_dir
```

After wave 1 completes, proceed to pattern extraction.

### Phase 4: Pattern Extraction

Use `/project:extract-patterns` command:

```bash
/project:extract-patterns output_dir pattern_library_path
```

This analyzes all iterations and extracts:
- 3-5 exemplary structural patterns
- 3-5 content quality patterns
- 3-5 innovation patterns
- 3-5 edge case handling patterns

The pattern library is saved as JSON with this structure:

```json
{
  "version": "1.0",
  "last_updated": "2025-10-10T12:00:00Z",
  "total_iterations_analyzed": 5,
  "patterns": {
    "structural": [
      {
        "name": "Pattern name",
        "description": "What this pattern achieves",
        "example_file": "path/to/example",
        "key_characteristics": ["trait1", "trait2"],
        "success_metrics": "Why this worked well"
      }
    ],
    "content": [...],
    "innovation": [...],
    "quality": [...]
  }
}
```

### Phase 5: Wave 2+ - Pattern-Guided Generation

For subsequent waves, include pattern library in agent context:

```markdown
For each iteration in wave N (N > 1):
  1. Load pattern library
  2. Review 3-5 example patterns relevant to current task
  3. Analyze spec requirements WITH pattern context
  4. Review existing iterations for uniqueness
  5. Generate output that:
     - Follows spec requirements
     - Incorporates successful patterns from library
     - Adds novel innovation beyond existing patterns
     - Maintains consistency with established quality bar
  6. Save to output_dir
```

### Phase 6: Continuous Pattern Refinement

After each wave (except the last):

```markdown
1. Run pattern extraction on ALL iterations (old + new)
2. Update pattern library:
   - Keep 3-5 best examples per category (prevent bloat)
   - Add new pattern types discovered
   - Remove patterns that are no longer exemplary
   - Update success metrics based on new data
3. Increment version number
4. Log changes for transparency
```

### Phase 7: Wave Completion and Loop

```markdown
After each wave:
  1. Report wave statistics:
     - Iterations generated
     - Patterns extracted/updated
     - Pattern library version
     - Unique innovations discovered

  2. For infinite mode:
     - Check context usage (stop if > 80% of budget)
     - If capacity remains, start next wave

  3. For counted mode:
     - If more waves remain, start next wave
     - Otherwise, generate final report
```

## Agent Coordination

### Sub-Agent Creation

Each iteration is generated by a dedicated sub-agent using the Task tool:

```xml
<task>
Create iteration {N} following spec: {spec_file}

PATTERN LIBRARY CONTEXT:
{Include 3-5 most relevant patterns from library}

REQUIREMENTS:
1. Read specification: {spec_file}
2. Review existing iterations: {list_of_existing_files}
3. Study pattern examples above
4. Generate unique output that:
   - Fully complies with spec
   - Incorporates proven patterns
   - Adds novel innovation
   - Maintains quality standards

OUTPUT:
Save to: {output_dir}/iteration_{N}.{extension}

VALIDATION:
Ensure output is genuinely unique and demonstrates pattern learning.
</task>
```

### Parallel Execution

Execute sub-agents in parallel (wave_size at a time):

```markdown
Wave of 5 iterations:
- Create 5 Task sub-agents simultaneously
- Each receives same pattern library but different iteration number
- Each must generate unique output
- Wait for all 5 to complete before pattern extraction
```

## Pattern Quality Standards

Extracted patterns must meet these criteria:

1. **Exemplary Quality**: Top 20% of iterations in their category
2. **Demonstrable Success**: Clear metrics showing why pattern works
3. **Transferable**: Applicable to future iterations
4. **Diverse**: Cover different approaches, not just variations
5. **Documented**: Include context about what makes it successful

## Success Metrics

Track these metrics across waves:

- **Pattern Adoption Rate**: % of iterations using library patterns
- **Innovation Rate**: New patterns discovered per wave
- **Quality Consistency**: Variance in output quality over time
- **Pattern Effectiveness**: Success rate of pattern-guided vs pattern-free iterations

## Output Report

At the end of execution, generate comprehensive report:

```markdown
# Pattern Synthesis Report

## Execution Summary
- Total iterations: {count}
- Waves completed: {wave_count}
- Final pattern library version: {version}

## Pattern Library Evolution
- Initial patterns: {count_wave_1}
- Final patterns: {count_final}
- Pattern categories discovered: {categories}

## Quality Metrics
- Average quality score: {score}
- Consistency improvement: {percent}
- Innovation diversity: {metric}

## Top Patterns
{List 5 most successful patterns with examples}

## Iteration Highlights
{Showcase 3-5 exceptional iterations}

## Pattern Library Location
{path_to_pattern_library}
```

## Error Handling

```markdown
If pattern extraction fails:
- Log warning
- Continue with existing pattern library
- Retry extraction after next wave

If sub-agent fails:
- Log error with iteration number
- Continue with remaining agents
- Optionally retry failed iteration

If context budget exceeded:
- Save current state
- Generate final report
- Exit gracefully
```

## Notes

- This system implements multi-shot prompting at the orchestration level
- Pattern library prevents redundancy while encouraging innovation
- Each wave improves the quality bar for subsequent waves
- Infinite mode discovers emergent patterns over time
- Pattern library is reusable across different specs with similar domains

## Related Commands

- `/project:extract-patterns` - Extract patterns from iterations
- `/project:analyze-patterns` - Analyze pattern library effectiveness
