# Generation Process

> **How to run a microdrama generation session.**
> **Numeric values:** See `/CONSTANTS.md`

---

## Initialization (Every Session)

Before generating ANY episodes:

### 1. Read Required Files

```
/skills/format_v12/SKILL.md           ← Format rules
/skills/dramatic_elements/SKILL.md    ← Hooks, cliffhangers
/skills/relationship_earning/SKILL.md ← Relationship timing
/[project]/ORCHESTRATION.md                   ← Project-specific content
/[project]/treatment.md                       ← MASTER prose treatment (generation input)
/[project]/scripting/bible/series_bible.md
/[project]/scripting/bible/characters.md      ← CRITICAL: Behavioral DNA for on-screen action
/[project]/_pipeline/state/current_state.json
```

### WHY characters.md IS CRITICAL

**Behavioral DNA constrains generation.** Without it, characters become generic.

| What It Contains | How You Use It |
|------------------|----------------|
| On-screen behaviors | Write these into action blocks — "Her fingers count unconsciously" |
| Stress behavior | Show when character is under pressure |
| Signature line | Include in dialogue (exact quote or variation) |
| Voice patterns | Maintain idiom in all dialogue |
| Anti-patterns | Things this character would NEVER say |

**The Contract:**
- Load `characters.md` at session start
- Reload between batches (prevents drift over long sessions)
- Show at least one behavioral DNA element per character per episode
- If you can't point a camera at it, it shouldn't be in the script

### 2. Establish Continuity

- Read last 2 completed episodes from `/scripting/episodes/`
- Note where we left off (tone, cliffhanger, character states)

### 3. Identify Next Batch

- Check `current_state.json` for `last_completed_batch`
- Next batch = `last_completed_batch + 1`
- Review batch schedule in project ORCHESTRATION.md for upcoming key events

---

## Batch Generation Loop

### Step A: Pre-Generation Planning

Before each batch:

**1. Extract batch from treatment.md:**
```bash
python3 /tools/extract_treatment_batch.py [project]/treatment.md [start] [end] --context
```

This gives you:
- Context window (Previously, This batch, Coming)
- Prose paragraphs for each episode
- THE MOMENT for each episode
- Cliffhanger images to hit

**2. For each episode in the batch, note:**
- [ ] **THE MOMENT** — What's the one beat that MUST land?
- [ ] **Prose paragraph** — What happens and why it matters (your content guide)
- [ ] **Cliffhanger image** — Specific visual/line to end on
- [ ] **Hook/Cliffhanger types** — Maintain distribution (70-85% SILENT, 70-85% MID-ACTION per `CONSTANTS.md`)
- [ ] **Thread markers** — What to PLANT/ADVANCE/PAYOFF this batch

