---
name: generate-script-orchestrated
description: Generate screenplay script episodes with orchestration — spawns fresh sub-agent per batch with cross-series thread/beat/pattern verification. Recommended for production script runs.
allowed-tools: Read, Write, Glob, Bash, Skill, Task
argument-hint: "[project] [--fresh|--from N]"
---

# /generate-orchestrated - Orchestrated Episode Generation

Generate episodes using a two-tier architecture:
- **Orchestrator** (you) - maintains lightweight series-level state
- **Batch Sub-Agents** - spawned fresh for each 5-episode batch

## Why Use This

The orchestrated approach solves context drift over 60 episodes:
- Each batch gets pristine context (no accumulated cruft)
- Orchestrator retains clarity for cross-series verification
- Can verify "did the thread planted in ep 12 pay off in ep 58?"
- Pattern violations caught early with specific recommendations

---

## Usage

```
/generate-orchestrated [project]
/generate-orchestrated [project] --fresh
/generate-orchestrated [project] --from [batch]
```

**Examples:**
```
/generate-orchestrated leviathan              # Resume from last checkpoint
/generate-orchestrated leviathan --fresh      # Backup, clear, start from ep 1
/generate-orchestrated leviathan --from 6     # Resume from batch 6
```

---

## Execution Instructions

When this skill is invoked, follow the agent protocol in `/agents/orchestrator_agent.md`.

The orchestrator workflow is also documented inline below for reference:

When `/generate-orchestrated [project]` is invoked:

### Step 1: Initialize Orchestrator State

Check if orchestrator state exists:

```bash
ls ./[project]/_pipeline/state/orchestrator_state.json
```

**If not exists:** Initialize it:
```bash
python3 /tools/init_orchestrator_state.py ./[project]
```

**If --fresh flag:** Backup and reinitialize:
```bash
# Backup existing episodes
timestamp=$(date +%Y%m%d_%H%M%S)
mkdir -p ./[project]/_pipeline/state/backups/generation_$timestamp
mv ./[project]/scripting/episodes/ep_*.md ./[project]/_pipeline/state/backups/generation_$timestamp/

# Reinitialize state
python3 /tools/init_orchestrator_state.py ./[project]
```

### Step 2: Load Orchestrator Context

Read the lightweight orchestrator state:

```
./[project]/_pipeline/state/orchestrator_state.json
```

Extract:
- `position.next_batch` → batch to generate
- `thread_tracker` → thread status and targets
- `emotional_beat_map` → beats pending
- `pattern_state` → hook/cliffhanger distribution
- `cross_batch_flags` → any issues from previous batches

Also read treatment.md THREAD INDEX section for reference.

### Step 3: Check Position

```
IF position.next_batch > 12:  # 12 = TOTAL_GENERATION_BATCHES (see CONSTANTS.md)
   → Series is complete
   → Run final verification
   → Output completion report
   → EXIT

IF --from [N] specified:
   → Set next_batch = N
   → Backup episodes from N onward
```

### Step 4: Prepare Batch Instructions

For the current batch, create instructions:

```json
{
  "batch": [N],
  "episodes": "[start]-[end]",
  "thread_instructions": {
    "plant_in_this_batch": [threads with target_plant in this range],
    "advance_in_this_batch": [threads needing advancement],
    "payoff_in_this_batch": [threads with target_payoff in this range],
    "overdue_threads": [threads past target_payoff]
  },
  "emotional_beat_instructions": {
    "beats_due_this_batch": [beats with target_episode in range],
    "tolerance": "±2 episodes"
  },
  "pattern_instructions": {
    "hook_constraint": [constraint if 3+ consecutive same type],
    "cliffhanger_constraint": [constraint if 3+ consecutive same type]
  },
  "continuity": {
    "last_location": [from previous batch summary],
    "open_tension": [from previous cliffhanger],
    "character_states": [key states]
  }
}
```

### Step 5: Output Batch Start

```
═══════════════════════════════════════════════════════════════
ORCHESTRATOR: Starting Batch [N] (Episodes [X]-[Y])
═══════════════════════════════════════════════════════════════

BATCH INSTRUCTIONS:
  Threads to plant: [list or "none"]
  Threads to advance: [list or "none"]
  Emotional beats due: [list or "none"]
  Pattern constraint: [constraint or "none"]

SPAWNING BATCH SUB-AGENT...
───────────────────────────────────────────────────────────────
```

### Step 6: Spawn Batch Sub-Agent

Use the Task tool to spawn a fresh batch agent:

```
Task tool:
  subagent_type: "general-purpose"
  description: "Generate batch [N] episodes"
  prompt: |
    You are a Batch Agent. Generate 5 episodes for [project].

    BATCH: [N]
    EPISODES: [start]-[end]

    INSTRUCTIONS:
    [batch_instructions JSON]

    PROTOCOL:
    1. Read /agents/batch_agent.md for full protocol
    2. Load fresh context (treatment, characters, format_v12)
    3. Extract treatment batch: python3 /tools/extract_treatment_batch.py ./[project] [N]
    4. Read last 2 episodes for continuity
    5. Generate 5 episodes following Kill Box format
    6. Validate each with episode_metrics.py (word count, dialogue %, exchanges)
    7. Run cinematization pass on each episode:
       - Scan for literary prose patterns
       - Transform to cinematic alternatives
       - Re-validate if content changed
       - See format_v12/SKILL.md → CINEMATIZATION PASS
    8. Run subtext pass on dialogue:
       - Flag on-the-nose lines (direct emotion, direct answers)
       - Transform using deflection, displacement, evasion
       - Target ~70% subtext, ~30% direct
       - See format_v12/SKILL.md → SUBTEXT PASS
    9. Run checkpoint: python3 .claude/hooks/save_checkpoint.py ./[project] [N]
    9. Report completion with summary

    OUTPUT when done:
    - Episodes saved to /[project]/scripting/episodes/
    - Batch summary at /[project]/state/batch_[N]_summary.json
    - Report: threads planted/advanced, beats hit, pattern distribution
```

