---
name: autogenerate-scripts
description: Generate all screenplay script episodes autonomously without stopping. Runs continuously, auto-reloads context between batches. Use when you want to walk away and let it finish.
allowed-tools: Read, Write, Glob, Bash, Skill
argument-hint: "[project] [--fresh|--from N]"
---

# /autogenerate - Autonomous Episode Generation

Generate episodes autonomously, running continuously until all episodes are complete. Auto-invokes `/load-context` after each batch and after any context compaction—**never stops to ask the user for input**.

## Usage

```
/autogenerate [project]
/autogenerate [project] --fresh
/autogenerate [project] --continue
/autogenerate [project] --from [batch]
```

**Examples:**
```
/autogenerate leviathan                    # Resume from last checkpoint
/autogenerate leviathan --fresh            # Backup, clear, start from ep 1
/autogenerate leviathan --continue         # Explicit resume (same as no flag)
/autogenerate leviathan --from 6           # Resume from batch 6
```

## Parameters

| Parameter | Required | Default | Description |
|-----------|----------|---------|-------------|
| `project` | Yes | — | Project folder name at root level (e.g., `leviathan`) |
| `--fresh` | No | off | Backup current episodes, reset state, start from episode 1 |
| `--continue` | No | on | Resume from last checkpoint (default behavior) |
| `--from [N]` | No | — | Resume from specific batch number |

---

## Fresh Regeneration Protocol

When invoked with `--fresh`:

### Step 1: Backup Current Episodes

```bash
# Create timestamped backup folder
mkdir -p ./[project]/backups/episodes_backup_[YYYYMMDD_HHMMSS]/

# Move all episodes to backup
mv ./[project]/scripting/episodes/ep_*.md ./[project]/backups/episodes_backup_[YYYYMMDD_HHMMSS]/
```

**Backup naming:** `episodes_backup_20260119_153052`

### Step 2: Reset State

Reset `./[project]/_pipeline/state/current_state.json`:

```json
{
  "project": "[project]",
  "last_episode": 0,
  "last_batch": 0,
  "last_completed_batch": 0,
  "last_completed_episode": 0,
  "next_batch": 1,
  "generated": [],
  "cliffhanger_history": [],
  "hook_history": [],
  "emotional_beats_hit": [],
  "threads_planted": [],
  "threads_paid_off": [],
  "relationship_stage": "Transaction",
  "character_states": {},
  "last_updated": "[ISO_TIMESTAMP]",
  "generation": {
    "last_validated": 0,
    "last_checkpoint": null,
    "validation_passed": false
  }
}
```

### Step 3: Clear Checkpoints (Optional)

```bash
# Archive old checkpoints
mv ./[project]/_pipeline/state/checkpoints/*.json ./[project]/backups/episodes_backup_[TIMESTAMP]/checkpoints/
```

### Step 4: Begin Autonomous Generation

Follow `/skills/orchestration_process/SKILL.md`:

```
REPEAT until the final episode:
  1. Read current_state.json → identify next batch
  2. Read treatment.md for batch content (THE MOMENT, prose, cliffhanger images)
  3. Read last 2 episodes for continuity (if any)
  4. For each episode:
     a. Generate episode → save to /scripting/episodes/
     b. Run: python3 /tools/episode_metrics.py ./[project]/scripting/episodes/ep_XXX.md --json
     c. If `is_valid: false`:
        - Run: python3 /tools/episode_metrics.py [file] --prompt
        - Apply fix instructions
        - Re-validate (max 3 attempts)
     d. Do NOT proceed to next episode until `is_valid: true`
  5. Run: python3 .claude/hooks/save_checkpoint.py ./[project] [batch]
  6. IF validation fails → apply deviation auto-regeneration protocols → retry
  7. Update current_state.json
  8. Continue to next batch
```

**CRITICAL:** Validate each episode with `episode_metrics.py --json` after EACH write. Do not estimate—the script counts accurately. Do NOT proceed to the next episode until `is_valid: true`.

---

## Resume Protocol

When invoked without `--fresh` (default) or with `--continue`:

### Step 1: Read State

```bash
# Check current position
cat ./[project]/_pipeline/state/current_state.json
```

### Step 2: Verify Episodes on Disk

```bash
# Count existing episodes
ls ./[project]/scripting/episodes/ep_*.md | wc -l
```

### Step 3: Identify Next Batch

- `next_batch` = `last_completed_batch` + 1
- If `last_completed_batch` = 12, generation is complete

### Step 4: Continue Generation

Resume the autonomous generation loop from the identified batch.

---

## Pre-Generation Gate (MANDATORY)

**Before starting ANY generation (fresh or resume), you MUST run:**

```bash
python3 .claude/hooks/validate_pre_generation.py ./[project]
```