**3. From Bible/State:**
- [ ] Current character voice stage (transformation arc position)
- [ ] Character behavioral DNA — what behaviors should show this batch?
- [ ] Relationship milestones — any earning opportunities?
- [ ] Cliffhanger variety (check last 2 episodes, don't repeat 3x)
- [ ] Hook type variety (same check)

### Step B: Generate Episodes

For each episode in the batch:

1. **Follow Kill Box structure** (see format_v12 skill)
   - HOOK → SETUP → ESCALATION → TURN → CLIFFHANGER

2. **Execute the treatment prose**
   - The prose paragraph is your PRIMARY content guide
   - What happens + why it matters emotionally
   - Key dialogue snippets to include

3. **Nail THE MOMENT**
   - This is the ONE beat that must land
   - If the script doesn't deliver THE MOMENT, it failed
   - Build toward it, don't bury it

4. **Hit the cliffhanger image**
   - End on the SPECIFIC visual/line from treatment
   - Not just "MID-ACTION" — the actual image

5. **Maintain character voice** per characters.md
   - Check voice stage for this episode range
   - Show behavioral DNA through ACTION (not exposition)

6. **Use granular sluglines** for distinct visual backgrounds

7. **Write shot-aware action blocks** (1-3 lines typical, 4 max — see format_v12 Action Block Architecture)

### Step C: Save and Verify Episodes

Save to `/scripting/episodes/ep_XXX.md` using format from format_v12 skill:

```markdown
# Episode [NUMBER]: [TITLE]

**Word Count:** [XXX]
**Dialogue:** [XX%]

---

[FOUNTAIN CONTENT]

---

**CLIFFHANGER TYPE:** [Mid-action/Aftermath] - [Category]
**NEXT:** [Brief setup for next episode]
```

**IMMEDIATELY after saving each episode, validate with episode_metrics.py:**

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

**Per-episode 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:
      ```bash
      python3 /tools/episode_metrics.py ./[project]/scripting/episodes/ep_XXX.md --prompt
      ```
   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 approach:**
- 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
- Batch validation becomes confirmation, not discovery

**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 Details

**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 fix workflow:**
1. If word count HIGH by N: Remove ~N words from action blocks
2. If word count LOW by N: Add ~N words of sensory detail
3. If exchanges HIGH: Consolidate dialogue (each character cue = 1 exchange)
4. Re-validate after each fix
5. Repeat until valid

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

### Step C-2: Cinematization Pass (After Each Episode Validates)

**After word count validation passes, run cinematization pass:**

1. **Scan for literary prose patterns:**
   - "He/She realized..." → Needs visual evidence
   - "Internal state like [metaphor]" → Needs physical reaction
   - "This was/wasn't [abstract noun]" → Needs evidence or dialogue
   - Backstory explanation in prose → Needs physical evidence or flashback
   - Psychology narration → Needs cut or transformation

2. **Transform to cinematic:**
   | Pattern | Transform To |
   |---------|--------------|
   | "The realization settled..." | Show what character SEES |
   | "Something like fear" | "His jaw tightens" |
   | "because X happened years ago" | Show scratch marks, age, physical evidence |
   | Character explaining motivation to person who knows | CUT or rephrase as question |

3. **Re-validate word count** (may have shifted slightly)

4. **Proceed to next episode** only after both metrics + cinematization pass

See `/skills/format_v12/SKILL.md` → CINEMATIZATION PASS section for full transformation strategies.

### Step C-3: Subtext Pass (After Cinematization)

**After cinematization pass, scan dialogue for on-the-nose lines:**

1. **Flag direct emotion statements:**
   - "I'm scared" → Deflect to trivial topic
   - "I love you" → Express through mundane concern ("Did you eat?")
   - "I'm angry" → Show through contradictory calm

2. **Flag direct answers to questions:**
   - "Are you okay?" / "No" → Evasion or answering different question
   - "Do you trust her?" / "No" → Indirect probe back

3. **Flag stated motivation:**
   - "I'm doing this because..." → Cut. Let action show motivation.

4. **Transform using subtext strategies:**
   | Technique | Example |
   |-----------|---------|
   | Deflection | Talk about something trivial instead |
   | Displacement | Express care through logistics |
   | Action | Fix something instead of apologizing |
   | Evasion | Answer a different question |
   | Contradiction | Behavior/tone opposes the words |

5. **Target ratio:** ~70% subtext, ~30% direct

See `/skills/format_v12/SKILL.md` → SUBTEXT PASS section for full examples.

### Step C-4: Transition Verification (After Each Episode)

**After writing each episode, verify transitions connect causally at both levels:**

The rule: **THEREFORE / BUT — Never "AND THEN"**

| Connector | Meaning | Quality |
|-----------|---------|---------|
| THEREFORE | Previous beat causes this beat | Good |
| BUT | This beat complicates/subverts the previous beat | Good |
| AND THEN | This beat merely follows chronologically | **Fix it** |

**Inter-episode check (hook vs previous cliffhanger):**
1. Does the hook acknowledge the previous cliffhanger's state?
2. Does a location change make spatial sense? (No teleportation)
3. If a new character appears, was their proximity established?
4. Does the emotional state carry across the boundary?

**Intra-episode check (Kill Box section boundaries):**
1. Does each section arise from the previous one? (HOOK→SETUP→ESCALATION→TURN→CLIFFHANGER)
2. Do stakes genuinely escalate, or is it the same level with new activity?
3. Watch for **convenience** — obstacles, locations, or characters that appear without setup to serve the plot

**If AND THEN:** Add a bridge line to motivate the transition, or modify the next section to establish the causal link. See `/appendix_a_cliffhangers_hooks.md` → Transition Logic.

**Note:** The Script Doctor (Pass 1: Structural) validates all transitions post-generation — both inter-episode (T-prefixed) and intra-episode (I-prefixed). But catching AND THEN transitions during generation is cheaper than fixing them later.

### Step D: Checkpoint Validation

After each batch of 5, run:

```bash
python3 .claude/hooks/save_checkpoint.py ./[project] [batch_number]
```

**Three-Gate Validation:**

| Gate | What It Checks | Fail Behavior |
|------|----------------|---------------|
| Gate 1: Mechanical | Word count, dialogue %, exchanges, format | Hard fail, must fix |
| Gate 2: Quality | Pattern variety, beats present, continuity | Hard fail, must fix |
| Gate 3: Dramatic QC | Voice, register, behavioral DNA, earning | Soft fail, flags for review |

**Deviation Auto-Regeneration (see `/DEVIATION_RULES.md`):**

When validation detects issues, follow the deviation protocol:
- **Word count over:** Regenerate with trim focus (max 2 attempts, then flag)
- **Word count under:** Regenerate until ≥450 (no limit)
- **Dialogue excess:** Regenerate with dialogue cap reminder
- **Pattern violation:** Regenerate with forced pattern interrupt
- **Voice drift:** Reload `characters.md` and regenerate

All deviations are logged to `state/deviation_log.json` for later review.

**Do NOT proceed to next batch until checkpoint passes (exit code 0).**

### Step D-3: Goal-Backward Check (Batches 3, 6, 9, 12 Only)

At these milestone batches, verify trajectory against arc goals:

```
1. Count threads resolved vs target (see CONSTANTS.md → Goal-Backward Verification)
2. Check emotional beats hit vs schedule
3. Calculate arc progress percentage
4. IF off-track:
   - Generate course correction recommendations
   - Log trajectory deviation
   - Adjust upcoming batch planning
```

**Verification Table (from CONSTANTS.md):**

| Batch | Episode | Threads | Emotional Beats |
|-------|---------|---------|-----------------|
| 3 | 15 | 0-1 | 2/11 |
| 6 | 30 | 2-3 | 5/11 |
| 9 | 45 | 4-5 | 8/11 |
| 12 | 60 | 6+ | 11/11 |

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

### Step D-2: Voice Contamination Check (Batches 3, 6, 9, 12 Only)

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

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

**Purpose:** Detect unintentional voice issues (not intentional evolution).

**What it checks:**
- **Contamination** — Character A using Character B's patterns
- **Generic drift** — Characters becoming too similar
- **Regression** — Sudden voice changes from previous batch

**If no issues detected:** Continue to next batch.

**If issues detected:**
- Script flags which characters have issues
- Triggers: `/dramatic-qc [project] --mode post --batch [N] --lens voice`
- Review flagged issues before continuing
- Decide: continue, rewrite, or flag for human review

### Step E: If Validation Fails

1. Read the failing episode(s)
2. Identify specific issues flagged
3. Rewrite to fix issues
4. Re-run checkpoint script
5. Repeat until ALL episodes pass

### Step F: After Checkpoint Clears

1. Update `/_pipeline/state/current_state.json`:
   - Increment `last_completed_batch`
   - Update character states
   - Note cliffhanger types used
   - Track pattern interrupt status

2. **MANDATORY: Reload context before next batch**

   After checkpoint passes, before generating the next batch, refresh these files:

   | File | Why |
   |------|-----|
   | `treatment.md` | Get content for next batch |
   | `characters.md` | Voice patterns drift over long sessions |
   | `format_v12/SKILL.md` | Refresh format rules (prevent rule drift) |
   | Last 2 completed episodes | Continuity anchoring |

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

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

3. Continue to next batch (return to Step A)

---

## Continuity Checks

Before proceeding to next batch, verify:

- [ ] All cliffhangers present and varied
- [ ] No broken cliffhanger chains (continuation resolves previous)
- [ ] Character voice matches transformation stage
- [ ] State file matches episode content
- [ ] Behavioral DNA showing in action
- [ ] Relationship earning on track

**If CRITICAL error:** STOP and report.
**If WARNING:** Note it and continue.

---

## Completion (After Episode 60)

1. **Run full transition gate:**
   ```bash
   python3 .claude/hooks/transition_gate.py ./[project]
   ```

2. **Run full dramatic QC:**
   ```bash
   python3 .claude/hooks/dramatic_qc_gate.py ./[project] --full
   ```

3. **Compile:**
   ```bash
   python3 /tools/compile_episodes.py ./[project]
   ```

4. **Output final summary report**

---

## Context Management

If context is getting long:

1. Complete current batch
2. Save all files
3. Run checkpoint script
4. Output: **"CHECKPOINT REACHED: Batch X complete. Resume with: 'Continue [project] generation.'"**

The user can start a new conversation and resume.

---

## CONTEXT COMPACTION PROTOCOL (CRITICAL)

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

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

### Why This Is Mandatory

Context compaction strips loaded files and summarizes instructions. Without reloading:
- `treatment.md` content is lost → generation becomes blind
- `characters.md` voice patterns are lost → voice drifts
- Format rules are summarized → constraints get paraphrased incorrectly
- Current position may be unclear → continuity breaks

### Detection

Context compaction has occurred if:
- Previous batch content is suddenly unclear
- You can't recall specific treatment prose for the current batch
- Character voice patterns feel vague or generalized
- Format rules seem summarized rather than detailed

### The Rule

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

This is non-negotiable. The reload takes ~30 seconds but prevents hours of drift-induced rewrites.

---

## Resumption Protocol

When resuming from checkpoint:

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

This triggers:
1. Read `/[project]/_pipeline/state/current_state.json`
2. Check `/[project]/scripting/episodes/` for existing episodes
3. Read last 2 completed episodes
4. Continue from next incomplete batch

---

## Autonomous Generation Protocol

When triggered with "Run autonomous generation for [project]":

```
REPEAT until Episode 60:
  1. Read current_state.json → identify next batch
  2. Read last 2 episodes for continuity
  3. Generate 5 episodes → save to /scripting/episodes/
  4. Run checkpoint validation
  5. IF validation fails:
     - Read failing episodes
     - Rewrite to fix issues
     - Re-run checkpoint
     - REPEAT until pass
  6. Update current_state.json
  7. MANDATORY RELOAD (prevents context drift):
     - Re-read treatment.md for next batch
     - Re-read characters.md
     - Re-read format_v12/SKILL.md
  8. IF CONTEXT COMPACTION DETECTED:
     - STOP current work
     - Run: /load-context [project] generate
     - Wait for "CONTEXT LOADED" confirmation
     - Resume from current position
  9. Report: "BATCH X VALIDATED. Continuing..."
  10. Loop back to step 1
END
```

**CRITICAL:**
- Do not skip validation
- Do not skip reload
- Do not proceed until checkpoint clears
- **After context compaction → `/load-context` → then continue**

---

## Quick Reference

```
SESSION START:
  1. /load-context [project] generate
  2. Read last 2 episodes
  3. Identify next batch

EACH BATCH:
  1. Plan (beats, variety, voice stage)
  2. Generate 5 episodes
  3. Save to /scripting/episodes/
  4. Run checkpoint
  5. Fix if needed
  6. Update state
  7. RELOAD CONTEXT (mandatory)
  8. Loop

CONTEXT COMPACTION:
  → STOP → /load-context [project] generate → Resume

CONTEXT LIMIT:
  → Complete batch → Save → Checkpoint → Report → User resumes

CLEAN CONTEXT ALTERNATIVE (/generate):
  → Use /generate-script [project] for fresh context each batch
  → After each batch: /compact → /generate-script [project]
  → Prevents drift, recommended for production

AUTONOMOUS GENERATION (/autogenerate):
  → Use /autogenerate-scripts [project] for continuous autonomous generation
  → Runs until Episode 60 or context compaction
  → Reloads context automatically between batches (no user intervention)
```

---

## Generation Skill Comparison

Two skills are available for episode generation:

### /generate — Clean Context Per Batch (Recommended for Production)

```
/generate-script [project]
  ↓
[Batch validates]
  ↓
"BATCH N COMPLETE. Run: /compact then /generate-script [project]"
  ↓
/compact
/generate-script [project]
  ↓
[Next batch...]
```

**Benefits:** Fresh context each batch, no drift risk, production quality.
**Trade-off:** Requires user to run `/compact` between batches.

See `.claude/skills/generate/SKILL.md` for full details.

### /autogenerate-scripts — Autonomous Continuous Generation

```
/autogenerate-scripts [project]
  ↓
[Batch 1 validates → auto-reload context → continue]
  ↓
[Batch 2 validates → auto-reload context → continue]
  ↓
... continues until Episode 60 or context compaction ...
  ↓
"SERIES COMPLETE" or "CONTEXT COMPACTED - run /load-context"
```

**Benefits:** Fully autonomous, no user intervention, fast.
**Trade-off:** Context accumulates (mitigated by mandatory reload between batches).

See `.claude/skills/autogenerate/SKILL.md` for full details.

---

*This skill is READ-ONLY process reference. Project-specific content lives in project ORCHESTRATION.md.*
