---
name: script-doctor
description: Full-series diagnostic via Gemini. Multi-pass architecture — Pass 1 checks inter-episode transitions (THEREFORE/BUT vs AND THEN), Pass 2 evaluates 6 series-level dimensions. Produces annotation-ready revision brief. Extracts annotations for /revise. Deep fix for structural P1s.
allowed-tools: Read, Bash, Glob, Grep
argument-hint: "[project] [--to-annotations|--verify|--deep-fix F00N|--dry-run|--focus dims]"
---

# /script-doctor - Series-Level Script Diagnostic

Sends the complete episode corpus + character bible + treatment to Google Gemini for full-series analysis. Produces a structured revision brief with annotation-ready findings — systemic issues that are invisible at the per-episode or per-batch level.

**This skill diagnoses. It does not modify episodes.** Findings extract to annotations for `/revise` (batch apply) or feed into `--deep-fix` (structural creative fixes) then `/rewrite`.

## Usage

```
/script-doctor [project]                       # Full diagnostic → brief with annotations
/script-doctor [project] --close-read          # Close-read only (7 batches, scene-level)
/script-doctor [project] --to-annotations      # Extract annotations from brief → annotations.json
/script-doctor [project] --deep-fix F002       # Creative fix for structural P1 finding
/script-doctor [project] --verify              # Post-revision verification pass
/script-doctor [project] --diagnose --dry-run  # Save payload without calling API
/script-doctor [project] --focus voice,arc_earning  # Focused diagnostic
```

**Examples:**
```
/script-doctor leviathan                       # Full diagnostic
/script-doctor leviathan --close-read          # Close-read only (scene-level, 7 batches)
/script-doctor leviathan --to-annotations      # Brief → annotations.json for /revise
/script-doctor leviathan --deep-fix F002       # Structural fix for unearned arc
/script-doctor leviathan --verify              # Verify previous fixes landed
/script-doctor leviathan --diagnose --dry-run  # Inspect prompt quality without API call
```

## Parameters

| Parameter | Required | Default | Description |
|-----------|----------|---------|-------------|
| `project` | Yes | -- | Project folder name |
| `--to-annotations` | No | false | Extract annotations from brief to `/revise` format |
| `--deep-fix` | No | -- | Finding ID (e.g., `F002`) for creative structural fix |
| `--verify` | No | false | Run verification pass (post-revision) |
| `--focus` | No | all | Comma-separated dimensions: `transitions,voice,pattern_fatigue,arc_earning,continuity,texture_tone_vitality,exposition_load` |
| `--close-read` | No | false | Run close-read pass only (7 batches with 2-ep overlap, scene-level analysis: spatial logic, motivation, transitions, physical consistency, filmability) |
| `--dry-run` | No | false | Save payload to file instead of calling Gemini API |
| `--model` | No | gemini-3.1-pro-preview | Override Gemini model |
| `--bundle` | No | false | Preview corpus payload (stats + save to file) |

## Prerequisites

- All episodes must be generated (checks `[project]/scripting/episodes/` for complete set)
- Gemini API key configured (see Setup below)
- `google-generativeai` Python package installed

## Setup

```bash
# Install Gemini SDK
pip install google-generativeai

# Set API key (add to shell profile for persistence)
export GEMINI_API_KEY="your-key-here"
```

## Multi-Pass Architecture

The script doctor runs in multiple internal passes, producing a single combined brief:

### Pass 1: Structural (Transitions — Inter + Intra)

Checks transitions at TWO levels in a single Gemini call:

**THE RULE: THEREFORE / BUT — NEVER "AND THEN"**

| Connector | Meaning | Quality |
|-----------|---------|---------|
| **THEREFORE** | Previous beat causes/necessitates the next | Good |
| **BUT** | Next beat complicates/subverts expectations | Good |
| **AND THEN** | Next beat merely follows chronologically, no causal link | **Failure** |

**Inter-episode** (59 boundaries): Checks every cliffhanger→hook boundary. Also checks spatial continuity, character positioning, emotional carry-over, off-screen resolution. Findings use T-prefixed IDs (T001, T002...).

**Intra-episode** (240 boundaries): Checks every Kill Box section boundary within each episode (HOOK→SETUP→ESCALATION→TURN→CLIFFHANGER). Flags convenience — obstacles, locations, or characters that appear without setup to serve the plot. Findings use I-prefixed IDs (I001, I002...).

Both sort first in the brief (structural before series-level).

### Pass 2: Series-Level (6 Dimensions)

Evaluates across 6 series-level dimensions (different from the 7 per-batch lenses used by `/assess`):

