# Microdramas Workflow Guide

> Complete reference from initial concept through finished scripts.

**Authoritative specification:** `/WORKFLOW_SPEC.md`
**Numeric values source of truth:** `/CONSTANTS.md`

> This guide provides a comprehensive reference for the Microdramas workflow. For authoritative process definitions, see `/WORKFLOW_SPEC.md`.

---

## SESSION START — DO THIS FIRST

**At the start of EVERY session (including after context compaction), run:**

```
/load-context [project] [mode]
```

| Mode | When to Use |
|------|-------------|
| `generate` | Episode generation (default) |
| `develop` | Development/pre-production work |
| `treatment` | Creating or revising treatment.md |

**Examples:**
```
/load-context leviathan generate    # Scripting: generate episodes
/load-context leviathan develop     # Development work
/load-context asi-bridge treatment  # Treatment phase
/load-context                       # Auto-detect from current directory
```

**This skill:**
1. Reads all required files for the mode
2. Reports current position (for generation)
3. Confirms context is loaded before work begins

**DO NOT skip this step.** Context-blind generation produces poor results.

### Files Loaded by Mode

**All modes load:**
- `/CONSTANTS.md` — Numeric values (single source of truth)
- `/skills/format_v12/SKILL.md` — V12 format rules

**Generate mode also loads:**
| File | Purpose |
|------|---------|
| `/[project]/treatment.md` | **MASTER** generation input |
| `/[project]/ORCHESTRATION.md` | Project-specific rules |
| `/[project]/bible/characters.md` | Voice patterns (CRITICAL) |
| `/[project]/state/current_state.json` | Position tracking |
| `/skills/orchestration_process/SKILL.md` | Batch loop, checkpoint protocol |
| `/appendix_a_cliffhangers_hooks.md` | Hook/cliffhanger taxonomy |
| Last 2 episodes | Continuity reference |

**Treatment mode also loads:**
| File | Purpose |
|------|---------|
| `/[project]/bible/series_bible.md` | World, characters, theme |
| `/[project]/bible/episode_arc.md` | Beat schedule (60 episodes) |
| `/[project]/bible/characters.md` | Voice patterns for prose |
| `/skills/treatment/SKILL.md` | Treatment format rules |

**Develop mode also loads:**
| File | Purpose |
|------|---------|
| `/_development/[project]/STATUS.md` | Progress tracking (34-point) |
| `/SCRIPTING_REQUIREMENTS.md` | 34-point checklist |
| `/templates/dev_templates/characters_template.md` | Required character format |
| `/appendix_c_emotion.md` | Anchor types, emotional architecture |
| Any existing dev docs | characters.md, thematic_spine.md, etc. |

> **Skill reference:** `.claude/skills/load-context/SKILL.md`

---

## Skills Reference

Before starting any phase, read relevant skills:

| Skill | Location | Purpose |
|-------|----------|---------|
| **Format Rules** | `/skills/format_v12/SKILL.md` | Word counts, dialogue %, Kill Box |
| **Cliffhanger/Hook Taxonomy** | `/appendix_a_cliffhangers_hooks.md` | Complete cliffhanger & hook subtypes |
| **Dramatic Elements** | `/skills/dramatic_elements/SKILL.md` | Wildcards, archetypes, pattern interrupts |
| **Variety Toolkit** | `/appendix_b_variety.md` | Wildcard beats, tone shifts, surprise |
| **Emotional Architecture** | `/appendix_c_emotion.md` | Anchor types, emotional beats, catharsis |
| **Treatment** | `/skills/treatment/SKILL.md` | Prose treatment, beat types, thread markers, THE MOMENT |
| **Relationship Earning** | `/skills/relationship_earning/SKILL.md` | When declarations are earned |
| **Generation Process** | `/skills/orchestration_process/SKILL.md` | How to run generation sessions |
| **Calibration** | `/skills/calibration/SKILL.md` | GOOD/BAD examples reference |

---

## Overview

This system supports the full lifecycle of vertical microdrama creation:

```
DEVELOPMENT → VALIDATION → PROMOTION → TREATMENT → GENERATION → VISUAL DESIGN → STORYBOARD → PRODUCTION
                                                                      ↑                          ↓
                                                               ASSESSMENT ← REWRITE ← COMPILATION
```

| Phase | Purpose | Output |
|-------|---------|--------|
| Development | Build characters, world, structure | 34-point checklist + dev docs |
| Validation | Verify dramatic infrastructure | Pass/fail gates |
| Promotion | Convert to scripting format | Bible + arc + state files |
| Treatment | Expand arc to prose treatment | treatment.md (MASTER for generation) |
| Generation | Write 60 episodes | Scripts in /episodes/ |
| Assessment | Find quality issues | Prioritized fix list |
| Rewrite | Fix specific issues | Revised scripts |
| Compilation | Merge into single file | Fountain screenplay |
| **Visual Design** | **Lock the look of the series** | **visual_bible.md + reference sheets** |
| **Storyboard** | **Shot breakdown per episode** | **storyboard_ep_NNN.json** |
| **Production** | **Generate frames and video** | **PNG frames + MP4 clips** |

---

# PHASE 1: DEVELOPMENT

## Starting a Project

### Option A: From Scratch

```
I want to start developing a new microdrama concept.

PROJECT SETUP:
1. Create folder: /Microdramas/_development/[name]/
2. Initialize STATUS.md
3. Create notes.md

INITIAL CONCEPT:
[Your idea here, OR "brainstorm" for 5 premise options]
```

### Option B: From Existing Materials

```
Create a development folder for [name].
I'm uploading my materials. Read everything and update STATUS.md.
```

### Option C: Resume Previous Work

```
Continue working on [project].
Read /_development/[name]/STATUS.md and show me current progress.
```

---

## The 34-Point Checklist (Character-First)

**CRITICAL:** Characters come BEFORE theme articulation. Theme is DISCOVERED through character collision, not designed upfront.

### SECTION 1: Characters First (10 items)

| # | Requirement | Why It Matters |
|---|-------------|----------------|
| 1 | Protagonist sketch (name, age, role, competence) | Who are we following? |
| 2 | Protagonist behavioral DNA | On-screen behaviors, not backstory |
| 3 | Antagonist sketch (name, role, what makes them SMART) | Worthy opposition |
| 4 | Antagonist behavioral DNA | Behaviors + what they're RIGHT about |
| 5 | Emotional anchor sketch | Challenges protagonist, holds truth |
| 6 | Anchor behavioral DNA | Behaviors + danger response |
| 7 | Voice patterns defined | Idiom, relational shorthand, anti-patterns |
| 8 | Voice consistency checklist | Distinct patterns, no contamination |
| 9 | Character tone & humor | Type, funny lines, when humor shifts |
| 10 | Protagonist need layers | Surface, deeper, deepest |

### SECTION 2: Pressure Test (2 items)

| # | Requirement | Why It Matters |
|---|-------------|----------------|
| 11 | Collision sequence written | 3 NON-CANONICAL test episodes forcing conflict |
| 12 | Theme discovery | Name what emerged from collision |

> **IMPORTANT:** The pressure test episodes are a SANDBOX. They are NOT Episodes 1-3 of your series. Write them to discover how your characters behave under pressure, what conflicts emerge naturally, and what theme reveals itself. Then discard them. If you try to make the pressure test "count" as real episodes, you'll constrain the discovery process and defeat the purpose.

### SECTION 3: Thematic Spine (5 items) — NOW articulate theme

| # | Requirement | Why It Matters |
|---|-------------|----------------|
| 13 | "This is really about..." | Emerged from collision |
| 14 | Thematic question | Debatable, no easy answer |
| 15 | Protagonist's thematic stance | Revealed through collision choices |
| 16 | Antagonist's counter-thesis | Defensible opposing answer |
| 17 | Mythological DNA | Archetype/myth echo |

### SECTION 4: Concept & Hook (5 items)

| # | Requirement | Why It Matters |
|---|-------------|----------------|
| 18 | Surprising conceit | Subverts expectation |
| 19 | Logline | Protagonist + goal + stakes + setting |
| 20 | Genre blend | Primary + secondary |
| 21 | Demographic hook | Competence porn, gamification, sigma flip |
| 22 | Archetype-Worldview | Type + visual manifestation |

### SECTION 5: Emotional Architecture (4 items)

| # | Requirement | Why It Matters |
|---|-------------|----------------|
| 23 | Anchor type | Cub/Ghost/Mirror |
| 24 | Anchor need layers | Surface, deeper, deepest |
| 25 | Primary Ache | What audience yearns for |
| 26 | Relationship milestones mapped | Earning schedule |

### SECTION 6: World (3 items)

| # | Requirement | Why It Matters |
|---|-------------|----------------|
| 27 | Setting | Where, when, sensory details |
| 28 | Rules/constraints | Pressure cooker |
| 29 | Factions/power structure | Forces in play |

### SECTION 7: Structure (5 items)