### Step 7: Receive Batch Results

After batch agent completes:

1. Read batch summary:
   ```
   ./[project]/_pipeline/state/batch_[N]_summary.json
   ```

2. Verify checkpoint passed:
   ```
   ./[project]/_pipeline/state/checkpoints/batch_[N]_checkpoint.json
   ```

### Step 8: Update Orchestrator State

The checkpoint automatically runs `update_orchestrator_state.py`, but verify:

```bash
cat ./[project]/_pipeline/state/orchestrator_state.json | grep "last_completed_batch"
```

### Step 9: Run Verification Checks

Check for issues:

**Thread continuity:**
- Any threads overdue (past target_payoff)?
- Any threads stale (no mention for 15+ episodes)?

**Pattern variety:**
- Any 4+ consecutive same hook type?
- Any 4+ consecutive same cliffhanger type?

**Emotional beats:**
- Any beats missed that were due this batch?

**At checkpoint batches (3, 6, 9, 12):**
```bash
python3 /tools/orchestrator_verify.py ./[project]
```

### Step 10: Output Batch Complete

```
═══════════════════════════════════════════════════════════════
ORCHESTRATOR: Batch [N] Complete
═══════════════════════════════════════════════════════════════

BATCH RESULTS:
  Episodes generated: [X]-[Y] ✓
  Validation: PASSED
  Threads planted: [list]
  Threads advanced: [list]
  Emotional beats hit: [list]

PATTERN STATE (series total):
  Hooks: [X]% silent ([Y] total, [Z] consecutive)
  Cliffhangers: [X]% mid-action ([Y] total, [Z] consecutive)

[If any issues:]
FLAGS:
  ⚠ [Issue description and recommendation]

PROGRESS: [N]/12 batches ([X]/60 episodes)
═══════════════════════════════════════════════════════════════
```

### Step 11: Continue Loop

```
IF next_batch <= 12:  # 12 = TOTAL_GENERATION_BATCHES (CONSTANTS.md)
   → Increment next_batch
   → GOTO Step 4 (prepare next batch instructions)

IF next_batch > 12:  # 12 = TOTAL_GENERATION_BATCHES (CONSTANTS.md)
   → GOTO Step 12 (series complete)
```

### Step 12: Series Complete

Run final verification:
```bash
python3 /tools/orchestrator_verify.py ./[project]
```

Output completion report:

```
═══════════════════════════════════════════════════════════════
ORCHESTRATOR: Series Generation Complete
═══════════════════════════════════════════════════════════════

FINAL STATISTICS:
  Episodes: 60/60
  Batches: 12/12

THREAD RESOLUTION:
  ✓ [Thread]: planted Ep X, paid off Ep Y
  ...

EMOTIONAL BEATS: [X]/11
  ✓ FIRST_CRACK (Ep [N])
  ...

PATTERN DISTRIBUTION:
  Hooks: [X]% silent / [Y]% dialogue
  Cliffhangers: [X]% mid-action / [Y]% aftermath

[If any unresolved flags:]
REVIEW NEEDED:
  ⚠ [Issue requiring human attention]

NEXT STEPS:
  1. /compile [project] — Generate Fountain file
  2. Review any flagged issues
  3. Final quality pass
═══════════════════════════════════════════════════════════════
```

---

## Parameters

| Parameter | Required | Default | Description |
|-----------|----------|---------|-------------|
| `project` | Yes | — | Project folder name (e.g., `leviathan`) |
| `--fresh` | No | off | Backup current episodes, reset state, start from ep 1 |
| `--from [N]` | No | — | Resume from specific batch number |

---

## Comparison: Generation Modes

| Mode | Context Management | User Interaction | Best For |
|------|-------------------|------------------|----------|
| `/generate-orchestrated` | Fresh sub-agent per batch | Autonomous (can pause) | Production runs, quality focus |
| `/generate` | Manual /compact between batches | Pauses after each batch | Maximum user control |
| `/autogenerate` | Auto-reload, single agent | Fully autonomous | Speed, hands-off |

**All three produce the same output format** and use the same validation pipeline.

---

## Files

| File | Location | Purpose |
|------|----------|---------|
| Orchestrator state | `/[project]/state/orchestrator_state.json` | Series-level tracking |
| Batch summaries | `/[project]/state/batch_N_summary.json` | Per-batch metadata |
| Episodes | `/[project]/scripting/episodes/ep_XXX.md` | Generated scripts |
| Checkpoints | `/[project]/state/checkpoints/batch_N_checkpoint.json` | Validation records |

---

## Troubleshooting

### "Orchestrator state not found"

Run initialization:
```bash
python3 /tools/init_orchestrator_state.py ./[project]
```

### Thread detected as overdue

The thread's target_payoff episode has passed. Either:
- Payoff immediately in next batch
- Update treatment if target was wrong

### Pattern violation detected

4+ consecutive same hook/cliffhanger type. The next batch MUST include the opposite type to break the pattern.

### Batch agent fails validation

The batch agent should retry automatically (max 3 times per episode). If still failing:
- Check episode_metrics.py output for specific issues
- May need manual fix or regeneration

---

*This skill provides orchestrated generation with fresh context per batch and cross-series verification for quality assurance.*