| Dimension | What It Catches | Example |
|-----------|----------------|---------|
| **voice** | Drift, convergence, calcification, "never say" violations | Jinx and Kian both using analytical language by Act 3 |
| **pattern_fatigue** | Catchphrase overuse, tic repetition, idiom loops, rhythm monotony | "sixty-forty" appears 28 times across 60 episodes |
| **arc_earning** | Transformations + relationships: missing beats, unearned shifts | Varek jumps from Disillusionment to Altruism without bridge |
| **continuity** | Thread integrity, planted-but-unresolved, knowledge consistency | Thread planted in ep 12 never pays off |
| **texture_tone_vitality** | Kill Box fatigue, breathing room, surprise, humor, play, fun | Every episode ending mid-action creates relentless rhythm |
| **exposition_load** | Dialogue-as-narration, "as you know" patterns, missed visual storytelling | Characters explaining what the audience can see |

Plus **uncategorized** for anything that doesn't fit.

### Pass 3: Close Read (batched scene-level)

Runs in `--full` mode as Phase 4 (or standalone with `--close-read`). Sends episodes in 7 batches of ~10 with 2-episode overlap:

| Check | Severity | What It Catches |
|-------|----------|-----------------|
| **spatial_logic** | P1 | Characters teleporting between levels/locations with no travel |
| **motivation** | P1/P2 | Major decisions with no visible reason; internal narration as motivation |
| **transition** | P1/P2 | Physical/spatial gaps between consecutive episodes |
| **physical_consistency** | P2 | Objects disappearing, injuries not carrying forward |
| **filmability** | P2 | Internal narration, authorial voice, non-camera-visible prose |

Findings use C-prefix IDs (C001, C002...) with dimension `close_read`.

### Why This Order

Structural fixes ADD text (bridge lines, modified hooks/cliffhangers). Close-read validates that text makes spatial and logical sense. Series-level evaluates voice, arc, and pattern across the full corpus. Structural → close-read → series-level.

## Output

### Diagnostic Brief (v2)

Saved to `[project]/_pipeline/state/script_doctor_brief.json`:

```json
{
  "version": "2.0",
  "project": "leviathan",
  "generated": "2026-01-31T...",
  "model": "gemini-2.5-pro",
  "summary": "Overall series assessment...",
  "findings": [
    {
      "id": "F001",
      "dimension": "pattern_fatigue",
      "severity": "P1",
      "title": "Jinx 'sixty-forty' overuse",
      "description": "Catchphrase appears in 28 of 60 episodes...",
      "episodes": [1, 4, 7, 14, 20, 24, 25, 29],
      "annotations": [
        {
          "episode": 4,
          "line": 0,
          "action": "REWRITE",
          "selected_text": "Sixty-forty we make it through this.",
          "note": "[F001/P1] Catchphrase overuse. Replace with gambler alternative: 'Stack's getting thin, glitch.'"
        }
      ]
    }
  ],
  "character_grades": { "JINX": { "grade": "B", "arc_summary": "..." } },
  "stats": { "total_findings": 12, "p1_count": 3, "p2_count": 5, "p3_count": 4 }
}
```

### Deep Fix Output

Saved to `[project]/_pipeline/state/deep_fix_F002.json`:

```json
{
  "finding_id": "F002",
  "fix_strategy": "Add transactional bridge scene between ep 41 and ep 54",
  "bridge_content": [
    {
      "episode": 49,
      "insert_after": "Exact quote from episode",
      "new_content": "150-200 word scene draft",
      "purpose": "Establishes mutual dependency through shared survival"
    }
  ],
  "rewrite_guidance": [...],
  "continuity_check": "Downstream impact description",
  "behavioral_dna_alignment": "How fix uses character logic"
}
```

## Execution

When this skill is invoked:

1. **Read the agent protocol:** `/agents/script_doctor_agent.md`
2. **Follow the protocol exactly** — it defines corpus bundling, Gemini interaction, brief generation, annotation extraction, deep fix, and verification flows

## The Revision Loop

### Standard Flow

```
/script-doctor leviathan                       # Step 1: Diagnostic → brief with annotations
  → Review the brief, approve/reject findings
/script-doctor leviathan --to-annotations      # Step 2: Extract → annotations.json
/revise leviathan script_doctor_annotations.json  # Step 3: Batch apply via /revise
/script-doctor leviathan --deep-fix F002       # Step 4: Creative fix for structural P1s
/script-doctor leviathan --verify              # Step 5: Confirm fixes landed
```

This is the **primary workflow**. REWRITE and DELETE annotations are handled efficiently in batch by `/revise`. FLAG annotations from structural findings (arc, pacing) get addressed via `--deep-fix` + `/rewrite`.

### Verification Loop

If verification finds remaining issues:
1. Re-extract annotations for unresolved findings
2. Run another `/revise` pass
3. Verify again

### Dry Run Workflow

To inspect prompt quality before committing API calls:

```
/script-doctor leviathan --diagnose --dry-run  # Save diagnostic payload
/script-doctor leviathan --deep-fix F002 --dry-run  # Save deep fix payload
```

Payloads save to `[project]/_pipeline/state/` as `.txt` files for manual inspection.