| # | Requirement | Why It Matters |
|---|-------------|----------------|
| 30 | 3-act breakdown | Major movements |
| 31 | 8-sequence skeleton | Episode clusters |
| 32 | Key plot points | Ep 15, 30, 45, 60 |
| 33 | Emotional beat schedule | 11 required beats |
| 34 | Thematic checkpoints | Theme integrated throughout |

---

## Behavioral DNA: The Core Requirement

**Every major character needs:**

| Element | Pass | Fail |
|---------|------|------|
| 3+ on-screen behaviors | "Talks to empty chair when stuck" | "Lost his brother" (backstory) |
| Stress behavior (specific) | "Laughs at inappropriate moments" | "Gets quiet" (generic) |
| Signature line | "Sixty-forty I don't die in this hole." | "We need to move." (anyone) |
| Orthogonal trait | Rust-lung (just exists, doesn't serve theme) | All traits serve theme |
| Contradiction | The cynic keeps a memento | Never breaks pattern |

### Character Expression Variety (Anti-Repetition)

Character elements should feel organic, not mechanical:

| Element | Target Frequency | Anti-Pattern |
|---------|-----------------|--------------|
| Behavioral DNA | 2-3 per batch (varied) | Same behavior 2+ consecutive eps |
| Idiom/Voice | 3-4 per batch (natural) | Forcing idiom every episode |
| Signature line | 2-3 per ACT | Overusing signature phrases |
| Stress behavior | Key moments only | Every conflict triggers it |
| Orthogonal trait | When organic to story | Forced appearances |

**The Rule:** If you notice you're checking a box, you're doing it wrong. Character expression should emerge from the scene's dramatic needs, not from a frequency requirement.

**The Orthogonal Trait Test:**
1. List ALL the character's defined traits
2. For each trait, ask: "Would this trait exist if the story had a completely different theme?"
3. If the answer is NO for every trait → character is engineered
4. At least ONE trait must exist just because it's WHO THEY ARE

---

## Development Documents

As decisions solidify, create these documents:

| Document | Created When | Contents |
|----------|--------------|----------|
| `characters.md` | After Section 1 | Behaviors, stress, signature lines, voice DNA |
| `pressure_test_results.md` | After Section 2 | Collision sequence, theme discovery |
| `thematic_spine.md` | After Section 3 | Theme, question, mythology |
| `relationship_map.md` | After Section 5 | Stages, markers, Primary Ache |
| `structure_outline.md` | After Section 7 | Acts, sequences, key points |
| `plant_payoff_plan.md` | After Section 7 | Thread seeds, payoff windows, echoes |

---

## Development Commands

| Command | Purpose |
|---------|---------|
| `/develop [project]` | Interactive development (guided) |
| `/develop [project] --audit` | Gap analysis without interaction |
| `/showrunner [project]` | Agent-driven development (faster) |
| `/showrunner [project] --auto 5` | Make 5 decisions automatically |

---

# PHASE 2: VALIDATION

## Three Validation Gates

Before promotion, projects must pass three gates:

### Gate 1: Behavioral DNA Gate (HARD)

```bash
python3 .claude/hooks/validate_behavioral_dna.py ./_development/[project]
```

**Checks:**
- 3+ on-screen behaviors per major character
- Specific stress behaviors (not generic)
- Signature lines that pass swap test
- At least 1 orthogonal trait per character
- Contradictions defined

**If this fails:** STOP. Fix character DNA before proceeding.

### Gate 2: Arc Validation Gate (HARD)

**Automated Checks (Tier 1):**
```bash
python3 /tools/validate_arc.py ./[project]
```
- No more than 3 consecutive same-type cliffhangers
- Action density ≥20 beats across series
- All 11 emotional beats at designated episodes
- Plant/Payoff: ≥6 threads, required variety

**Subjective Scoring (Tier 2) — Pairwise Methodology:**
```bash
python3 /tools/validate_arc.py ./[project] --pairwise
```
Generates prompts for Claude to score using reasoning-before-judgment:
- Cliffhanger intensity (≥9.0 overall, ≥8.5 per sequence)
- Tension Escalation, Reversal Quality, Stakes, Variety, Pacing (avg ≥7.0)

See `/evaluation/pairwise_comparison.md` for methodology.

### Gate 3: Validate Agent (HARD)

```
/validate [project]
/validate [project] --strict
```

**Tier 1 (Must Pass):**
- All 34 checklist items checked
- All 5 development documents exist
- Law 2 tables complete (plot + character for Ep 15, 30, 45, 60)
- Primary Ache defined with threats
- At least 8 relationship markers

**Tier 2 (Scored, Avg ≥ 3.5):**
- Thematic question clarity
- Thesis/antithesis tension
- Primary Ache intensity
- Key episode quality (15, 30, 45, 60)

**Results:**
- ❌ NOT READY — Hard gate failed
- ⚠️ READY WITH WARNINGS — Pass with flags
- ✅ READY FOR PROMOTION — All clear

---

# PHASE 3: PROMOTION

> **Full reference:** `/WORKFLOW_SPEC.md` Phase 3

Promotion transforms development documents into production-ready scripting format.

```
/promote [project]
```

**What happens:**
1. Folder created at `/[project]/` (root level)
2. **Development docs TRANSFORMED to scripting format:**
   - `characters.md` → `/bible/characters.md` (COPIED DIRECTLY - no transformation)
   - `world.md` + `concept_hook.md` + `thematic_spine.md` → `/bible/series_bible.md`
   - `structure_outline.md` → `/bible/episode_arc.md` (TWO-STEP PROCESS - see below)
3. State files initialized:
   - `/state/current_state.json` — Narrative position
   - `/state/checkpoints/` — Batch checkpoints
4. ORCHESTRATION.md created — Master generation prompt

## Episode Arc Creation (Two-Step Process)

The episode_arc.md is created in two steps during promotion:

**Step 1: Python Skeleton** (automatic)
- `promote_project.py` creates `episode_arc.md` with 8 sequence headers
- Generates 60 episode rows with `[FILL]` placeholders
- Includes verification templates and plant/payoff tracking

**Step 2: AI Fills Details** (promote_agent)
- Reads dev documents: `structure_outline.md`, `plant_payoff_plan.md`, `characters.md`, `thematic_spine.md`
- Fills per-episode details:
  - **One-Line** — Episode summary
  - **Cliffhanger** — Specific image/line ending
  - **Type** — Cliffhanger code (M-CF, M-PT, A-RE, etc.)
  - **Intensity** — 1-10 rating
- Verifies distribution, emotional beats, intensity curve

**After promotion, episode_arc.md contains:**
- All 60 episodes with one-line summaries
- Cliffhanger text and type codes
- Intensity scores
- Thread markers (plant/advance/payoff)
- Action/emotional beat flags

---

# PHASE 4: TREATMENT

> **Full reference:** `/skills/treatment/SKILL.md`

Treatment transforms the production `bible/episode_arc.md` into a **prose treatment document** (`treatment.md`) that serves as the MASTER input for episode generation.

---

## Why Treatment?

1. **Cheap changes:** Fixing "Episode 23 is a retread" costs seconds at the prose level, hours at the script level
2. **Plussing opportunity:** 60 paragraphs reveal weak spots: "Three escapes in a row" jumps out
3. **THE MOMENT focus:** Every episode has ONE key beat that must land—identified before generation
4. **Generator constraint:** Episode generator executes treatment prose, hitting THE MOMENT and cliffhanger image

---

## Treatment Format

**Before (outline):**
```markdown
**Ep 5: "Breadcrumb"**
- **Event:** Dax finds data chip with Cass's voice...
```

**After (treatment):**
```markdown
### Episode 5: "Breadcrumb"
**Sequence:** 1 | **Beat:** CATALYST | **Hook:** SILENT | **Cliffhanger:** MID-ACTION
**Threads:** [PLANT: Cass's Humming]
**THE MOMENT:** Her voice on the recording — "Hey, little brother" — she's alive, or was

Dax finds a data chip hidden behind a cat sticker—their childhood sign, their secret
language. His hands shake as he plays it. Humming first—a melody he knows—then her
voice: "Hey, little brother. If you're hearing this... I'm sorry." This is the hook
that launches everything. Cass isn't just missing. She's alive, or was. She planned
this. Left it for him specifically.

**[CLIFFHANGER: The recording cuts out mid-sentence. Dax sits in the dark, holding the chip.]**
```

---

## Key Treatment Elements

### THE MOMENT

Every episode has ONE moment that must land—the emotional payload:

| Element | Example |
|---------|---------|
| Format | `**THE MOMENT:** [specific image/line] — [why it matters]` |
| Good | "Her voice on the recording — 'Hey, little brother' — she's alive" |
| Bad | "Emotional beat happens" (vague) |

**THE MOMENT must be:**
- A specific image, line, or action (not abstract)
- The ONE beat the episode lives or dies by
- What the audience will remember

### Prose Paragraph

The prose paragraph weaves all episode content together in flowing narrative form:
- What happens and why it matters emotionally
- Key dialogue snippets in quotes
- Thread connections to larger story
- Sensory/visual details

### Cliffhanger Image

Every episode ends with a SPECIFIC visual or line:

```markdown
**[CLIFFHANGER: The recording cuts out mid-sentence. Dax sits in the dark, holding the chip.]**
```

Not just "MID-ACTION"—the actual image to hit.

---

## Word Counts by Beat Type

| Beat Type | Word Range | Reason |
|-----------|------------|--------|
| SETUP, COMPLICATION | 40-55 words | Standard beats |
| CATALYST, LOCK-IN | 50-70 words | Turning points need detail |
| COLLISION, CRISIS, REVELATION | 60-80 words | High-stakes moments |
| CLIMAX | 70-90 words | Emotional peaks, complex beats |
| RESOLUTION | 50-70 words | Landing the ending |

*See `/CONSTANTS.md` for canonical values.*

---

## Thread Marker Syntax

| Marker | Format | Meaning |
|--------|--------|---------|
| PLANT | `[PLANT: Thread Name]` | First appearance, subtle |
| ADVANCE | `[ADVANCE: Thread Name]` | Thread progresses, more visible |
| PAYOFF | `[PAYOFF: Thread Name]` | Thread pays off, full visibility |

All thread names must reference the THREAD INDEX at the top of treatment.md.

---

## Hook & Cliffhanger Distribution

| Type | Target | Requirement |
|------|--------|-------------|
| Hook: SILENT | 70-85% | Hard gate |
| Hook: DIALOGUE | 15-30% | Balance |
| Cliffhanger: MID-ACTION | 70-85% | Hard gate |
| Cliffhanger: AFTERMATH | 15-30% | Balance |

**Critical constraint:** No 4+ consecutive same type (max 3 allowed; see `CONSTANTS.md`).

### First 10 Episodes Rule (Pilot Window)

The first 10 episodes must hook the audience with intense cliffhangers:

- **Ep 1-10:** All cliffhangers should be MID-ACTION (exempt from pattern variety)
- **Ep 11+:** Standard pattern variety applies (max 3 consecutive same type)
- **SILENT hooks are fine throughout** — they resolve the previous cliffhanger

---

## Treatment Commands

| Command | Purpose |
|---------|---------|
| `/treatment [project]` | Transform outline to prose treatment |
| `/treatment [project] --validate-only` | Check existing treatment format |
| `/treatment [project] --flag-weak` | Identify weak episodes for review |
| `/treatment [project] --plus [N,N,N]` | Improve specific episodes |

---

## Treatment Reader (Fountain Compile)

Compile treatment into a clean Fountain document for human review (~12-15 minute read):

```bash
python3 /tools/compile_treatment.py ./[project]
# Creates: [project]/[name]_treatment.fountain
```

**Output format for each episode:**
```
[[EPISODE 1: SALVAGE]]

[Prose paragraph - what happens and why it matters]

[Cliffhanger image - the specific beat to end on]

===
```

**The compiled output includes:**
- Episode number and title as section header
- Prose paragraph (the action/content)
- **Cliffhanger image** (the final beat - now included for complete episode picture)
- Page breaks between episodes

**Human review focus:**
- Read all 60 episodes in ~12-15 minutes
- Check each cliffhanger creates a "need to know" moment
- Flag weak episodes for plussing

---

## Treatment Validation

```bash
python3 /tools/validate_treatment.py ./[project]
python3 /tools/validate_treatment.py ./[project] --flag-weak
```

**Hard Gates:**
| Check | Requirement |
|-------|-------------|
| Coverage | All 60 episodes present |
| Metadata | Sequence, Beat, Hook, Cliffhanger on each |
| THE MOMENT | Present and specific for each episode |
| VOICE SEED | Episode 1 has VOICE SEED line |
| Key episode words | Ep 1 ≥80, Ep 10/15 ≥70 words |
| **Total word count** | **3000-4000 words (~15-20 min read)** |
| Cliffhanger images | Bracketed specific visual/line |
| Thread coherence | All markers reference THREAD INDEX |
| Thread resolution | All threads have PLANT + PAYOFF |
| Hook ratio | 70-85% SILENT |
| Cliffhanger ratio | 70-85% MID-ACTION |
| Pattern variety | Max 3 consecutive same type |

**Soft Flags:**
- Vague language ("tensions rise", "things escalate")
- 4+ consecutive same beat type
- Weak THE MOMENT (generic, not visual)
- **Continuity flags** (MID-ACTION → DIALOGUE transitions may lose tension)
- Episode 10 urgency (should have physical danger element)

---

## Treatment Workflow

```
1. /treatment [project]
   └── Transform episode_arc.md to prose treatment
   └── Creates: treatment.md (MASTER document)
   └── Source: bible/episode_arc.md (unchanged)

2. Human review (~15 min)
   └── Read 60 prose paragraphs
   └── Check THE MOMENT is specific for each
   └── Flag weak episodes

3. /treatment [project] --plus [weak episodes]
   └── AI suggests alternatives with diagnosis
   └── Human selects

4. python3 validate_treatment.py ./[project]
   └── Verify all hard gates pass

5. Proceed to generation (Phase 5)
```

---

## Treatment vs Episode Arc

| Aspect | episode_arc.md | treatment.md |
|--------|----------------|--------------|
| Purpose | Intermediate format from promotion | Generation input (MASTER) |
| Format | Bullet points | Prose paragraphs |
| THE MOMENT | Implicit | Explicit |
| Cliffhanger | Type only | Specific image |
| Word counts | N/A | By beat type |
| Status | Reference only during treatment | MASTER document for generation |

---

## Characters File (No Transformation Needed)

> characters.md is COPIED DIRECTLY during promotion — no transformation required.

**Why no transformation?** The development `characters.md` template is already structured for both development AND generation:

```markdown
## JINX — THE SCAVENGER

### Behavioral DNA

**On-Screen Behaviors:**
1. Counts on her fingers when calculating odds
2. Touches her debt counter when lying
3. Talks to objects before trusting them

**Stress Behavior:** Gets LOUDER and MORE flippant. Jokes accelerate.

**Signature Line:** "Sixty-forty I regret this."

**Orthogonal Trait:** Hums when she works. Off-key, barely audible.

**Contradiction:** Treats everything as transaction—except when someone is genuinely dying.

### Voice DNA

**Idiom:** Gambling math—speaks in bets, odds, percentages

**Humor Type:** GALLOWS HUMOR

**Anti-Patterns (NEVER says):**
- Absolutes ("always," "never," "definitely")
- "Trust me"
- Unhedged hope

### Voice Evolution

**FORBIDDEN until Episode {N}:**
- sincere statements without ironic distance

**REQUIRED in every episode:**
- at least one gambling metaphor
- deflection when emotions surface

**Voice Evolution Trigger:**
- Episode 45: [trigger event]
- After trigger: [new voice pattern]
```

**Template:** `/templates/dev_templates/characters_template.md`

**Full specification:** `/WORKFLOW_SPEC.md`

---

## Project-Specific Voice Enforcement

The `characters.md` file must include CHARACTER-SPECIFIC ENFORCEMENT RULES:

```markdown
### {CHARACTER_NAME}

**FORBIDDEN until Episode {N}:**
- {pattern} (e.g., "sincere statements without ironic distance")
- {pattern} (e.g., "direct expressions of care")

**REQUIRED in every episode:**
- {pattern} (e.g., "at least one gambling metaphor")
- {pattern} (e.g., "deflection when emotions surface")

**Voice Evolution Trigger:**
- Episode {N}: {trigger event}
- After trigger: {new voice pattern}
```

**Examples:**
- Jinx: FORBIDDEN "sincere statements without ironic distance" until Ep 45+
- Kian: FORBIDDEN "human idioms" until Ep 20+ (learns them over time)
- Antagonist: FORBIDDEN "admission of being wrong" (always)

This enforcement layer prevents voice drift and ensures character evolution happens at the right moments.

---

## Scripting Folder Structure

```
/[project]/
├── treatment.md              ← MASTER prose treatment (generation input)
├── bible/
│   ├── series_bible.md       ← World, theme, mythology
│   ├── characters.md         ← Behavioral DNA, voice patterns
│   └── episode_arc.md        ← 60-episode roadmap (from promotion)
├── state/
│   ├── current_state.json
│   └── checkpoints/
├── episodes/
│   ├── ep_001.md
│   ├── ep_002.md
│   └── ...
├── logs/                      ← QA reports
├── ORCHESTRATION.md          ← Project-specific rules
└── [PROJECT]_COMPLETE.fountain
```

---

## Pre-Generation Review

Before autonomous generation, validate episode_arc.md:

### Step 1: Run Validation Script

```bash
python3 .claude/hooks/validate_episode_arc.py ./[project]/bible/episode_arc.md
```

**Checks:**
- Thread coherence (plant → advances → payoff)
- Minimum 6 threads
- Hook ratio (target: 80% silent, validation: 70-85%)
- Cliffhanger ratio (target: 80% mid-action, validation: 70-85%)
- No 4+ consecutive same type (max 3 allowed)
- Structural beats at eps 15, 30, 45, 60

Fix any ERRORS. Review WARNINGS.

### Step 2: Human Review

Spend 10-15 minutes reviewing:
- Thread coherence (do plants pay off logically?)
- Pacing (emotional temperature variety?)
- Pattern variety (no monotonous hooks/cliffhangers?)

### Step 3: Approve or Revise

Do not proceed to generation until satisfied with the arc structure.

---

# PHASE 5: GENERATION

## V12 Constraints

> **Full reference:** `/skills/format_v12/SKILL.md`
> **Cliffhanger/Hook Taxonomy:** `/appendix_a_cliffhangers_hooks.md`

| Rule | Value | Notes |
|------|-------|-------|
| Word count | 450-500 per episode (see `CONSTANTS.md`) | Check project ORCHESTRATION.md for overrides |
| Dialogue | ≤40% of word count | |
| Exchanges | 6-8 per episode max | |
| Hooks | Target: 80% silent | Validation accepts: 70-85% |
| Cliffhangers | Target: 80% mid-action | Validation accepts: 70-85% |
| Action blocks | 1-3 lines (4 max) | Shot-aware |
| Pattern limit | Max 3 consecutive same type | 4+ is violation |

### Narrative Integrity Rules

> **Full reference:** `/skills/format_v12/SKILL.md` → Narrative Integrity Rules section

| Rule | Description |
|------|-------------|
| **No episode numbers in prose** | Reference events by WHAT HAPPENED, not "Episode 10" |
| **Visual callbacks** | Must be filmable; don't narrate the connection |
| **Authorial voice** | Prose must be transparent; no "we see..." or "the audience realizes..." |

**Examples:**
| ❌ Wrong | ✅ Right |
|----------|----------|
| "kept since Episode 1" | "kept since the beginning" |
| "The same hands that once..." | Just show the same gesture |
| "Ironically, she..." | Let the irony speak for itself |

**Validation:** The `validate_batch.py` script checks for meta-references and fails on "Episode N" patterns in prose.

**Cliffhanger Subtypes:**
- **Mid-Action:** Physical Threat (M-PT), Countdown (M-CT), Choice (M-CH), Pursuit (M-PU), Confrontation (M-CF)
- **Aftermath:** Revelation (A-RE), Consequence (A-CO), Power Shift (A-PS), The Silence (A-SI), The Cost (A-CT), The Decision (A-DE)

### Action Block Architecture

> **Full rules:** `/skills/format_v12/SKILL.md` → Action Block Architecture section

**The Camera Test (MANDATORY):** Every paragraph = ONE shot.

| If camera points at... | Then... |
|------------------------|---------|
| Different subject (him → her) | NEW PARAGRAPH |
| Different scale (wide → CU) | NEW PARAGRAPH |
| Different area of location | NEW PARAGRAPH |
| A beat or pause | NEW PARAGRAPH |

**Filmability Gate:** If you cannot point a camera at it, CUT IT.

| FILMABLE (Keep) | UNFILMABLE (Cut) |
|-----------------|------------------|
| "Rust flakes from the hooks" | "since before Jinx was born" |
| "Her eye whirs, focusing" | "forty years in the grey market" |

**Block Length Rules:**
| Block Type | Lines | When to Use |
|------------|-------|-------------|
| Impact beat | 1 line | Gunshot, reveal, single punch |
| Standard | 2-3 lines | Most action blocks |
| Dense texture | 4 lines MAX | Complex setup requiring detail |

**CRITICAL ANTI-PATTERN:** Prose-novel blocks (6+ lines, multiple subjects, unfilmable backstory) are the #1 generation failure mode. See calibration doc for examples.

---

## Generation Commands

### Generation Mode Comparison

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

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

---

### The /generate Skill — Clean Context Per Batch (Recommended)

> **Skill reference:** `.claude/skills/generate/SKILL.md`

```
/generate [project]                    # Resume from last checkpoint
/generate [project] --fresh            # Backup, clear, start from ep 1
/generate [project] --from [batch]     # Resume from specific batch
```

**How /generate works:**
- **Invokes `/load-context [project] generate` FIRST** (mandatory)
- Generates one batch (5 episodes)
- Runs checkpoint validation
- **Pauses and waits for user** to run `/compact` + re-invoke `/generate`
- This ensures fresh context each batch, preventing drift

**Fresh Regeneration (`--fresh`):**
1. Backs up current `/episodes/` to `/backups/episodes_backup_[timestamp]/`
2. Resets `current_state.json` to batch 0
3. Archives checkpoints
4. Begins generation from episode 1

**Resume (default):**
1. Invokes `/load-context` to load required files
2. Reads `current_state.json` for position
3. Generates next batch, then pauses

**Recommended for production quality.** The pause between batches allows context to be cleared, preventing voice drift and constraint relaxation.

### Manual Generation

```
Generate Episodes 1-5 for [project].
```

### /autogenerate — Autonomous Continuous Generation

> **Skill reference:** `.claude/skills/autogenerate/SKILL.md`
> **Full process reference:** `/skills/orchestration_process/SKILL.md`

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

**How /autogenerate works:**
- **Invokes `/load-context [project] generate` at start** (mandatory)
- Runs continuously until Episode 60 complete or context compacts
- **Does NOT stop after each batch** — continues automatically
- **Reloads context between batches** (treatment.md, characters.md, format_v12)

**Autonomous loop:**
```
LOOP until next_batch > 12:
  1. Read current_state.json → identify next_batch
  2. IF next_batch > 12 → EXIT (series complete)
  3. Read treatment.md for this batch
  4. Read last 2 episodes for continuity
  5. Generate 5 episodes (verify word count after each)
  6. Run checkpoint validation
  7. IF checkpoint FAILS → fix → retry
  8. IF checkpoint PASSES:
     a. Update current_state.json
     b. RELOAD CONTEXT (treatment, characters, format rules)
     c. CONTINUE TO NEXT BATCH (do not stop)
  9. IF CONTEXT COMPACTION → /load-context → resume
```

**Key difference from /generate:** `/autogenerate` continues automatically after each batch. `/generate` pauses and waits for user to run `/compact`.

### /generate-orchestrated — Two-Tier Orchestrated Architecture

> **Skill reference:** `.claude/skills/generate-orchestrated/SKILL.md`
> **Agent protocols:** `/agents/orchestrator_agent.md`, `/agents/batch_agent.md`

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

**How /generate-orchestrated works:**

Uses a two-tier architecture to solve context drift over 60 episodes:

```
┌─────────────────────────────────────────────────────────────┐
│                     ORCHESTRATOR AGENT                       │
│  Maintains: Thread tracker, emotional beat map, pattern state│
│  Context size: ~2-3K tokens (lightweight)                    │
├─────────────────────────────────────────────────────────────┤
│  ┌─────────────┐  ┌─────────────┐       ┌─────────────┐     │
│  │ Batch 1     │  │ Batch 2     │  ...  │ Batch 12    │     │
│  │ Sub-Agent   │  │ Sub-Agent   │       │ Sub-Agent   │     │
│  │ (fresh)     │  │ (fresh)     │       │ (fresh)     │     │
│  └─────────────┘  └─────────────┘       └─────────────┘     │
└─────────────────────────────────────────────────────────────┘
```

- **Orchestrator** maintains lightweight series-level state (~2-3K tokens)
- **Batch Sub-Agents** spawned fresh per batch (~15-20K tokens each)
- Each batch agent receives orchestrator instructions and returns structured summary
- Verification layer runs after each batch and at checkpoints

**Benefits over other modes:**
- Fresh context per batch (no accumulated cruft or voice drift)
- Orchestrator retains clarity for cross-series verification
- Can track threads across full 60-episode arc
- Pattern violations caught early with specific episode references

**Orchestrator loop:**
```
LOOP until Batch 12 complete:
  1. Read orchestrator_state.json (lightweight)
  2. Prepare batch instructions (threads, beats, patterns)
  3. Spawn fresh batch sub-agent via Task tool
  4. Batch agent: loads full context, generates 5 episodes, validates, returns summary
  5. Update orchestrator state from batch summary
  6. Run verification checks (threads, beats, patterns)
  7. At batches 3,6,9,12: goal-backward checkpoint
  8. Continue to next batch
```

**Files:**

| File | Location | Purpose |
|------|----------|---------|
| Orchestrator state | `/[project]/state/orchestrator_state.json` | Thread tracker, beat map, pattern state |
| Batch summaries | `/[project]/state/batch_N_summary.json` | Per-batch metadata from sub-agents |

**Commands:**
```bash
# Initialize orchestrator state (automatic on first run)
python3 /tools/init_orchestrator_state.py ./[project]

# Run combined verification
python3 /tools/orchestrator_verify.py ./[project]

# Individual verification checks
python3 /tools/verify_thread_continuity.py ./[project]
python3 /tools/verify_emotional_beats.py ./[project]
python3 /tools/verify_pattern_variety.py ./[project]
```

**When to use:** Production runs where quality is paramount and you want cross-series verification without manual context management.

### Episode Writing Rule (MANDATORY)

**After EVERY episode Write, validate with `episode_metrics.py` before proceeding:**

```bash
python3 /tools/episode_metrics.py ./[project]/episodes/ep_XXX.md --json
```

**Validation loop:**
1. Check `is_valid` in the JSON output
2. If `true`: proceed to next episode
3. If `false`:
   a. Run with `--prompt` flag to get fix instructions
   b. Apply the specific fix instructions to the episode
   c. Re-validate (max 3 attempts)
4. Do NOT proceed to next episode until `is_valid: true`

**Why this script instead of `wc -w`:**
- Python counts accurately (LLMs cannot tally while generating)
- Checks word count, exchanges, AND dialogue % in one pass
- Provides specific fix instructions when out of range
- Episodes are pre-validated before batch checkpoint

**Do NOT:**
- Estimate word counts in headers—verify them
- Skip validation for "just one episode"
- Blame the validator if your estimate was wrong
- The validator counts all words in the file; your header estimate is not authoritative

### Word Count Validation (CRITICAL)

**Claude cannot count words accurately while generating.** Only Python scripts provide correct counts.

**The validator counts ALL words in the file including:**
- Headers and metadata (# Episode X: Title)
- Kill Box timestamps ([00:00-00:05])
- Cliffhanger/hook type annotations
- Everything from start to end of file

**Exchange counting:** Each character cue = 1 exchange (not speaker transitions).

**Iterative Validation Workflow:**
1. Generate episode (aim for ~470-480 words by feel)
2. Run: `python3 /tools/episode_metrics.py [file] --json`
3. If invalid (e.g., "515 words, max 500"):
   - Remove ~15-20 words from action descriptions
   - Re-run validation
   - Repeat until valid
4. Do NOT trust header word count estimates—they are approximations

**Tips for trimming:**
- Remove one 15-20 word sentence from action
- Cut adjectives/adverbs that don't add visual info
- Combine short action blocks

### Deviation Auto-Regeneration

When generation produces episodes outside constraints, follow the deviation protocol (`/DEVIATION_RULES.md`):

| Issue | Action |
|-------|--------|
| Word count 501-530 | Auto-regenerate (1x) with trim focus |
| Word count >530 after 2 tries | Flag for review, continue |
| Word count <450 | Keep regenerating until ≥450 |
| Dialogue >40% | Auto-regenerate with dialogue cap |
| Pattern 4x+ consecutive | Auto-regenerate with forced interrupt |
| Voice drift | Reload characters.md, regenerate |
| Character repetition | Regenerate with different DNA element |

**Philosophy:** All deviations are handled through regeneration. Flagged issues are addressed during `/rewrite`.

**Logging:** All deviations logged to `state/deviation_log.json`:
```json
{
  "episode": 15,
  "deviation_type": "word_count_over",
  "original_value": 537,
  "action_taken": "auto_regenerate",
  "attempts": 2,
  "resolved": true,
  "flagged_for_review": false
}
```

**Why mandatory reload?** Context degradation over 12 batches causes:
- Instructions drift as context fills
- Voice patterns blur
- Format rules get paraphrased
- Accumulated cruft from fixes/retries

The reload takes ~30 seconds but prevents hours of rewrites.

### Context Compaction Protocol

**When automatic context compaction occurs during generation, IMMEDIATELY run:**

```
/load-context [project] generate
```

**Detection:** Context compaction has occurred 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

**The Rule:** After ANY context compaction → `/load-context` → then continue

This is non-negotiable. Continuing without reload produces blind generation.

### Resume After Context Limit

```
Continue [project] generation from the last checkpoint.
```

---

## Three-Gate Validation (Per Batch)

### Gate 1: Mechanical Validation

| Check | Requirement |
|-------|-------------|
| Word count | 450-500 words (see `CONSTANTS.md`) |
| Dialogue | ≤40% |
| Exchanges | ≤8 |
| Format | Kill Box structure |
| **Meta-references** | **No "Episode N" patterns in prose** |

**Meta-reference gate:** The validator checks prose sections for episode number references like "Episode 10" or "55 episodes of..." and hard-fails if found. Reference events by what happened, not production numbers.

### Gate 2: Quality Gate

| Tier | Checks | On Fail |
|------|--------|---------|
| Tier 1 | Pattern variety (hooks, cliffhangers) | HARD FAIL |
| Tier 2 | Dramatic beats, transitions | HARD FAIL |
| Tier 3 | Ratios, thread opportunities | Report only |

### Gate 3: Transition Gate (After Batch 12)

| Check | Description |
|-------|-------------|
| Pattern violations | No time skip after Mid-Action |
| Semantic review | Character continuity, resolution |

**Save checkpoint after each batch:**
```bash
python3 .claude/hooks/save_checkpoint.py ./[project] [batch_number]
```

### Voice Contamination Check (Batches 3, 6, 9, 12)

At these batches, the checkpoint script runs voice contamination detection:

```bash
python3 .claude/hooks/baseline_comparison.py ./[project] [batch]
```

This detects **unintentional contamination** (characters borrowing each other's idioms) and **regression** (characters reverting to earlier patterns unexpectedly).

**Note:** Character voice *should* evolve intentionally (mask cracking, relationship deepening). This check catches *unintentional* drift, not designed evolution.

**On contamination detection:**
- Script flags which characters are contaminating each other
- Auto-triggers `/dramatic-qc [project] --mode post --batch [N] --lens voice`
- Review before continuing to next batch

### Goal-Backward Verification (Batches 3, 6, 9, 12)

At milestone batches, verify arc trajectory against targets:

| Batch | Episode | Threads Resolved | Arc Progress | Emotional Beats |
|-------|---------|------------------|--------------|-----------------|
| 3 | 15 | 0-1 | 25% | 2/11 |
| 6 | 30 | 2-3 | 50% | 5/11 |
| 9 | 45 | 4-5 | 75% | 8/11 |
| 12 | 60 | 6+ | 100% | 11/11 |

**Verification Steps:**
1. Count threads resolved vs target
2. Check emotional beats hit vs schedule
3. Calculate arc progress percentage
4. If off-track: generate course correction recommendations

**Course Correction Actions:**
- Missing threads: Accelerate payoffs in next batch
- Missing beats: Insert recovery beat in next available episode
- Pacing issues: Flag for treatment revision

---

# PHASE 6: ASSESSMENT

## The 5-Question Test

Before assessment, ask:

1. **Behavioral Specificity:** Can you describe the protagonist in three on-screen behavioral traits?
2. **Unpredictability:** Does any scene contain something unexpected from genre conventions?
3. **Voice Distinctiveness:** Is there a single line of dialogue ONLY this character would say?
4. **Earned Emotion:** Does the emotional climax arrive through conflict or declaration?
5. **Memorability:** Would you remember a specific moment 24 hours after watching?

If the answer to most is "no," the project has dramatic quality issues.

---

## Dramatic QC Commands

| Task | Command |
|------|---------|
| Pre-generation check | `/dramatic-qc [project] --mode pre` |
| Post-batch check | `/dramatic-qc [project] --mode post --batch [N]` |
| Full assessment | `/dramatic-qc [project] --mode assess --lens all` |
| Single lens | `/dramatic-qc [project] --lens voice --ep [N]` |

---

## Validation Approach

| Element | Frequency | Validation |
|---------|-----------|------------|
| Behavioral DNA | Every episode | **Automated** — concrete physical tells are detectable |
| Voice/Idiom | Every other episode (guidance) | **Manual** via /dramatic-qc — some idioms aren't regex-detectable |

**Why this distinction:**
- Behavioral DNA is concrete: "touches wrist", "scans exits", "counts on fingers" — regex can find these
- Voice idiom varies: gambling (detectable) vs poetic/philosophical (not detectable)
- Post mask-break: Idiom can fade as arc completes — transformation beats consistency

---

## The Seven Assessment Lenses

### 1. Behavioral DNA (`behavioral_dna.md`)

**Checks:**
- Do characters have on-screen behaviors or just backstory?
- Are stress behaviors specific or generic?
- Do signature lines pass the swap test?
- Is there at least one orthogonal trait per character?

**Scoring:**
| Score | Level | Description |
|-------|-------|-------------|
| 9-10 | Vivid | Behaviors drive scenes; immediately recognizable |
| 7-8 | Strong | Behaviors present; occasional generic moments |
| 5-6 | Present | Some evidence; relies on dialogue |
| 3-4 | Weak | Mostly backstory; few behaviors |
| 1-2 | Absent | Character is concept, not person |

### 2. Voice (`voice.md`)

**The Swap Test:**
1. Take 5 lines of dialogue from Character A
2. Remove the character name
3. Can you identify the speaker?

If not → voice needs work.

**Scoring:**
| Score | Level | Description |
|-------|-------|-------------|
| 9-10 | Unmistakable | Could identify from any 3 consecutive lines |
| 7-8 | Strong | Could identify most lines |
| 5-6 | Present | Inconsistent, some contamination |
| 3-4 | Weak | Generic with occasional flashes |
| 1-2 | Absent | Interchangeable with any character |

### 3. Texture (`texture.md`)

**Checks:**
- Emotional register variety (not all same intensity)
- Surprise elements (subverts expectations)
- Buildup before declarations
- Theme embodied, not stated

**Scoring:**
| Score | Level | Description |
|-------|-------|-------------|
| 9-10 | Masterful | Every beat feels inevitable AND surprising |
| 7-8 | Strong | Clear emotional architecture; good variety |
| 5-6 | Competent | Some register shifts; mostly expected |
| 3-4 | Flat | Monotone or predictable |
| 1-2 | Dead | No emotional progression |

### 4. Relationship Earning (`relationship_earning.md`)

> **Full reference:** `/skills/relationship_earning/SKILL.md`

**The Earning Equation:**
```
Emotional Weight of Declaration ≤ Accumulated Evidence
```

**Episode timing guide:**
| Episode | Appropriate Level |
|---------|-------------------|
| 1-10 | Actions only, no declarations |
| 11-20 | Small acknowledgments ("You're not useless") |
| 21-30 | Tentative trust ("I trust you with this") |
| 31-40 | Significant statements ("I need you") |
| 41-50 | Deep connection |
| 51-60 | Major declarations ("I love you") |

**Accelerated Earning (shared intensity):**
| Accelerator | Multiplier |
|-------------|------------|
| Shared near-death survival | 2x |
| One saves other's life | 2x |
| Mutual vulnerability in crisis | 1.5x |
| Extended isolation together | 1.5x |

**Scoring:**
| Score | Level | Description |
|-------|-------|-------------|
| 9-10 | Fully earned | Every declaration backed by demonstration |
| 7-8 | Mostly earned | Key moments earned; minor shortcuts |
| 5-6 | Partially earned | Some demonstration, some declaration |
| 3-4 | Thin | More declaration than demonstration |
| 1-2 | Declared | Relationships announced, not built |

### 5. Visual Richness (`visual_richness.md`)

**Checks:**
- Can every line of prose be pointed at with a camera?
- Are action blocks shot-aware (one shot per paragraph)?
- Is there sensory detail beyond dialogue?
- Are locations and objects visually specific?

**Scoring:**
| Score | Level | Description |
|-------|-------|-------------|
| 9-10 | Cinematic | Every line filmable; rich visual texture |
| 7-8 | Strong | Mostly filmable; occasional abstract language |
| 5-6 | Adequate | Some visual detail; relies on dialogue |
| 3-4 | Thin | Generic descriptions; hard to visualize |
| 1-2 | Abstract | Prose reads like summary, not screenplay |

### 6. Continuity (`continuity.md`)

**Checks:**
- Do planted threads pay off?
- Are character states consistent across episodes?
- Do props, injuries, and locations track correctly?
- Are timeline references consistent?

**Scoring:**
| Score | Level | Description |
|-------|-------|-------------|
| 9-10 | Airtight | All threads tracked; no contradictions |
| 7-8 | Strong | Minor gaps; major threads consistent |
| 5-6 | Adequate | Some dangling threads; no major breaks |
| 3-4 | Weak | Noticeable contradictions; threads forgotten |
| 1-2 | Broken | Continuity errors undermine story |

### 7. Double-View Continuity (`double_view_continuity.md`)

**Checks:**
- Does a rewatch reveal planted details that weren't obvious first time?
- Are early moments recontextualized by later revelations?
- Do background details gain significance on second viewing?
- Is foreshadowing subtle enough to miss but clear enough to find?

**Scoring:**
| Score | Level | Description |
|-------|-------|-------------|
| 9-10 | Masterful | Rewatch transforms the experience; layers of hidden detail |
| 7-8 | Strong | Several planted details reward second viewing |
| 5-6 | Present | Some foreshadowing; mostly surface-level |
| 3-4 | Thin | Few rewatch rewards; story plays the same both times |
| 1-2 | Absent | No planted details; single-view story |

---

## Severity Levels

### MUST FIX (Blocks Quality)

- No behavioral evidence for character
- Voice contamination between characters
- Declaration without buildup
- Theme stated in dialogue
- Monotone register (3+ episodes at same intensity)

### COULD IMPROVE (Flagged)

- Missing orthogonal trait
- Generic stress response
- Thin relationship (stated, not demonstrated)
- No surprise element in batch

---

# PHASE 7: REWRITE

## Rewrite Commands

```
/rewrite [project] ep [N] "[issue description]"
/rewrite [project] ep [N-M] "[issue]"     # Linked arc (max 5)
/rewrite [project] ep [N]                  # Suggest mode
```

**Examples:**
```
/rewrite leviathan ep 23 "Kian's dialogue feels too robotic"
/rewrite leviathan ep 47-49 "Scar revelation needs more buildup"
/rewrite leviathan ep 58 "I love you moment feels rushed"
```

**Process:**
1. Reads episode + surrounding context + characters.md
2. Presents 2 AI options + custom input
3. Creates `.backup` before changes
4. Logs to `/state/rewrite_log.json`

---

## Thread Commands

Add plant/payoff schemes across episodes:

```
/thread [project] "[name]" --episodes [N,N,N,N]
/thread [project] "[name]" --auto
```

**Examples:**
```
/thread leviathan "Lucky Coin" --episodes 1,15,35,56
/thread leviathan "Kian's memory of Earth" --auto
```

---

## Batch Revision

Process annotations from the Revision Tool:

```
/revise [project] annotations.json
```

**Workflow:**
1. Open `/editors/revision_editor.html`
2. Load compiled `.fountain` file
3. Highlight text, add comments
4. Export annotations as JSON
5. Run `/revise`
6. Process each with [A]pply / [S]kip / [M]anual

---

# PHASE 8: COMPILATION

## Compile Commands

```
/compile [project]                    # Clean screenplay (no metadata)
/compile [project] --metadata         # With episode titles + cliffhanger callouts
/compile [project] --treatment        # Treatment to Fountain
/compile [project] [output_name]      # Custom output name
```

**Examples:**
```
/compile leviathan                    # → LEVIATHAN_COMPLETE.fountain
/compile leviathan --metadata         # → LEVIATHAN_WITH_METADATA.fountain
/compile leviathan --treatment        # → treatment_reader.fountain
/compile the-hike THE_HIKE_FINAL.fountain
```

## Compilation Modes

### Episode Mode (default)

**Output:** `/[project]/[TITLE]_COMPLETE.fountain`

**What it does:**
- Strips ALL metadata (word counts, loglines, cliffhanger annotations)
- Extracts clean Fountain content
- Adds page breaks between episodes
- Creates title page

**Use case:** Final screenplay for reading/production.

### Metadata Mode (`--metadata`)

**Output:** `/[project]/[TITLE]_WITH_METADATA.fountain`

**What it preserves:**
- Episode title as centered heading: `> EPISODE 1: THE VOID <`
- Cliffhanger type at end: `> [CLIFFHANGER: Mid-Action (M-PT) - Physical Threat] <`

**Use case:** Review scripts with structural context visible.

### Treatment Mode (`--treatment`)

**Output:** `/[project]/treatment_reader.fountain`

**What it does:**
- Extracts episode titles, prose paragraphs, cliffhangers
- Strips thread markers, validation metrics, sequence headers
- Clean ~15-minute read of full series outline

**Use case:** Human review of treatment before generation.

## Process

1. Verify all 60 episodes exist (or treatment.md for --treatment)
2. Run: `python3 /tools/compile_episodes.py ./[project] [--metadata | --treatment]`
3. Output to project folder

**Compatible apps:** Highland 2, Fade In, Final Draft, WriterSolo

---

# HOOKS CONFIGURATION

## Automatic Validation Gates

The system uses Claude Code hooks to automatically enforce constraints during generation. These are configured in `.claude/settings.json`.

### Current Hook Configuration

```json
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Write",
        "hooks": [
          { "type": "command", "command": ".claude/hooks/episode_enforcement.py" },
          { "type": "command", "command": ".claude/hooks/enforce_context_load.py" }
        ]
      }
    ],
    "PostToolUse": [
      {
        "matcher": "Write",
        "hooks": [
          { "type": "command", "command": ".claude/hooks/checkpoint_reminder.py" }
        ]
      }
    ]
  }
}
```

### What Each Hook Does

| Hook | Trigger | Purpose |
|------|---------|---------|
| `episode_enforcement.py` | Before Write | Validates episode constraints before saving |
| `enforce_context_load.py` | Before Write | **Blocks episode writes if context not loaded** |
| `checkpoint_reminder.py` | After Write | Reminds to run checkpoint validation |

### Context Enforcement (Critical)

The `enforce_context_load.py` hook prevents "blind generation" after context compaction:

1. When `/load-context` runs in generate mode, it writes a flag file to `state/.context_loaded`
2. Before any episode Write, the hook checks if this flag exists and is recent
3. If missing or stale → **Write is blocked** with error message
4. This ensures context is always loaded before generation

**Why this matters:** After context compaction, Claude Code loses the treatment prose, character voices, and format rules. Without this gate, episodes would be generated from summarized/degraded context.

### Manual Validation Gates

These scripts are called manually by skills (not automatic hooks):

| Script | Called By | Purpose |
|--------|-----------|---------|
| `validate_pre_generation.py` | `/autogenerate`, `/generate` | Verifies all required files exist |
| `validate_pre_treatment.py` | `/treatment` | Blocks treatment if not promoted |
| `validate_behavioral_dna.py` | `/promote`, `/validate` | Character validation gate |
| `save_checkpoint.py` | After each batch | Batch validation + state update |

---

# QUICK REFERENCE

## Full Workflow Commands

| Phase | Command |
|-------|---------|
| **Session Start** | `/load-context [project] [mode]` ← **DO THIS FIRST** |
| **Development** | `/develop [project]` or `/showrunner [project]` |
| **Validation** | `/validate [project]` |
| **Promotion** | `/promote [project]` ← **Creates scripting folder** |
| **Treatment** | `/treatment [project]` |
| **Treatment Validation** | `python3 validate_arc.py ./[project] --treatment` |
| **Arc Pairwise Scoring** | `python3 validate_arc.py ./[project] --pairwise` |
| **Pre-Gen QC** | `/dramatic-qc [project] --mode pre` |
| **Generation (manual)** | `/generate [project]` ← Pauses after each batch |
| **Generation (auto)** | `/autogenerate [project]` ← Runs until Episode 60 |
| **Generation (orchestrated)** | `/generate-orchestrated [project]` ← Fresh sub-agent per batch |
| **Post-Batch QC** | `/dramatic-qc [project] --mode post --batch [N]` |
| **Assessment** | `/dramatic-qc [project] --mode assess --lens all` |
| **Rewrite** | `/rewrite [project] ep [N] "[issue]"` |
| **Thread** | `/thread [project] "[name]" --episodes [N,N,N]` |
| **Compile** | `/compile [project]` or `/compile [project] --metadata` |

## Python Scripts

### Validation Scripts

| Script | Location | Purpose |
|--------|----------|---------|
| `episode_metrics.py` | `/tools/` | **Per-episode validation** (run after each write) |
| `validate_docs.py` | `/tools/` | Documentation consistency checker |
| `validate_behavioral_dna.py` | `.claude/hooks/` | Character behavioral DNA validation |
| `validate_treatment.py` | `/tools/` | Treatment validation (word count, continuity, threads) |
| `validate_arc.py` | `/tools/` | Arc validation (--treatment, --pairwise, --flag-weak) |
| `validate_batch.py` | `.claude/hooks/` | Mechanical validation per batch (incl. meta-reference check) |
| `validate_pre_generation.py` | `.claude/hooks/` | Pre-generation gate (verifies all files exist) |
| `validate_pre_treatment.py` | `.claude/hooks/` | Pre-treatment gate (verifies promotion complete) |
| `validate_episode_arc.py` | `.claude/hooks/` | Episode arc structure validation |

### Workflow Scripts

| Script | Location | Purpose |
|--------|----------|---------|
| `save_checkpoint.py` | `.claude/hooks/` | Save batch checkpoint + state update |
| `quality_gate.py` | `.claude/hooks/` | Pattern/beat validation |
| `baseline_comparison.py` | `.claude/hooks/` | Voice contamination detection |
| `transition_gate.py` | `.claude/hooks/` | Transition review between batches |
| `enforce_context_load.py` | `.claude/hooks/` | **Blocks writes if context not loaded** |
| `episode_enforcement.py` | `.claude/hooks/` | Episode constraint enforcement |
| `checkpoint_reminder.py` | `.claude/hooks/` | Post-write checkpoint reminder |

### Utility Scripts

| Script | Location | Purpose |
|--------|----------|---------|
| `engine_constants.py` | `/tools/` | **Shared constants module** — reads from CONSTANTS.md |
| `promote_project.py` | `/tools/` | Creates scripting folder from development |
| `compile_episodes.py` | `/tools/` | Merge episodes to Fountain (--metadata for titles/cliffhangers) |
| `compile_treatment.py` | `/tools/` | Compile treatment.md to Fountain |
| `extract_treatment_batch.py` | `/tools/` | Extract episodes from treatment for generation |

### Orchestrator Scripts

| Script | Location | Purpose |
|--------|----------|---------|
| `init_orchestrator_state.py` | `/tools/` | Initialize orchestrator_state.json from treatment.md |
| `update_orchestrator_state.py` | `/tools/` | Update orchestrator state after each batch |
| `generate_batch_summary.py` | `/tools/` | Extract metadata from completed batch |
| `verify_thread_continuity.py` | `/tools/` | Check thread plant/advance/payoff continuity |
| `verify_emotional_beats.py` | `/tools/` | Check 11 beats hit within tolerance |
| `verify_pattern_variety.py` | `/tools/` | Check hook/cliffhanger pattern variety |
| `orchestrator_verify.py` | `/tools/` | **Combined verification runner** |

## Key Files

| File | Purpose |
|------|---------|
| `/CONSTANTS.md` | **Numeric values (single source of truth)** |
| `/DEVIATION_RULES.md` | **Auto-regeneration protocols for constraint violations** |
| `/skills/format_v12/SKILL.md` | Format rules (source of truth) |
| `/appendix_a_cliffhangers_hooks.md` | Cliffhanger & hook taxonomy (canonical) |
| `/appendix_b_variety.md` | Variety toolkit |
| `/appendix_c_emotion.md` | Emotional architecture |
| `/appendix_d_ai_video.md` | AI video production, Archetype-Worldview, visual strategy |
| `/skills/dramatic_elements/SKILL.md` | Wildcards, archetypes, pattern interrupts |
| `/skills/treatment/SKILL.md` | Treatment format, prose paragraphs, THE MOMENT |
| `/skills/relationship_earning/SKILL.md` | Earning timing guide |
| `/skills/orchestration_process/SKILL.md` | Generation process + deviation handling |
| `/skills/calibration/SKILL.md` | How to use calibration |
| `/SCRIPTING_REQUIREMENTS.md` | 34-point checklist |
| `/agents/treatment_agent.md` | Treatment transformation/plussing |
| `/agents/dramatic_qc_agent.md` | QC orchestrator |
| `/lenses/*.md` | Assessment lenses |
| `/calibration/dramatic_quality_calibration.md` | GOOD/BAD examples |
| `/[project]/treatment.md` | **MASTER document** for generation |
| `/[project]/ORCHESTRATION.md` | Project-specific content |
| `/[project]/bible/series_bible.md` | World, characters, rules |
| `/[project]/bible/characters.md` | Dialogue patterns |
| `/[project]/state/current_state.json` | Narrative position |
| `/[project]/state/deviation_log.json` | Deviation history from generation |
| `/[project]/state/orchestrator_state.json` | Thread tracker, beat map, pattern state (orchestrated mode) |
| `/[project]/state/batch_N_summary.json` | Per-batch metadata from sub-agents (orchestrated mode) |
| `/agents/orchestrator_agent.md` | Orchestrator protocol for `/generate-orchestrated` |
| `/agents/batch_agent.md` | Batch sub-agent protocol |

---

# PHASE 9: VISUAL DESIGN

## Purpose

Lock down the visual look of the series before storyboarding. This phase produces the production design documents and reference images that ensure visual consistency across all generated frames and video.

**Requires:** Episodes written (you need the scripts to know what locations, props, and wardrobe exist)
**Produces:** `visual_bible.md` + character reference sheets + location reference images

## Why After Episode Generation?

Some visual design can be conceptualized during development, but specific requirements emerge from the scripts:
- You wouldn't know to design "the Forgotten's dwellings" unless they appear in an episode
- Wardrobe changes tied to plot beats need the scripts to exist first
- Prop designs depend on how they're used in action
- Location details are implied by scene headings across 60 episodes

## Visual Bible

The Visual Bible (`visual_bible.md`) is the production design document for image generation:

| Section | Contents |
|---------|----------|
| **Color Palette** | HEX codes per location tier, per character |
| **Characters** | Visual summary, face/body, wardrobe per arc phase, reference images |
| **Props** | Dimensions, materials, colors (HEX), light behavior, state changes |
| **Locations** | Architecture style, materials, lighting, atmospheric effects |
| **VFX Elements** | UI overlays, practical effects, post-production composites |
| **Lighting Guides** | Per-scenario prompt language, reference images |
| **Flux 2 Slot Assignments** | Which reference images go in which slots (1-10) |

**Template:** `/templates/visual_bible_template.md`

## Character Reference Sheets

Generate with Flux 2 Klein (local) or Flux 2 Max (production quality):

| Angle | Purpose | Flux 2 Slot |
|-------|---------|-------------|
| Front | Primary identity | Slot 1 |
| Profile (left) | Jaw, nose, ear shape | Slot 2 |
| Three-quarter | Most common camera angle | Slot 3 |
| Full body | Wardrobe, proportions, posture | Slot 4 |

Lock these reference images and pass them into every subsequent generation.

## Flux 2 Reference Slot Allocation

| Slots | Assignment | Source |
|-------|------------|--------|
| 1-4 | Character identity | Character reference sheets |
| 5 | Wardrobe/props | Signature items |
| 6-7 | Environment | Location reference images |
| 8 | Lighting reference | Per-scene lighting setup |
| 9-10 | Pose/layout guides | Per-shot (allocated during storyboarding) |

**Full Flux 2 protocols:** `/appendix_e_flux2_protocols.md`

## Future: LoRAs

For multi-episode production consistency, train LoRAs from character reference sheets using Flux 2 [dev] (32B open weights). Not needed for storyboarding — reference images are sufficient.

---

# PHASE 10: STORYBOARD

## Purpose

Break each episode into a directed shot list with generation-ready prompts.

**Requires:** Episode scripts + visual bible (or at minimum, characters.md + series_bible.md)
**Produces:** `storyboard_ep_NNN.json` per episode

## Workflow

```
Episode Script (ep_NNN.md)
        ↓
/storyboard [project] ep [N]       ← Claude analyzes, outputs JSON
        ↓
validate_storyboard.py              ← Mechanical verification (hard gate)
        ↓
storyboard_ep_NNN.json              ← Structured shot breakdown
        ↓
Storyboard Director (HTML tool)     ← Human edits visually
        ↓
storyboard_ep_NNN.json              ← Updated with edits + director notes
        ↓
generate_from_storyboard.py         ← Generates frames + videos from JSON
        ↓
Frames (PNG) + Videos (MP4)
```

## Commands

| Command | Purpose |
|---------|---------|
| `/storyboard [project] ep [N]` | Analyze episode → JSON |
| `/storyboard [project] ep [N] --edit` | Load existing JSON, refine (fills free-form descriptions into structured fields) |
| `/storyboard [project] ep [N] --from-shotlist` | Convert markdown shotlist to JSON |

## Storyboard Agent Context Loading

| Source | Purpose |
|--------|---------|
| Episode script | The script to break into shots |
| `characters.md` | Character visual descriptions for prompts |
| `series_bible.md` | World, geography, color palette, factions |
| `visual_bible.md` | Visual design (locations, props, HEX palette) — if exists |
| `ORCHESTRATION.md` | Project-specific rules |
| `storyboard_schema.json` | Output format |
| `appendix_e_flux2_protocols.md` | Flux 2 prompt engineering |

## Storyboard Director (HTML Tool)

`/editors/shotlist_editor.html` — two-panel visual editor:
- Scrollable timeline (left) + shot editor (right)
- Free-form "Describe This Shot" field — Claude fills structured fields via `--edit`
- Toggle buttons for shot type, angle, movement, aspect
- Full prompt editing (first frame, last frame, motion)
- Drag-drop images onto shot cards
- Reference image manager
- JSON import/export, LocalStorage auto-save

## Validation

```bash
python3 /tools/validate_storyboard.py storyboard.json episode.md         # Human-readable
python3 /tools/validate_storyboard.py storyboard.json episode.md --json   # Machine-readable
python3 /tools/validate_storyboard.py storyboard.json episode.md --prompt # Fix instructions
```

**Checks:** Beat coverage, script coverage, hallucination detection, shot integrity, beat distribution.

## Shot Duration Calibration

- Target: ~5-6 seconds per shot maximum
- Anything over 6s will feel static in AI video
- Beat duration / shot count must produce reasonable per-shot durations
- 18-24 shots per episode typical for 1:30-2:00 runtime

---

# PHASE 11: PRODUCTION (Frame & Video Generation)

## Purpose

Generate visual frames and video clips from storyboard JSON.

**Requires:** Locked storyboard JSON + character reference sheets
**Produces:** PNG frames + MP4 video clips

## Pipeline Script

```bash
python3 generate_from_storyboard.py storyboard_ep_001.json --frames     # First/last frames (Flux 2)
python3 generate_from_storyboard.py storyboard_ep_001.json --video      # Videos (WAN 2.1 I2V)
python3 generate_from_storyboard.py storyboard_ep_001.json --all        # Both
python3 generate_from_storyboard.py storyboard_ep_001.json --shot 4     # Single shot
python3 generate_from_storyboard.py storyboard_ep_001.json --preview    # Low-res local preview
```

## Hardware

| Environment | Capability | Use |
|-------------|-----------|-----|
| Local (48GB Apple Silicon) | 640x368, 33 frames, 2.1s | Preview/iteration |
| Cloud (A100 80GB) | 832x480, 81 frames, 5s | Production render |

## Models

| Model | Purpose |
|-------|---------|
| Flux 2 Klein (GGUF) | Frame generation (first/last pairs) |
| WAN 2.1 I2V 14B (GGUF) | Video generation (image-to-video) |

**Full pipeline details:** `leviathan/VIDEO_PIPELINE_PROGRESS.md`

---

# RED FLAGS

## In Development

❌ "Marcus lost his brother" → Backstory, not behavior
❌ Stress behavior: "gets quiet" → Too generic
❌ All traits serve the theme → Character feels engineered
❌ No signature line → Character has no distinctive voice
❌ Theme articulated before characters exist → Theme-first error

## In Generated Scripts

❌ "I have calculated the optimal solution." → Generic AI dialogue
❌ "We need to move." → Could be any character
❌ "I trust you completely." (Ep 5) → Way too early
❌ "You can never trust machines." → Theme stated, not embodied
❌ Every episode at 7/10 intensity → Monotone register
❌ "kept since Episode 1" → Meta-reference (use "since the beginning")
❌ "The same hands that once held her throat..." → Unfilmable callback
❌ "In this moment, we see..." → Authorial voice leaking through

## In Emotional Beats

❌ "I love you" before Ep 40 → Unearned
❌ "You're my family" without prior sacrifice → Declared, not demonstrated
❌ First name use without earning → Milestone skipped

---

# THE GOAL

Scripts that are:
- **Structurally valid** (V12 constraints, patterns, format)
- **Dramatically alive** (specific characters, distinctive voices, earned emotions)

Mechanical QC catches structural issues.
Dramatic QC catches quality issues.

Both are necessary. Neither is sufficient alone.

---

---

# APPENDIX: DOCUMENTATION MAINTENANCE

## CONSTANTS.md — Single Source of Truth

All numeric values in the engine are centralized in `/CONSTANTS.md`:

| Category | Examples |
|----------|----------|
| Episode Constraints | Word count (450-500), dialogue max (40%), exchanges (8) |
| Pattern Distribution | Hook ratio (80/20), cliffhanger ratio (80/20) |
| Pilot Window | First 10 episodes rules |
| Treatment Constraints | Word counts by beat type |
| Series Structure | 60 episodes, generation batch (5), treatment batch (10) |
| Relationship Earning | Episode timing for declarations |

**When changing a numeric value:**
1. Update `/CONSTANTS.md`
2. Run `validate_docs.py` to find any hardcoded values
3. Fix any files still hardcoding the old value

---

## Documentation Consistency Checker

After any change to numeric values or terminology:

```
/validate-docs
/validate-docs --verbose
/validate-docs --fix-refs
```

Or run directly:
```bash
python3 /tools/validate_docs.py [options]
```

**Options:**
| Option | Description |
|--------|-------------|
| (none) | Check all docs, show only failures |
| `--verbose` | Show where canonical values appear (for auditing) |
| `--fix-refs` | Show which files need CONSTANTS.md references added |

**What it checks:**
- Outdated values (old word counts, renamed concepts)
- Terminology issues ("The Lens" → "Archetype-Worldview")
- Missing CONSTANTS.md references in key documents

**Exit codes:**
- `0` = PASS (all documents consistent)
- `1` = ISSUES FOUND (fix before proceeding)

**Skill reference:** `.claude/skills/validate-docs/SKILL.md`

---

## Terminology Reference

| Old Term | Current Term | Notes |
|----------|--------------|-------|
| The Lens | Archetype-Worldview | See `/appendix_d_ai_video.md` |
| 250-315 words | 450-500 words | See CONSTANTS.md |
| 280-350 validation | 450-500 validation | Updated range |
| 350-400 words | 450-500 words | See CONSTANTS.md |
| 330-420 validation | 450-500 validation | Updated range |
| 200-265 words (short-form) | 450-500 words | Short-form removed; all projects use standard |

---

## Adding New Numeric Constants

1. Add to `/CONSTANTS.md` with description
2. Add regex pattern to `validate_docs.py` CANONICAL_VALUES (if tracking needed)
3. Update any existing documents to reference CONSTANTS.md
4. Run `/validate-docs` to verify

---

## Documentation Maintenance Commands

| Command | Purpose |
|---------|---------|
| `/validate-docs` | Check numeric/terminology consistency |
| `/validate-docs --verbose` | Show all value locations |
| `/validate-docs --fix-refs` | Show files needing CONSTANTS.md refs |
| `/update-guides` | Sync guide content with engine changes |

---

*System version: V12 | Skills architecture | Last updated: 2026-01-29*
*Changes: Added Visual Design phase (Phase 9), Storyboard phase (Phase 10), Production phase (Phase 11), visual_bible_template.md, Flux 2 protocols (Appendix E), storyboard agent context expansion*