This gate verifies ALL required files exist:
- [ ] `treatment.md` ← **MASTER generation input** (blocks if missing)
- [ ] `ORCHESTRATION.md` ← Project-specific rules
- [ ] `scripting/bible/characters.md` ← Voice patterns, behavioral DNA
- [ ] `scripting/bible/series_bible.md` ← World, characters
- [ ] `_pipeline/state/current_state.json` ← Position tracking

**If the gate returns exit code 1 → GENERATION IS BLOCKED.**

Do NOT proceed with generation until all required files exist.

### Missing treatment.md?

The most common blocker is missing `treatment.md`. Create it with:
```
/treatment [project]
```

This generates the 60-episode prose treatment containing:
- Prose paragraphs (what happens and why it matters)
- THE MOMENT (the one beat that must land per episode)
- Cliffhanger images (specific visual to end on)

> **Note:** `treatment.md` is the MASTER generation input. `bible/episode_arc.md` (if present) is a reference document from promotion but is NOT used directly during generation.

---

## Source Documents for Generation

| Document | Purpose | Status |
|----------|---------|--------|
| `./[project]/treatment.md` | Prose paragraphs, THE MOMENT, cliffhanger images | **MASTER INPUT** |
| `./[project]/ORCHESTRATION.md` | Project-specific rules, behavioral DNA, humor | Required |
| `./[project]/scripting/bible/characters.md` | Voice patterns, FORBIDDEN/REQUIRED | Required |
| `./[project]/scripting/bible/series_bible.md` | World, characters, thematic core | Required |
| `./[project]/_pipeline/state/current_state.json` | Position tracking | Required |
| `/skills/format_v12/SKILL.md` | Word count, dialogue %, Kill Box structure | Reference |
| `/skills/orchestration_process/SKILL.md` | Batch loop, checkpoint protocol | Reference |
| `/calibration/dramatic_quality_calibration.md` | GOOD/BAD examples | Reference |

> **Deprecated for generation:** `./[project]/scripting/bible/episode_arc.md` — This file exists as a reference from promotion but `treatment.md` has replaced it as the generation input.

---

## Output

### On Fresh Start
```
═══════════════════════════════════════════════════════════════
AUTOGENERATE: [PROJECT] — Fresh Regeneration
═══════════════════════════════════════════════════════════════

BACKUP CREATED:
  Location: ./[project]/backups/episodes_backup_[TIMESTAMP]/
  Episodes: 60 files backed up
  Checkpoints: Archived

STATE RESET:
  last_completed_batch: 0
  last_completed_episode: 0
  next_batch: 1

BEGINNING GENERATION...
  Reading treatment.md...
  Reading characters.md...
  Starting Batch 1 (Episodes 1-5)...

═══════════════════════════════════════════════════════════════
```

### On Resume
```
═══════════════════════════════════════════════════════════════
AUTOGENERATE: [PROJECT] — Resume from Checkpoint
═══════════════════════════════════════════════════════════════

CURRENT STATE:
  last_completed_batch: 7
  last_completed_episode: 35
  next_batch: 8

CONTINUING GENERATION...
  Reading last 2 episodes (34, 35) for continuity...
  Starting Batch 8 (Episodes 36-40)...

═══════════════════════════════════════════════════════════════
```

---

## Execution

When this skill is invoked:

1. **Read the skill file** (this document)
2. **Parse parameters** (`--fresh`, `--continue`, `--from`)
3. **MANDATORY: Invoke `/load-context` using the Skill tool:**
   ```
   Skill tool → skill: "load-context", args: "[project] generate"
   ```
   This loads all required files into context before any generation begins.
4. **Load project state** from `./[project]/_pipeline/state/current_state.json`
5. **Execute appropriate protocol:**
   - `--fresh` → Backup + Reset + Generate
   - `--continue` (default) → Resume + Generate
   - `--from [N]` → Partial backup + Reset to N-1 + Generate
6. **Follow the AUTONOMOUS GENERATION LOOP below**
7. **Run checkpoint validation** after each batch
8. **MANDATORY: Invoke `/load-context` via Skill tool after each batch validates**
9. **IF CONTEXT COMPACTION DETECTED: Invoke `/load-context` via Skill tool and continue**
10. **Update state** after each successful batch
11. **LOOP: Return to step 6** — Continue to next batch until the final episode is complete

**CRITICAL:** This is AUTONOMOUS generation. Never stop to ask the user to run commands. When you need to reload context (after batches or after compaction), invoke `/load-context` yourself using the Skill tool and continue.

---

## Safety

- **Backups are mandatory** before any destructive operation
- **Never delete** without backing up first
- **Timestamped folders** prevent overwriting previous backups
- **State is reset** only after successful backup
- **Checkpoints are archived** with episodes

---

## AUTONOMOUS GENERATION LOOP (CRITICAL)

**This is the core loop. DO NOT STOP after a batch completes—continue to the next batch.**

```
LOOP until next_batch > TOTAL_GENERATION_BATCHES:  # 12 = TOTAL_GENERATION_BATCHES (CONSTANTS.md)
  1. Read current_state.json → identify next_batch
  2. IF next_batch > TOTAL_GENERATION_BATCHES → EXIT LOOP (series complete)  # CONSTANTS.md: TOTAL_GENERATION_BATCHES
  3. Read treatment.md for this batch's episodes
  4. Read last 2 episodes for continuity
  5. Generate 5 episodes (verify word count after each)
  6. Run checkpoint: python3 .claude/hooks/save_checkpoint.py ./[project] [batch]
  7. IF checkpoint FAILS → fix episodes → GOTO step 6
  8. IF checkpoint PASSES:
     a. Update current_state.json
     b. INVOKE /load-context via Skill tool:
        Skill tool → skill: "load-context", args: "[project] generate"
     c. CONTINUE TO NEXT ITERATION immediately (do not stop)
  9. IF CONTEXT COMPACTION DETECTED at any point:
     a. INVOKE /load-context via Skill tool (same as 8b)
     b. Continue from current position
  10. GOTO step 1
```

**IMPORTANT:**
- After a batch validates, DO NOT output "BATCH COMPLETE" and wait
- After context compaction, DO NOT ask the user to run `/compact`
- ALWAYS invoke `/load-context` yourself using the Skill tool
- The loop only exits when `next_batch > TOTAL_GENERATION_BATCHES` — i.e. all episodes complete (see `CONSTANTS.md → TOTAL_GENERATION_BATCHES`)

---

## MANDATORY CONTEXT RELOAD BETWEEN BATCHES (CRITICAL)

**After EVERY successful batch checkpoint, you MUST invoke `/load-context` before continuing to the next batch.**

**How to reload:** Use the Skill tool to invoke `/load-context`:

```
Skill tool → skill: "load-context", args: "[project] generate"
```

This is NOT optional. Context accumulates cruft over batches. The `/load-context` skill ensures:
- Treatment prose stays fresh (not paraphrased from memory)
- Character voices stay distinct (not contaminated)
- Format rules stay precise (not approximated)
- Current position is verified

**DO NOT just read files manually—invoke the skill so it reports position and confirms context.**

---

## CONTEXT COMPACTION PROTOCOL (CRITICAL)

**When context is automatically compacted during generation, you MUST immediately invoke `/load-context` and continue—DO NOT stop and ask the user.**

### Detection

You'll know compaction happened if:
- Previous batch content is suddenly unclear
- You can't recall specific treatment prose
- Character voice patterns feel vague
- Format rules seem summarized rather than detailed

### Automatic Recovery (DO NOT STOP)

**When compaction is detected:**

1. **Invoke `/load-context`** using the Skill tool:
   ```
   Skill tool → skill: "load-context", args: "[project] generate"
   ```
2. **Wait for "CONTEXT LOADED" confirmation**
3. **Verify current position** from the output
4. **CONTINUE generation immediately** from where you left off

### Why Automatic Recovery

This is **autonomous** generation. The whole point is to run without user intervention. When context compacts:
- ❌ DO NOT output "Please run /compact"
- ❌ DO NOT ask the user to do anything
- ❌ DO NOT stop and wait
- ✅ DO invoke `/load-context` yourself
- ✅ DO continue the generation loop

### The Rule

**After ANY context compaction → invoke `/load-context` via Skill tool → continue immediately**

---

## Comparison: /autogenerate vs /generate

| Aspect | /autogenerate | /generate |
|--------|---------------|-----------|
| Context handling | Auto-reloads via Skill tool after each batch | User manually runs /compact + /generate |
| User interaction | Fully autonomous—runs until all episodes complete | Pauses after each batch for user action |
| Context compaction | Auto-recovers by invoking /load-context | Asks user to run /compact |
| Voice drift risk | Low (auto-reload between batches) | Minimal (fresh context per batch) |
| Speed | Faster (no pauses) | Slower (manual pauses) |
| Best for | Hands-off generation | Maximum control |

**Both commands now auto-reload context between batches.** The difference is:
- `/autogenerate` handles everything autonomously
- `/generate` pauses for user review and manual context clearing

---

## Quick Reference

```
/autogenerate [project]           # Resume from checkpoint, run autonomously
/autogenerate [project] --fresh   # Backup → Reset → Start from ep 1
/autogenerate [project] --from 6  # Backup eps 26+ → Resume from batch 6

AUTONOMOUS LOOP:
  1. Invoke /load-context via Skill tool
  2. Generate batch (5 episodes)
  3. Validate batch
  4. Invoke /load-context via Skill tool (reload)
  5. Continue to next batch
  6. IF context compaction → invoke /load-context → continue
  7. Repeat until the final episode complete

NEVER STOPS TO ASK USER:
  ❌ "Please run /compact"
  ❌ "Run /load-context to continue"
  ✅ Invokes /load-context itself via Skill tool
  ✅ Continues autonomously until all episodes done
```
