#!/usr/bin/env bash
# rap-avatar-mv — MASTER gated step-runner.
#
# Advances the whole rap-MV pipeline but PAUSES at every human gate (exit 10).
# Do the manual/creative work the gate prints, then re-run the SAME command:
# re-run IS approval. Completed stages are recorded in build/rap-state and
# skipped. To re-roll a PAID artifact (song / hero clip / scene clip), DELETE the
# artifact and re-run — nothing that already exists is ever re-bought.
#
# Usage:  make-rap-mv.sh <pack> <slug> [--restart] [--from <stage>] [--replace wNN[,wNN]]   (--replace rewinds to preflight)
set -euo pipefail
_ARGV=("$@")                 # the call as made: the snapshot re-exec below replays it verbatim
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=lib/common.sh
source "$HERE/lib/common.sh"
load_env

PACK="${1:-}"; SLUG="${2:-}"; shift 2 || true
[ -n "$PACK" ] && [ -n "$SLUG" ] || die "usage: make-rap-mv.sh <pack> <slug> [--restart] [--from <stage>] [--replace wNN[,wNN]]"

STAGES="scaffold lyrics song map hook stem styles plan shot-refs vocal-map broll-plan inventory preflight first-take render-all library transcribe select slide needs cover cut audio-swap sync-gate board meta bookends captions polish preview deliver qc"
RESTART=0; FROM=""; REPLACE=""; UNTIL=""
while [ $# -gt 0 ]; do
  case "$1" in
    --restart) RESTART=1;;
    --from) FROM="${2:-}"; [ -n "$FROM" ] || die "--from needs a stage name"; shift;;
    --replace) REPLACE="${2:-}"; [ -n "$REPLACE" ] || die "--replace needs wNN[,wNN]"; shift;;
    --until) UNTIL="${2:-}"; [ -n "$UNTIL" ] || die "--until needs a stage name"; shift;;
    *) die "unknown flag: $1";;
  esac
  shift
done
if [ -n "$FROM" ]; then
  case " $STAGES " in *" $FROM "*) ;; *) die "--from '$FROM' is not a stage. Stages: $STAGES";; esac
fi
if [ -n "$UNTIL" ]; then
  # --until <stage>: stop, exit 0, the moment that stage is marked done. The fixture proof
  # plans a synthetic film (through broll-plan), synthesises its clips from the plan,
  # then runs the rest — it must never reach first-take, which submits a real render.
  case " $STAGES " in *" $UNTIL "*) ;; *) die "--until '$UNTIL' is not a stage. Stages: $STAGES";; esac
fi

load_preset "$PACK"
# THE FILM'S AUDIO MODE IS THE PLAN'S, once a plan exists (make_plan records it with the
# other constants); the pack's AUDIO_MODE only until then. Every per-mode branch below
# asks film_mode, so a gate is never told the mode by a flag the runner had to remember.
film_mode() {
  # the plan's own constants.audioMode; a plan made before constants travelled on it
  # (2026-09-02) carries none, and the PACK's AUDIO_MODE is then the truth — an empty
  # answer must not read as record mode
  local f="$P/build/plan.json" m=""
  if [ -s "$f" ]; then
    m=$(python3 -c 'import json,sys; print(((json.load(open(sys.argv[1])).get("constants") or {}).get("audioMode") or "").strip())' "$f" 2>/dev/null)
  fi
  echo "${m:-${AUDIO_MODE:-record}}"
}
P="$(project_dir "$SLUG")"
load_video_env "$P"
# THE OPERATOR'S CLOCK IS THE FILM'S. COVER_SPANS / VOCAL_SWAP_KEEP_RECORD may be given on
# QuickTime's clock ("1:48-1:53"); the tools subtract the title card from the previous
# delivery's cards.json when it exists (film3 item 6). A fresh film has no cards yet:
# song seconds then, and the parser says so.
cards_args=()
[ -f "$P/build/bookends/cards.json" ] && cards_args=(--cards "$P/build/bookends/cards.json")
require_consent

STATE="$P/build/rap-state"
# references/ holds the portrait, the keyframes and lyrics.txt. `vclaw video init`
# does not create it, so the very first gate — "write references/lyrics.txt" —
# was an instruction the operator could not follow as printed.
mkdir -p "$P/build" "$P/references"
# RUN FROM A SNAPSHOT OF THE SCRIPTS. bash reads a script incrementally and python
# reads a helper when it is invoked, so an edit to the live scripts mid-run changed
# what a running runner did next — it bit us today. THE RUNNER FILE ITSELF IS NOT
# "already loaded": bash keeps reading it by offset, and a rewrite mid-run had a film
# run execute a fragment of a comment ("evel: command not found", v8 14:32; "stops",
# the duet fixture 19:08, 2026-09-02). So once the copy exists the runner re-executes
# ITSELF from it (below) and the live file is free to edit. The python helpers and
# anything `source`d come from the same copy, keyed on the scripts' content. The copy mirrors the repo depth
# with symlinks (skills/<other>, engines/, dist/, scripts/ ...) because several
# helpers locate the repo root from their own __file__ — a flat copy would put them
# three levels under build/ and they would resolve nothing. A runner already running
# from a snapshot (dryrun.sh re-entering the runner) keeps the snapshot it has.
case "$HERE" in *"/.runner-cache/rap-avatar-mv/"*|*"/runner-snapshot/"*) ;; *)
  _snap_hash=$(cat "$RAP_SCRIPTS/make-rap-mv.sh" "$RAP_SCRIPTS"/*.py "$RAP_SCRIPTS"/*.sh "$RAP_SCRIPTS"/lib/*.sh 2>/dev/null | md5 -q)
  _repo="$(cd "$RAP_SKILL_DIR/../.." && pwd)"
  # ONE SHARED, CONTENT-ADDRESSED CACHE for every film (operator, 2026-09-05: "is there a
  # better way than copying all?"): the same scripts hash to the same folder, so twenty films
  # share one 2 MB copy instead of each keeping its own pile under build/. The copy is still
  # taken from DISK (a run must be able to carry an uncommitted fix), and the git commit +
  # dirty flag are logged so every run can be traced to code.
  _snap="${VCLAW_WORKSPACE:-$HOME/videoclaw}/.runner-cache/rap-avatar-mv/$_snap_hash"
  mkdir -p "$_snap/skills/rap-avatar-mv"
  rsync -a --delete --exclude '__pycache__' "$RAP_SCRIPTS/" "$_snap/skills/rap-avatar-mv/scripts/"
  for _e in "$_repo"/* "$_repo"/.[!.]*; do
    [ -e "$_e" ] || continue
    _n="$(basename "$_e")"
    case "$_n" in skills|.git) continue;; esac
    [ -e "$_snap/$_n" ] || ln -s "$_e" "$_snap/$_n"
  done
  for _e in "$_repo"/skills/*; do
    _n="$(basename "$_e")"
    [ "$_n" = "rap-avatar-mv" ] && continue
    [ -e "$_snap/skills/$_n" ] || ln -s "$_e" "$_snap/skills/$_n"
  done
  for _e in "$RAP_SKILL_DIR"/*; do
    _n="$(basename "$_e")"
    [ "$_n" = "scripts" ] && continue
    [ -e "$_snap/skills/rap-avatar-mv/$_n" ] || ln -s "$_e" "$_snap/skills/rap-avatar-mv/$_n"
  done
  RAP_SCRIPTS="$_snap/skills/rap-avatar-mv/scripts"
  RAP_REFS="$_snap/skills/rap-avatar-mv/references"
  export RAP_SCRIPTS
  _git_head="$(git -C "$_repo" rev-parse --short HEAD 2>/dev/null || echo unknown)"
  _git_dirty="$([ -n "$(git -C "$_repo" status --porcelain -- "$RAP_SCRIPTS" 2>/dev/null)" ] && echo " + UNCOMMITTED edits" || echo "")"
  log "scripts snapshot: $RAP_SCRIPTS (edits to the live scripts cannot reach this run; git $_git_head$_git_dirty)"
  # HOUSEKEEPING (operator, 2026-09-05: "there must be a better way" — 20 snapshot folders and
  # 57 pass logs had piled up in one day). A snapshot is only worth keeping while a run uses
  # it: drop every other one except those a live process is running from, and keep only the
  # newest RUNNER_LOG_KEEP (default 5) runner-pass*.log files — project-audit.jsonl is the
  # durable record, the pass logs are scratch.
  _live_snaps="$(ps -eo args 2>/dev/null | grep -oE "\.runner-cache/rap-avatar-mv/[0-9a-f]{32}" | sort -u || true)"
  for _d in "$(dirname "$_snap")"/*/; do
    [ -d "$_d" ] || continue
    _h="$(basename "$_d")"
    [ "$_h" = "$_snap_hash" ] && continue
    case "$_live_snaps" in *"$_h"*) continue;; esac
    rm -rf "$_d"
  done
  # (`|| true`: with no pass logs yet `ls` exits 2 and pipefail would end the runner here)
  { ls -t "$P"/build/runner-pass*.log 2>/dev/null | tail -n +$(( ${RUNNER_LOG_KEEP:-5} + 1 )) | while read -r _old; do rm -f "$_old"; done; } || true
  # ... and run the rest of THIS FILE from the copy too (see above). Same argv, same
  # environment; `HERE` then sits under runner-snapshot and this block is skipped.
  exec bash "$_snap/skills/rap-avatar-mv/scripts/make-rap-mv.sh" "${_ARGV[@]}"
esac
[ "$RESTART" = "1" ] && : > "$STATE"
touch "$STATE"
# build/STOP is the polite stop (lane_render ends its pass at the next boundary). While it
# exists the runner will not start: a resume is an explicit act, not an accident.
[ -f "$P/build/STOP" ] && die "build/STOP is present — the last pass was stopped on purpose. rm '$P/build/STOP' and re-run to resume."
# --replace wNN: re-render surgery the runner owns. Every hand-driven re-render on the
# last film meant deciding which artifacts to void and where to rewind — and the rewind
# point was gotten wrong twice in one day. replace_window.py encodes the dependency
# table (park the clip AND its job record AND the operator cut files; void everything
# derived from the clip set; leave the content-keyed and versioned artifacts alone),
# then the normal --from machinery rewinds to render-all, which renders only what is
# missing.
if [ -n "$REPLACE" ]; then
  [ -z "$FROM" ] || die "--replace implies --from preflight; do not pass both"
  # --replace RENDERS ONLY THE NAMED WINDOW(S). While the plan still has windows that
  # have never landed, that turns one stubborn window into a wall: film #3's w06 was
  # replaced ahead of the list, kept failing moderation, and the runner retried it
  # alone for four hours while 23 windows waited (2026-09-04). Walk the list first — a
  # plain re-run renders what is missing — and replace at the END, when what is
  # missing is a decision. RAP_REPLACE_ANYWAY=1 is the deliberate override.
  if [ "${RAP_REPLACE_ANYWAY:-0}" != "1" ] && [ -f "$P/build/plan.json" ]; then
    _pending="$(python3 - "$P/build/plan.json" "$REPLACE" <<'PYPEND'
import json, os, sys
plan = json.load(open(sys.argv[1], encoding="utf-8"))
skip = set(sys.argv[2].split(","))
clips = os.path.join(plan.get("queueDir") or os.path.join(os.path.dirname(sys.argv[1]), "queue", "explore"), "clips")
print(",".join(j["id"] for j in plan["jobs"]
               if j["id"] not in skip and not j.get("deferred")
               and not os.path.isfile(os.path.join(clips, j["id"] + ".mp4"))))
PYPEND
)"
    [ -z "$_pending" ] || die "--replace $REPLACE would render ONLY that window while these have never landed: $_pending
  Walk the list first (a plain re-run renders what is missing), then replace at the end.
  RAP_REPLACE_ANYWAY=1 overrides this on purpose."
  fi
  python3 "$RAP_SCRIPTS/replace_window.py" --project "$P" --windows "$REPLACE" \
    || die "replace refused — nothing was changed"
  # ... from PREFLIGHT, not render-all: a replaced window usually has a changed prompt,
  # and lane_render rightly refuses a take whose contract moved since approval. Rewound
  # to render-all, that refusal landed nothing, "some windows did not render"
  # auto-passed, and select_cut refused a cut with no w09 (Baby Ram & Sita v8,
  # 2026-09-02). Preflight rebuilds the window's contract and re-approves it on the
  # same path every contract takes.
  FROM="preflight"
  RENDER_ONLY="$REPLACE"      # that window, not everything the plan lacks (see render-all)
fi
if [ -n "$FROM" ]; then
  # Everything before $FROM is done BY POSITION (an unmarked earlier stage is announced,
  # never re-run); $FROM and everything after it is dropped. See lib/common.sh.
  # shellcheck disable=SC2086
  state_rewind_to "$STATE" "$FROM" $STAGES || die "--from '$FROM' is not a stage"
fi

done_stage(){ grep -qx "$1" "$STATE" 2>/dev/null; }
# The cutaway record for a style: its own file, or the pre-2026-08-29 shared one when
# only that exists (a film cut before the fix still gates against its record).
cutaways_for(){
  if [ -f "$P/build/cutaways-$1.json" ]; then printf '%s' "$P/build/cutaways-$1.json"
  elif [ -f "$P/build/cutaways.json" ]; then printf '%s' "$P/build/cutaways.json"; fi
}
mark(){
  grep -qx "$1" "$STATE" 2>/dev/null || echo "$1" >> "$STATE"
  if [ -n "${UNTIL:-}" ] && [ "$1" = "$UNTIL" ]; then
    log "--until $UNTIL: stopping here (stage marked done; re-run without --until to continue)"
    exit 0
  fi
}
# The styles every per-style stage iterates. styles-effective.json exists only when the
# `select` stage proved the drawn styles produced IDENTICAL selections — with one clip
# per window there is nothing for a "variant" to vary, and the loop then built the same
# film N times under N names (measured: six byte-identical 112MB deliverables, and the
# operator had to ask which file to send). The effective list collapses that to one.
film_styles(){
  local src="$P/build/styles-drawn.json"
  [ -f "$P/build/styles-effective.json" ] && src="$P/build/styles-effective.json"
  python3 -c "import json;print(' '.join(s['id'] for s in json.load(open('$src'))['styles']))"
}
# Every DRAWN style, ignoring a previous collapse. The select stage must re-select all
# of them so collapse_styles compares fresh selections: on New Era (2026-08-31) it
# selected the one collapsed style, compared it with five stale selections from the
# night before, un-collapsed, and the cut stage walked into the stale files.
drawn_styles(){
  python3 -c "import json;print(' '.join(s['id'] for s in json.load(open('$P/build/styles-drawn.json'))['styles']))"
}

: "${ASPECT:=9:16}"
# FULL TRACK IS THE DEFAULT. It was opt-in, and HOOK_SECONDS defaulted to 8 — so a
# pack that simply did not mention either produced an EIGHT-SECOND FILM from a
# two-minute song, silently. The two failure modes are not symmetrical: accidentally
# covering the whole song costs render time you can see coming, while accidentally
# covering 26% of it produces a finished, plausible, wrong film that no gate catches.
# A music video of a song should be the song unless someone says otherwise.
: "${HOOK_FULL_TRACK:=1}"
# VOCAL_BRIEF_MIN_RATIO (pack, default 0.45): how close whisper's hearing must be to a
# sheet line before the brief places it. A line under the bar is "not heard", its window
# becomes no-voice, and plan_coherence refuses the plan when the song sings there (film #3:
# "Jai Hanuman gyaan gun saagar" heard as "jai lisa jai hanuman gyan gansagar" by BOTH
# ears, ratio 0.41). Lower it per film, then read vocal-brief.html for false placements.
# The whisper model behind the song map, the vocal map and the slice check. `small` is
# the lane's calibrated default (sung timings). `medium` hears a chanted intro and a
# spoken number that small dropped or mis-timed (New Era, 2026-08-29: "a hundred
# ninety-one" placed 1.4 s late, two voice slices refused at preflight) — set it in the
# pack when the map's alignment ratios come back low. lane_render's per-draw judge keeps
# its own (faster) model.
: "${WHISPER_MODEL:=small}"
: "${WHISPER_ENGINE:=openai}"
whisper_engine_setup "$RAP_SCRIPTS"
whisper_engine_check "$P/build" "$WHISPER_ENGINE"
# Only meaningful when HOOK_FULL_TRACK=0. No default: if you are cutting a window out
# of a track, its length is a decision, not something to inherit.
if [ "${HOOK_FULL_TRACK}" = "0" ] && [ -z "${HOOK_SECONDS:-}" ]; then
  die "HOOK_FULL_TRACK=0 means the film is a WINDOW of the song, so the pack must set
  HOOK_SECONDS to its length. Unset HOOK_FULL_TRACK (or set it to 1) to cover the
  whole track instead."
fi
: "${HOOK_SECONDS:=0}"
: "${STYLE_COUNT:=2}"
: "${MV_FPS:=24}"
: "${BROLL_DIR:=$P/build/broll/clips}"
# ONE CUTAWAY PER WORLD, not just per gap. Three cutaways covered seven windows on the
# nineties film and the operator saw the same three shots come round ("add more brolls
# as you repeating alot", 2026-08-29). Each world gets its own; cover picks same-world
# first. BROLL_EVERY_STYLE=0 restores the gaps-only plan.
: "${BROLL_EVERY_STYLE:=1}"
: "${SCENE_SECONDS:=14}"   # a LIP-SYNCED window maxes at 14s: the voice counts twice against the provider's 30s audio budget
# WHAT THE MODEL HEARS. `mix` cuts every voice slice from hook.wav — the whole track,
# bed and all; `stem` cuts it from the Demucs vocal stem the `stem` stage writes. The
# published Seedance guidance ("dense mixes give the model no clock") and the nineties
# film (three draws of w11 sang the right words at the wrong rhythm against the mix,
# 2026-08-29) both point at the mix. `mix` stays the default until the A/B says so.
: "${VOICE_SOURCE:=mix}"
case "$VOICE_SOURCE" in mix|stem) ;; *) die "VOICE_SOURCE must be mix or stem, got '$VOICE_SOURCE'";; esac
# Where a sung WORD ENDS (`e` on every word in song-words.json / stem-words.json): stem
# MEASURES it from the vocal stem's RMS (the template's default); gemini hears the audio
# and answers per word (measured ~0.9 s late before silences — selectable, not default);
# whisper keeps whisper's own ends, which tile to the next onset. A pack WITHOUT the
# variable behaves as whisper, so every film planned before this keeps its plan.hash.
: "${WORD_ENDS:=whisper}"
case "$WORD_ENDS" in gemini|stem|whisper) ;; *) die "WORD_ENDS must be gemini, stem or whisper, got '$WORD_ENDS'";; esac
# THE PAID DOOR, one window at a time. PAID_WINDOWS="w05,w11" (pack) sends each named
# window the free lane did not land to the Higgsfield API pool through the official CLI
# (`paid_take.py`: quoted by `generate cost`, bound to the SAME approved contract, judged
# by the same judge). The free lane stays the default; a paid take is the operator's
# call per window, never a batch, and never on the standing word (see render-all).
: "${PAID_WINDOWS:=}"
VOICE_WAV="$P/build/hook.wav"
[ "$VOICE_SOURCE" = "stem" ] && VOICE_WAV="$P/build/stems/vocals.wav"
# ONE CLOCK. Every sung prompt used to carry a timestamp list ("0.1–5.8s the lead
# voice sings …") beside the audio reference — the "second timing system" the Seedance
# guidance says to avoid, and w11 sang the right words at the wrong rhythm three times
# with it (2026-08-29). PROMPT_TIMESTAMPS=0 (the default) quotes the lines in order
# and names no seconds; =1 restores the timestamped script (the A/B's control arms).
: "${PROMPT_TIMESTAMPS:=0}"
PROMPT_CLOCK_ARGS=()
[ "$PROMPT_TIMESTAMPS" = "0" ] && PROMPT_CLOCK_ARGS=(--no-timestamps)
# The length of ONE CLIP, which is NOT the length of the film. They coincide only
# while the whole film fits in a single shot (HOOK_SECONDS <= the route's cap). A
# full-track hook is many clips, and feeding HOOK_SECONDS to the prompt composer
# then embedded "Audio 1 is the 191.5-second rap track" into every prompt while the
# thing actually being submitted was 8 seconds long. Always the smaller of the two.
CLIP_SECONDS="$SCENE_SECONDS"
# Only clamp when the film is a WINDOW shorter than one clip. On a full-track film
# HOOK_SECONDS is 0 (the length is the song's, not known until the song exists), and
# clamping to it would set every clip to zero seconds.
if [ "${HOOK_FULL_TRACK}" != "1" ]; then
  awk -v h="$HOOK_SECONDS" -v c="$SCENE_SECONDS" 'BEGIN{exit !(h>0 && h<c)}' && CLIP_SECONDS="$HOOK_SECONDS"
fi
# What the gates SAY the film is, so a message never reads "inside 0s".
FILM_LENGTH_NOTE="the whole song"
[ "${HOOK_FULL_TRACK}" != "1" ] && FILM_LENGTH_NOTE="the ${HOOK_SECONDS}s hook window"
STYLE_STATE="$P/build/style-bag.json"
# A pack may ship its own style set when the generic rap-MV register does not fit
# the subject (e.g. a club anthem performed in club kit). Absolute path, or a
# filename resolved against the packs dir.
: "${STYLES_FILE:=$RAP_REFS/styles.json}"
[ -f "$STYLES_FILE" ] || STYLES_FILE="$VCLAW_PACKS/$STYLES_FILE"
[ -f "$STYLES_FILE" ] || die "STYLES_FILE not found: ${STYLES_FILE}"
SONG="$P/artifacts/audio/soundtrack-suno.mp3"
TRANSCRIPT="$P/build/transcript.json"
HOOK_JSON="$P/build/hook.json"
# Operator overrides — which window was swapped by hand and WHY — as data beside
# the selection, so a version bump is an edit to a JSON file rather than an edit to
# a build script. Absent is normal and means "no hand overrides this version".
OVERRIDES="${OVERRIDES:-$P/build/overrides.json}"

# ---- 1. scaffold -----------------------------------------------------------
if ! done_stage scaffold; then
  # The route was a hardcoded literal here, so a pack on the free Runway lane was
  # announced as veo-useapi on every run — a log line contradicting its own pack.
  log "scaffold: $SLUG (route ${ROUTE:-veo-useapi}, aspect $ASPECT)"
  # Test for project.json, NOT the directory: this runner creates $P/build for
  # its state file before this stage runs, so a directory test is always true and
  # `vclaw video init` would never fire (caught on the first real project).
  [ -f "$P/project.json" ] || node "$MAIN/dist/cli/vclaw.js" video init "$SLUG" --mode storyboard \
    --root "$VCLAW_WORKSPACE" >/dev/null
  mark scaffold
fi

# ---- 2. lyrics (gate) ------------------------------------------------------
if ! done_stage lyrics; then
  [ -f "$P/references/lyrics.txt" ] || gate "write the rap lyrics" \
"Write $P/references/lyrics.txt — a 4-8 bar hook, in YOUR OWN WORDS.
  * The film covers ${FILM_LENGTH_NOTE}; write enough words for it.
  * Suno's copyright filter matches the LINE, so never reuse an existing lyric.
  * Open on impact; the first bar is what the opening clip will carry.
  See references/song-recipe.md."
  # THE SHEET MUST BE ROMANISED. The ear, the aligner and the judge read Latin letters;
  # a Devanagari sheet cost film #2 its first stage and surfaced three stages later as
  # "singer_diarize failed — need at least one array to stack" (film3 item 8).
  RAP_SCRIPTS="$RAP_SCRIPTS" python3 - "$P/references/lyrics.txt" <<'PYSHEET' || die "the lyric sheet is not romanised (see above)"
import os, sys
sys.path.insert(0, os.environ["RAP_SCRIPTS"]); import raplib
latin, total = raplib.sheet_latin_share(sys.argv[1])
if total and latin * 2 < total:
    sys.exit(f"lyrics: {total - latin} of {total} lines have no Latin letters — the sheet must be romanised "
             f"(Aam ko chhoo loon, not आम को छू लूँ); keep the Devanagari in a separate file if you want it")
PYSHEET
  mark lyrics
fi

# ---- 3. song (paid; gate once; re-run = approve) ---------------------------
if ! done_stage song; then
  # A FILM THAT COPIES A REAL RECORDING buys nothing: SOURCE_URL (pack) ingests the original
  # into references/source.{mp4,wav,-silent.mp4,json} and writes its audio as $SONG, so the
  # buy below is skipped. Also the picture the shot references and the dance breakdown
  # read (SHOT_REFS_VIDEO defaults to references/source.mp4). SOURCE_COOKIES=chrome opts
  # into yt-dlp's browser cookies (a Keychain prompt on macOS).
  if [ -n "${SOURCE_URL:-}" ] && [ ! -f "$SONG" ]; then
    log "song: ingesting the source recording from SOURCE_URL"
    python3 "$RAP_SCRIPTS/ingest_source.py" --project "$P" --url "$SOURCE_URL" \
      ${SOURCE_COOKIES:+--cookies-from-browser "$SOURCE_COOKIES"} \
      || die "the source could not be ingested (see above) — fix SOURCE_URL, or unset it to buy a song"
    gate "approve the source" \
"Watch it: open '$P/references/source-silent.mp4' (silent, 720p) and play '$SONG'.
  * This recording IS the film's song and the picture its shots follow.
  * Wrong video? DELETE references/source.* and '$SONG', fix SOURCE_URL, re-run.
Re-run to approve."
  fi
  if [ ! -f "$SONG" ]; then
    log "song: kie.ai Suno (SONG_STYLE=${SONG_STYLE:-<unset>})"
    "$MAIN/skills/rhyme-factory/scripts/make-song.sh" "$SLUG" "$PACK"
    gate "approve the song" \
"Play it: open '$SONG'
  * Does it actually have a HOOK? The whole film is cut from the loudest, most
    repeated section — a song with no hook produces a dead clip.
  * Not right? DELETE the mp3 and re-run to buy another take.
Re-run to approve."
  fi
  # Outside the guard on purpose: the gate above only fires on the pass that BUYS the
  # song, so the re-run finds the file present, skips the inner block, and marks here.
  mark song
fi

# ---- 4. map (whisper the song — real onsets, never guessed) ----------------
if ! done_stage map; then
  require_whisper
  # --word_timestamps True, ALWAYS. Two stages need word-level times and both fall back
  # silently without them, which is how a film shipped with the wrong captions:
  #
  #   captions   line_subs gives each lyric line its own in and out. Without word times
  #              it falls back to make_subtitles, which keeps whisper's SEGMENT text —
  #              and whisper's segments over a silent outro contained "Thank you for
  #              watching!", which burned into the film as a caption for a line the song
  #              does not have.
  #   vocal-map  where the singing actually STOPS. The energy map cannot see it.
  #
  # It costs one transcription pass and nothing else. Transcribe the STEREO source, not
  # build/hook.wav: the mono downmix is what produced the hallucination in the first
  # place, and the stereo original of the same song came back clean.
  log "map: whisper ($WHISPER_MODEL, word timestamps) -> $TRANSCRIPT"
  # IN THE SONG'S OWN LANGUAGE. Auto-detect is fine for English; on a Hinglish track it
  # wandered (a Hindi pass that missed the first 21s, an English pass that TRANSLATED
  # the words). SONG_LANGUAGE in the pack (whisper code: hi, pa, en) pins it, and the
  # vocal brief below aligns the lyric sheet to these words.
  # THE SHEET PRIMES THE EAR. whisper's --initial_prompt conditions the first decoding
  # window; given the lyric lines it hears a chanted intro it otherwise skipped, and
  # writes "a hundred ninety-one" as the words sung instead of "191" placed 1.4 s late
  # (New Era, 2026-08-29: medium without the prompt heard nothing before 11 s). The
  # prompt is capped (whisper keeps ~224 tokens) at the sheet's head, which is what the
  # first window needs; later windows condition on what was already decoded.
  _lyric_prompt="$(RAP_SCRIPTS="$RAP_SCRIPTS" python3 -c 'import os,sys; sys.path.insert(0, os.environ["RAP_SCRIPTS"]); from transcribe_clips import sheet_prompt; print(sheet_prompt(sys.argv[1]))' "$P/references/lyrics.txt")"
  # VISIBLY SLOW, NOT SILENTLY SLOW. The pass used to run with both streams silenced: on
  # the slow engine that is 75 minutes with no sign of life, and twice a healthy pass
  # was killed as hung (film #3). whisper's own stderr goes to build/whisper-map.log.
  log "map: whisper ($WHISPER_ENGINE) is running — progress: tail -f $P/build/whisper-map.log"
  ( cd "$P/build" && whisper "$SONG" --model "$WHISPER_MODEL" --output_format json \
      ${SONG_LANGUAGE:+--language "$SONG_LANGUAGE"} \
      ${_lyric_prompt:+--initial_prompt "$_lyric_prompt"} \
      --word_timestamps True --output_dir . >>"$P/build/whisper-map.log" 2>&1 )
  base="$(basename "${SONG%.*}")"
  [ -f "$P/build/$base.json" ] || die "whisper produced no JSON in $P/build"
  cp -f "$P/build/$base.json" "$P/build/transcript-words.json"
  mv -f "$P/build/$base.json" "$TRANSCRIPT"
  # ONE PASS, EVERY CONSUMER. The transcribe stage asks whisper_words for the same
  # song under the same prompt; seed its content-keyed cache from this pass so that
  # is a hit, not a second 75-minute pass (film #3 made the identical pass three times).
  RAP_SCRIPTS="$RAP_SCRIPTS" python3 -c 'import os,sys; sys.path.insert(0, os.environ["RAP_SCRIPTS"]); from transcribe_clips import seed_cache, sheet_prompt; print("map: seeded " + seed_cache(sys.argv[1], sys.argv[2], sys.argv[3], None, sheet_prompt(sys.argv[4]) or None))' \
    "$SONG" "$P/artifacts/clip-tx" "$P/build/transcript-words.json" "$P/references/lyrics.txt" >&2
  whisper_engine_record "$P/build" "$WHISPER_ENGINE"
  python3 - "$P/build/transcript-words.json" <<'PYCHK' || die "the transcript has no word timings — captions and the vocal map would both fall back silently"
import json, sys
d = json.load(open(sys.argv[1], encoding="utf-8"))
n = sum(len(s.get("words") or []) for s in d.get("segments", []))
print(f"map: {n} word timings", file=sys.stderr)
sys.exit(0 if n else 1)
PYCHK
  mark map
fi

# ---- 5. hook (THE GATE: refuses a lazy 0-N cut) ----------------------------
if ! done_stage hook; then
  log "hook: choosing the climax window"
  # HOOK_FULL_TRACK=1 in the pack: the film covers the WHOLE song. Set it for a
  # list-song, where each verse is its own joke and a scored climax window would
  # discard whole sections. Unset = the original climax-window behaviour, unchanged.
  if ! python3 "$RAP_SCRIPTS/pick_hook.py" --song "$SONG" --transcript "$TRANSCRIPT" \
        --out-dir "$P/build" --duration "$HOOK_SECONDS" \
        $([ "${HOOK_FULL_TRACK}" = "1" ] && echo --full-track); then
    gate "the climax gate refused this song" \
"pick_hook refused (see above). Either:
  * the song has a soft intro and a later window is the hook — nothing to do, the
    runner-up windows are printed above; or
  * you have LISTENED and the opening really IS the hook — re-run pick_hook by
    hand with --from-start-ok, which records the override in hook.json:
      python3 $RAP_SCRIPTS/pick_hook.py --song '$SONG' --transcript '$TRANSCRIPT' \\
        --out-dir '$P/build' --duration $HOOK_SECONDS --from-start-ok
  * or DELETE '$SONG' and re-run to buy a song that opens on its hook."
  fi
  mark hook
fi

# song-words.json: the song's word onsets for the brief and the vocal map. ONE
# function, two callers (plan, vocal-map). This is a SECOND EAR, not a repeat of the
# map: the map hears the stereo source primed with the sheet; this pass hears the
# mono hook.wav unprimed, and vocal_brief fills the map's silences with what only
# this ear caught (the final hook's first lines — 110 words the primed pass missed on
# a 130 s song). Deriving it from the map transcript was tried (2026-09-04) and
# withdrawn in review: a fill made from the base fills nothing. On the slow engine
# it is a second 75-minute pass; WHISPER_ENGINE=cpp makes it 41 s.
# `|| { python > tmp; mv tmp final; }` let a FAILED python mv an empty file into place
# (bash relaxes set -e inside a ||-list compound) and the file then read as done
# forever (review finding, 2026-09-02). The move happens only when python succeeded.
# A schema-1 words file (onsets only) is rewritten from the cached whisper JSON — a cache
# read, not a second pass (`whisper_words` keys the raw transcript by content, and the
# raw transcript always carried the ends). Then WORD_ENDS names where `e` comes from.
words_need_v2(){ [ -f "$1" ] && ! grep -q '"schema": *2' "$1"; }
apply_word_ends(){   # <words.json> <audio>   — in place; gemini without a key is a hard stop
  local words_json="$1" audio="$2"
  [ "$WORD_ENDS" = "whisper" ] && return 0
  [ -s "$words_json" ] && [ -f "$audio" ] || return 0
  local rc=0
  python3 "$RAP_SCRIPTS/word_ends.py" --words "$words_json" --audio "$audio" --source "$WORD_ENDS" \
       --report "${words_json%.json}-ends.json" || rc=$?
  [ "$rc" = 0 ] && return 0
  [ "$rc" = 3 ] && die "WORD_ENDS=gemini needs a Gemini key (see above). Export one, or set WORD_ENDS=stem (local, free) or WORD_ENDS=whisper in the pack — the film must not quietly get worse word ends."
  die "word_ends.py failed on $words_json (exit $rc) — see above"
}
ensure_song_words(){
  local words_json="$P/build/song-words.json"
  if [ ! -f "$words_json" ] || words_need_v2 "$words_json"; then
    if RAP_SCRIPTS="$RAP_SCRIPTS" python3 - "$P" > "$words_json.tmp" <<'PYWORDS'
import json, os, sys
sys.path.insert(0, os.environ["RAP_SCRIPTS"])
from transcribe_clips import whisper_words, WORDS_SCHEMA
P = sys.argv[1]
w = whisper_words(f"{P}/build/hook.wav", os.environ.get("WHISPER_MODEL", "small"), f"{P}/build/song-tx")["words"]
json.dump({"schema": WORDS_SCHEMA, "words": w, "source": f"{P}/build/hook.wav"}, sys.stdout)
PYWORDS
    then mv "$words_json.tmp" "$words_json"; else rm -f "$words_json.tmp"; warn "song word pass failed — the brief aligns on the transcript alone"; return 0; fi
  fi
  # the ends come from the stem when the film has one (a clean vocal), else from hook.wav
  local audio="$P/build/hook.wav"
  [ -f "$P/build/stems/vocals.wav" ] && audio="$P/build/stems/vocals.wav"
  apply_word_ends "$words_json" "$audio"
}

# ---- 5b. stem (free, local): the vocal stem — the clean clock the slices are cut from --
# Demucs separates hook.wav (so the stem shares its timeline exactly) into
# build/stems/vocals.wav with a content sidecar; the plan stage's singer_diarize reuses
# it. VOICE_SOURCE=stem makes a missing stem a hard stop; under `mix` it is a warning,
# because vocal_map still wants the stem to find where the singing stops.
if ! done_stage stem; then
  mkdir -p "$P/build/stems"
  if python3 "$RAP_SCRIPTS/singer_diarize.py" --separate-only --song "$P/build/hook.wav" \
       --stem "$P/build/stems/vocals.wav"; then
    log "stem: $P/build/stems/vocals.wav"
    # SIX MEASUREMENTS BEFORE A SLICE IS CUT FROM IT (stem_check.py): a silent stem, a
    # truncated one, a wrong-song stem, the mix copied back under the stem's name. Until
    # this gate the only check was that the file existed. Under VOICE_SOURCE=stem a
    # failed check is a hard stop (every slice would sing to it); under mix a warning
    # (the stem only says where the singing stops). preflight_higgs reads the report.
    _inst="$P/build/stems/_demucs/htdemucs/hook/no_vocals.wav"
    rc=0
    python3 "$RAP_SCRIPTS/stem_check.py" --song "$P/build/hook.wav" --vocals "$P/build/stems/vocals.wav" \
      $([ -f "$_inst" ] && printf -- '--inst %s' "$_inst") --out "$P/build/stems/stem-check.json" || rc=$?
    if [ "$rc" != 0 ]; then
      if [ "$VOICE_SOURCE" = "stem" ]; then
        die "VOICE_SOURCE=stem but the vocal stem FAILED its quality check (see the FAIL lines above and
  $P/build/stems/stem-check.json). Re-separate it (delete build/stems and re-run the stem stage),
  or set VOICE_SOURCE=mix to cut the slices from the whole track."
      fi
      warn "stem: the vocal stem failed its quality check (see above) — it is used only to find where
  the singing stops; VOICE_SOURCE=mix cuts the slices from the whole track"
    fi
  elif [ "$VOICE_SOURCE" = "stem" ]; then
    die "VOICE_SOURCE=stem but the vocal stem could not be separated (see above — it needs
  \$VCLAW_WORKSPACE/tools/singer-diarize/.venv with demucs). Fix the venv, or set
  VOICE_SOURCE=mix to cut the slices from the whole track."
  else
    warn "stem: no vocal stem — the slices are cut from the mix (VOICE_SOURCE=mix) and the
  vocal map falls back to the energy of the whole track"
  fi
  mark stem
fi

# ---- 6. styles (deterministic shuffle-bag draw; gate to confirm) -----------
if ! done_stage styles; then
  python3 "$RAP_SCRIPTS/pick_styles.py" --styles "$STYLES_FILE" \
    --state "$STYLE_STATE" --slug "$SLUG" --count "$STYLE_COUNT" \
    ${STYLE_ALLOW:+--only "$STYLE_ALLOW"} > "$P/build/styles-drawn.json"
  mark styles   # before the gate: gate() exits, so a mark after it never runs
  gate "confirm the two styles" \
"Drawn (see $P/build/styles-drawn.json):
$(python3 -c "import json,sys; d=json.load(open('$P/build/styles-drawn.json')); [print('  * '+s['label']+' — '+s['mood']) for s in d['styles']]")

  * Happy? Re-run to continue.
  * Want a different pair? Re-run pick_styles.py with --redraw first:
      python3 $RAP_SCRIPTS/pick_styles.py --styles '$STYLES_FILE' \\
        --state '$STYLE_STATE' --slug '$SLUG' --count $STYLE_COUNT --redraw \\
        > '$P/build/styles-drawn.json'"
fi

# ---- 6b. contract (free) — the preview IS the contract, built BEFORE any spend --
# IDENTITY_NOTES is the visual descriptor the model locks the face from. It was
# never passed here, so every prompt this lane has ever composed described the
# portrait only as "the protagonist portrait" and make_plan then hung @IMG_1 off
# a citation with no prose behind it. Unset it and compose_prompts says so.
# VIDEO_MODE picks a named grammar from references/video-modes.json — camera
# behaviour, dance-or-still, ensemble treatment and the negatives that keep biting.
# Unset = today's behaviour exactly. See it with:
#   python3 skills/rap-avatar-mv/scripts/compose_prompts.py --list-modes
# REBUILD ONLY WHEN THE INPUTS CHANGED. This ran unconditionally, on every single
# invocation — and `spend_gate` refuses when the approval is older than
# storyboard.html. So approving and re-running rewrote the contract first and
# refused with "the approval predates the current contract", forever: the gate
# standing in front of every render COULD NOT BE PASSED. It went unnoticed because
# this lane has always been driven by hand from here on, which is the exact habit
# the gate exists to replace.
#
# Recomposing only when a real input is newer keeps the guarantee the gate is
# actually making — you approved THIS contract, not an older one — while letting an
# unchanged contract stay approved.
_contract="$P/build/storyboard.html"
_needs_contract=0
[ -f "$_contract" ] || _needs_contract=1
for _in in "$STYLES_FILE" "$P/build/styles-drawn.json"; do
  [ -f "$_in" ] && [ "$_in" -nt "$_contract" ] && _needs_contract=1
done
if [ "$_needs_contract" = 1 ]; then
  # A register that puts performer b (or both) in any block needs the whole second
  # identity BEFORE composing: the still, the prose, and a stated second pronoun.
  # Checked here, at the runner, so the refusal names the pack var to set rather
  # than surfacing as a compose/plan error further down.
  if python3 -c '
import json, sys
styles = json.load(open(sys.argv[1], encoding="utf-8")).get("styles", [])
sys.exit(0 if any(s.get("performer") in ("b", "both") for s in styles) else 1)
' "$STYLES_FILE"; then
    [ -n "${PORTRAIT_2:-}" ] || die "the style register uses performer b/both but the pack sets no PORTRAIT_2"
    [ -f "$PORTRAIT_2" ] || die "PORTRAIT_2 is set but not found: $PORTRAIT_2"
    [ -n "${IDENTITY_NOTES_2:-}" ] || die "the style register uses performer b/both but IDENTITY_NOTES_2 is empty"
    case "${PERFORMER_PRONOUNS:-}" in
      *\|*) ;;
      *) die "the style register uses performer b/both but PERFORMER_PRONOUNS does not state two pronouns (e.g. \"he|she\")" ;;
    esac
  fi
  # compose_prompts REFUSES (exit 2) on a contradictory pack/register — b/both without
  # a second subject, a second subject without a second pronoun, both+solo. That
  # refusal used to be swallowed by `|| true` (the preview was once best-effort), so
  # the runner carried on and make_plan planned the film from the STALE prompts.json
  # it had not rewritten: a single-performer contract, silently. The contract this
  # stage writes is what every later stage reads, so its refusal must stop the run.
  python3 "$RAP_SCRIPTS/compose_prompts.py" --styles "$STYLES_FILE" \
    --drawn "$P/build/styles-drawn.json" --out-dir "$P/build" \
    --keyframe-dir "$P/references" --duration "$CLIP_SECONDS" --aspect "$ASPECT" \
    --subject "${IDENTITY_NOTES:-}" ${VIDEO_MODE:+--mode "$VIDEO_MODE"} \
    ${IDENTITY_NOTES_2:+--subject-2 "$IDENTITY_NOTES_2"} \
    ${PERFORMER_PRONOUNS:+--pronouns "$PERFORMER_PRONOUNS"} \
    ${PERFORMER_NAMES:+--performer-names "$PERFORMER_NAMES"} \
    ${LYRIC_LANGUAGE:+--lyric-language "$LYRIC_LANGUAGE"} \
    ${PORTRAIT:+--identity-ref "$PORTRAIT"} ${PORTRAIT_2:+--identity-ref-2 "$PORTRAIT_2"} \
    || die "compose_prompts refused — fix the pack/register (see the message above); the previous contract in $P/build was NOT reused"
fi

# ---- 7. plan (free): cut the hook into windows and build one voice ref each -
# ONE RENDER PER WINDOW. The old keyframes -> hero -> B-roll split is gone: it
# existed because the route table said nothing took a photoreal face AND an audio
# reference together, which was never true of Seedance. See "An earlier design
# here was wrong" in SKILL.md.
if ! done_stage plan; then
  [ -n "$PORTRAIT" ] || die "pack must set PORTRAIT (the face still) for the plan stage"
  # A second performer needs BOTH halves of an identity: the still and the prose.
  if [ -n "${PORTRAIT_2:-}" ]; then
    [ -f "$PORTRAIT_2" ] || die "PORTRAIT_2 is set but not found: $PORTRAIT_2"
    [ -n "${IDENTITY_NOTES_2:-}" ] || die "PORTRAIT_2 is set but IDENTITY_NOTES_2 is empty — the
    second performer needs a visual descriptor as much as the first; the portrait alone
    does not lock a face on these models."
  fi
  # The pack's ROUTE is passed THROUGH, so a pack means what it says. It used to be
  # printed at scaffold and then dropped, leaving the runner announcing one lane and
  # rendering on another — a silent cross-route fallback, which docs/adr forbids
  # outright. explore_queue's guard validates it and refuses an unusable route by
  # name, so a stale pack now fails loudly instead of quietly working differently.
  python3 "$RAP_SCRIPTS/make_plan.py" --project "$P" \
    --styles "$STYLES_FILE" --drawn "$P/build/styles-drawn.json" \
    --identity-ref "$PORTRAIT" --aspect "$ASPECT" ${ROUTE:+--route "$ROUTE"} \
    ${PORTRAIT_2:+--identity-ref-2 "$PORTRAIT_2"} \
    --clip-seconds "$CLIP_SECONDS" ${SECTIONS:+--sections "$SECTIONS"} \
    --voice-source "$VOICE_SOURCE" --voice-wav "$VOICE_WAV" \
    $([ "${LYRIC_LANGUAGE:-English}" != "English" ] && printf -- '--no-word-verify')
  # THE PROMPT MUST SAY WHAT THE AUDIO DOES. With the windows known, align the lyric
  # sheet to the transcript's words, write what each window actually sings (and where
  # it is silent), then re-plan so every window's prompt directs the mouth line by line
  # and a wordless window is sent with NO voice. (2026-08-22: a mostly-instrumental
  # window was told to rap for 13s and the model invented the vocal.)
  # TWO EARS. The sheet-primed whisper (map) is right where it hears but misses whole
  # stretches (Baby Ram & Sita, 2026-09-02: an opening hook, half a hook plus the bridge,
  # the final hook's first lines — 110 words for a 130 s song); the unprimed word pass
  # hears those. Every vocal_brief run below aligns the transcript with the word pass
  # filling its silences (merge_word_streams). The vocal-map stage reuses the file.
  VB_FILL=()
  words_json="$P/build/song-words.json"
  ensure_song_words
  [ -s "$words_json" ] && VB_FILL=(--fill-words "$words_json")
  # THE THIRD EAR: whisper on the Demucs VOCAL STEM, primed with the sheet. Two passes over
  # the mix left an 8.6 s hole with two sung lines in it (film #2's corrected plan,
  # 2026-09-02, caught by the results review); the stem heard both at once. Fills only what
  # the two mix passes left silent.
  stem_words="$P/build/stem-words.json"
  if { [ ! -f "$stem_words" ] || words_need_v2 "$stem_words"; } && [ -f "$P/build/stems/vocals.wav" ]; then
    if RAP_SCRIPTS="$RAP_SCRIPTS" python3 - "$P" > "$stem_words.tmp" <<'PYSTEM'
import json, os, sys
sys.path.insert(0, os.environ["RAP_SCRIPTS"])
from transcribe_clips import whisper_words, WORDS_SCHEMA
P = sys.argv[1]
sheet = [l.strip() for l in open(f"{P}/references/lyrics.txt", encoding="utf-8")
         if l.strip() and not l.strip().startswith("[")]
w = whisper_words(f"{P}/build/stems/vocals.wav", os.environ.get("WHISPER_MODEL", "small"), f"{P}/build/stem-tx",
                  language=os.environ.get("SONG_LANGUAGE") or None, prompt=". ".join(sheet)[:700])["words"]
json.dump({"schema": WORDS_SCHEMA, "words": w, "source": f"{P}/build/stems/vocals.wav", "primed": True}, sys.stdout)
PYSTEM
    then mv "$stem_words.tmp" "$stem_words"; else rm -f "$stem_words.tmp"; warn "stem word pass failed — the brief aligns without it"; fi
  fi
  [ -s "$stem_words" ] && apply_word_ends "$stem_words" "$P/build/stems/vocals.wav"
  [ -s "$stem_words" ] && VB_FILL+=(--fill-words "$stem_words")
  if [ -f "$P/references/lyrics.txt" ]; then
    python3 "$RAP_SCRIPTS/vocal_brief.py" --lyrics "$P/references/lyrics.txt" \
      --transcript "$TRANSCRIPT" --plan "$P/build/plan.json" ${VB_FILL[@]+"${VB_FILL[@]}"} \
      --min-ratio "${VOCAL_BRIEF_MIN_RATIO:-0.45}" \
      --max-intra-gap "${VOCAL_BRIEF_MAX_INTRA_GAP_S:-2.0}" \
      --out "$P/build/vocal-brief.json" --html "$P/build/vocal-brief.html" \
      --voice-dir "$P/build/voice" --song "$P/build/hook.wav" || die "vocal_brief failed — the lyric sheet could not be placed in time"
    # THE SONG BREAKDOWN (SONG_BREAKDOWN=1, pack): Gemini listens to the stem and proposes a
    # section, a singer and a choreography cue per placed line — ADVISORY, shown beside
    # singers.html's answer; the times are whisper's, the words are the sheet's, nothing is
    # applied. Cues land in song-cues-proposed.json (SHOT_MOVES shape) for SHOT_REFS=1.
    if [ "${SONG_BREAKDOWN:-0}" = "1" ] && [ ! -f "$P/build/song-breakdown.json" ]; then
      python3 "$RAP_SCRIPTS/song_breakdown.py" --project "$P" \
        --brief "$P/build/vocal-brief.json" --transcript "$TRANSCRIPT" \
        --out "$P/build/song-breakdown.json" --html "$P/build/song-breakdown.html" \
        || warn "song_breakdown could not run (see above) — the plan continues without the proposal"
      [ -f "$P/build/song-breakdown.html" ] && gate "review the song breakdown" \
"Open '$P/build/song-breakdown.html'. It is a PROPOSAL: sections, who sings, a cue per line.
  * Who sings is decided on singers.html by your ear — a row that differs is a question.
  * Cues you like: pass '$P/build/song-cues-proposed.json' as SHOT_MOVES under SHOT_REFS=1.
Re-run to continue."
    fi
    # WHO SINGS EACH LINE IS MEASURED, THEN VERIFIED BY EAR — never guessed from a tag
    # or a pitch. singer_diarize separates the vocal stem (Demucs), embeds each line,
    # clusters two voices, names them from SINGER_ANCHOR (a span the operator confirmed,
    # e.g. "21-31=male"), and writes singers.html with the song and the stem beside
    # each line. The operator listens; re-running is his verification. (2026-08-23: a
    # pitch median put her face on his vocal for seven draws; the sheet said Both.)
    if [ ! -f "$P/build/singers.json" ]; then
      python3 "$RAP_SCRIPTS/singer_diarize.py" --song "$P/build/hook.wav" \
        --brief "$P/build/vocal-brief.json" --out "$P/build/singers.json" \
        --html "$P/build/singers.html" ${SINGER_ANCHOR:+--anchor "$SINGER_ANCHOR"} \
        || die "singer_diarize failed — see above (needs \$VCLAW_WORKSPACE/tools/singer-diarize/.venv)"
      gate "verify who sings each line" \
"Open '$P/build/singers.html': every line with the song and the vocal stem beside the
  tool's answer. Type corrections where it is wrong, press 'Copy corrections', and re-run
  singer_diarize.py with that --corrections flag; then re-run. Re-running IS your verification."
    fi
    python3 "$RAP_SCRIPTS/vocal_brief.py" --lyrics "$P/references/lyrics.txt" \
      --transcript "$TRANSCRIPT" --plan "$P/build/plan.json" ${VB_FILL[@]+"${VB_FILL[@]}"} \
      --min-ratio "${VOCAL_BRIEF_MIN_RATIO:-0.45}" \
      --max-intra-gap "${VOCAL_BRIEF_MAX_INTRA_GAP_S:-2.0}" \
      --out "$P/build/vocal-brief.json" --html "$P/build/vocal-brief.html" \
      --voice-dir "$P/build/voice" --song "$P/build/hook.wav" \
      --singers "$P/build/singers.json" || die "vocal_brief failed with singers.json"
    # WINDOWS START ON SUNG LINES (WINDOW_MODE=lines, the default once a lyric sheet
    # exists; WINDOW_MODE=grid keeps the old uniform tiling). With every lyric line timed,
    # re-cut the film so each clip opens on a line (8-13s phrases) and a wordless intro is
    # its own shot-led window(s); then re-brief THOSE windows and plan with the direction
    # in every prompt.
    if [ "${WINDOW_MODE:-lines}" = "lines" ]; then
    song_len="$(python3 -c "import json;print(json.load(open('$P/build/hook.json'))['durationSec'])")"
    # LANE DEFAULTS (2026-08-23, from the first two-performer film): PHRASE_WINDOWS=1
    # (one voice, one section, as many whole lines as fit the cap), EXACT_ONSETS=1 (a
    # window opens ON its first word), SLACK_HEAD=0 / SLACK_TAIL=1 (no lead-in — the
    # model starts at the clip's first frame — but a second of real frames after the
    # window for `slide`), and the slice is silent outside its own lines. A pack can
    # set any of these to 0/other; the defaults are what the operator verified by ear.
    # LINE_WINDOW_PINS (pack, optional): window edges that must be kept because a clip
    # the project already owns fits them — e.g. "42,52,60". A re-cut that moved those
    # edges would orphan the clip and send the window back to the lane.
    # WINDOW_LINES=N (pack, optional): N lyric lines per window instead of phrase packing —
    # 1 = the published sync recipe (one short line, locked shot). Roughly doubles the
    # window count (and the lane time) of a 150 s song; the A/B decides whether it is
    # needed. When set it overrides PHRASE_WINDOWS and the --min floor drops to 4 s.
    _lw_min="${LINE_WINDOW_MIN:-8}"; [ -n "${WINDOW_LINES:-}" ] && _lw_min=4
    python3 "$RAP_SCRIPTS/line_windows.py" --brief "$P/build/vocal-brief.json" \
      --song-seconds "$song_len" --out "$P/build/windows.json" \
      --min "$_lw_min" --max "$CLIP_SECONDS" \
      ${LINE_WINDOW_PINS:+--pin "$LINE_WINDOW_PINS"} ${WINDOW_LINES:+--lines "$WINDOW_LINES"} \
      $([ -z "${WINDOW_LINES:-}" ] && [ "${PHRASE_WINDOWS:-1}" = "1" ] && printf -- "--phrases") || die "line_windows failed"
    # THE SECTIONS FILE IS PROPOSED FROM THE BRIEF (film3 item 7): once the brief exists
    # below, sections_from_brief.py writes build/sections-proposed.json; an unset SECTIONS
    # takes it, an authored SECTIONS is checked against the brief (a "break" over placed
    # lines, or a stale briefSha, is a refusal — film #2's hand file cut a sung verse).
    _had_sections="${SECTIONS:-}"
    propose_sections() {
      local prop="$P/build/sections-proposed.json"
      python3 "$RAP_SCRIPTS/sections_from_brief.py" --brief "$P/build/vocal-brief.json" \
        --styles-drawn "$P/build/styles-drawn.json" --song-seconds "$song_len" --out "$prop" \
        ${SECTION_WORLDS:+--worlds "$SECTION_WORLDS"} ${PERFORMER_PRONOUNS:+--pronouns "$PERFORMER_PRONOUNS"} \
        ${_had_sections:+--check "$_had_sections"} \
        || die "sections: the authored file disagrees with the brief (see above) — edit it, or unset SECTIONS to take the proposal"
      if [ -z "$_had_sections" ]; then
        SECTIONS="$prop"
        _plan_args+=(--sections "$SECTIONS")
        log "sections: proposed from the brief -> $prop (edit it and re-run --from plan to change)"
      fi
    }
    _plan_args=(--project "$P" --styles "$STYLES_FILE" --drawn "$P/build/styles-drawn.json"
      --identity-ref "$PORTRAIT" --aspect "$ASPECT" ${ROUTE:+--route "$ROUTE"}
      ${PORTRAIT_2:+--identity-ref-2 "$PORTRAIT_2"}
      --clip-seconds "$CLIP_SECONDS" ${SECTIONS:+--sections "$SECTIONS"}
      --voice-source "$VOICE_SOURCE" --voice-wav "$VOICE_WAV"
      --windows "$P/build/windows.json"
      --slack-head "${SLACK_HEAD:-0}" --slack-tail "${SLACK_TAIL:-0}")
    [ "${LYRIC_LANGUAGE:-English}" != "English" ] && _plan_args+=(--no-word-verify)
    python3 "$RAP_SCRIPTS/make_plan.py" "${_plan_args[@]}"
    python3 "$RAP_SCRIPTS/vocal_brief.py" --lyrics "$P/references/lyrics.txt" \
      --transcript "$TRANSCRIPT" --plan "$P/build/plan.json" ${VB_FILL[@]+"${VB_FILL[@]}"} \
      --min-ratio "${VOCAL_BRIEF_MIN_RATIO:-0.45}" \
      --max-intra-gap "${VOCAL_BRIEF_MAX_INTRA_GAP_S:-2.0}" \
      --out "$P/build/vocal-brief.json" --html "$P/build/vocal-brief.html" \
      --voice-dir "$P/build/voice" --song "$P/build/hook.wav" \
      --singers "$P/build/singers.json" || die "vocal_brief failed on the line windows"
    propose_sections
    python3 "$RAP_SCRIPTS/make_plan.py" "${_plan_args[@]}" "${PROMPT_CLOCK_ARGS[@]}" \
      --vocal-brief "$P/build/vocal-brief.json" ${PERFORMER_PRONOUNS:+--pronouns "$PERFORMER_PRONOUNS"} ${PERFORMER_NAMES:+--performer-names "$PERFORMER_NAMES"} \
      $([ "${EXACT_ONSETS:-1}" = "1" ] && printf -- "--exact-onsets")
    if [ "${EXACT_ONSETS:-1}" = "1" ]; then
      # WHOLE LINES ONLY: the windows just moved onto their first words, so the brief's
      # per-window spans are stale — re-brief against the exact windows and plan once
      # more (idempotent: the same lines give the same edges).
      python3 "$RAP_SCRIPTS/vocal_brief.py" --lyrics "$P/references/lyrics.txt" \
        --transcript "$TRANSCRIPT" --plan "$P/build/plan.json" ${VB_FILL[@]+"${VB_FILL[@]}"} \
      --min-ratio "${VOCAL_BRIEF_MIN_RATIO:-0.45}" \
      --max-intra-gap "${VOCAL_BRIEF_MAX_INTRA_GAP_S:-2.0}" \
        --out "$P/build/vocal-brief.json" --html "$P/build/vocal-brief.html" \
        --voice-dir "$P/build/voice" --song "$P/build/hook.wav" \
        --singers "$P/build/singers.json" || die "vocal_brief failed on the exact windows"
    # THE SLICE PAGE. Every voice slice the model will hear, with sung / head / tail /
    # render seconds and a player, so the operator can see a padded render before it
    # costs a lane-hour (he found the New Era defect by reading exactly those two numbers).
    python3 "$RAP_SCRIPTS/slice_review.py" --plan "$P/build/plan.json" \
      --vocal-brief "$P/build/vocal-brief.json" --out "$P/build/slices.html" \
      --json "$P/build/slices.json" || die "slice_review failed"
    log "slices: $P/build/slices.html"
      python3 "$RAP_SCRIPTS/make_plan.py" "${_plan_args[@]}" "${PROMPT_CLOCK_ARGS[@]}" \
        --vocal-brief "$P/build/vocal-brief.json" ${PERFORMER_PRONOUNS:+--pronouns "$PERFORMER_PRONOUNS"} ${PERFORMER_NAMES:+--performer-names "$PERFORMER_NAMES"} \
        --exact-onsets
    fi
    # FOLLOW THE REFERENCE VIDEO (SHOT_REFS=1, pack): per sung window the original's own
    # shot — a measured moves sentence (dance-breakdown), a styled keyframe of the
    # performer in that framing (Go Bananas, char CHAR_IDS) as @IMG_1, and with
    # MOTION_DONOR=1 the muted footage as the motion reference — then the plan is rebuilt
    # once more with --shot-refs so every prompt carries the rewrite. The window geometry
    # is untouched (same windows, same slices), so plan.hash does not move.
    if [ "${SHOT_REFS:-0}" = "1" ]; then
      # the ingested source is the reference video unless the pack names another
      if [ -z "${SHOT_REFS_VIDEO:-}" ] && [ -f "$P/references/source.mp4" ]; then
        SHOT_REFS_VIDEO="$P/references/source.mp4"
        log "shot-refs: SHOT_REFS_VIDEO defaults to references/source.mp4 (ingest_source)"
      fi
      [ -n "${SHOT_REFS_VIDEO:-}" ] || die "SHOT_REFS=1 needs SHOT_REFS_VIDEO=<the reference video> in the pack (or SOURCE_URL, which ingests it to references/source.mp4)"
      [ -f "$SHOT_REFS_VIDEO" ] || die "SHOT_REFS_VIDEO not found: $SHOT_REFS_VIDEO"
      _bd="$P/build/dance-breakdown.json"
      if [ ! -s "$_bd" ]; then
        log "shot-refs: measuring the reference video's choreography (dance-breakdown)…"
        python3 "$MAIN/skills/dance-breakdown/scripts/breakdown.py" --video "$SHOT_REFS_VIDEO" \
          ${SHOT_REFS_CUTS:+--cuts "$SHOT_REFS_CUTS"} --end "$song_len" --out "$_bd" \
          --html "$P/build/dance-breakdown.html" ${SHOT_REFS_DENY:+--deny "$SHOT_REFS_DENY"} \
          || die "dance-breakdown failed — see above"
      fi
      _char="${CHAR_IDS// /|}"            # "397 399" -> "397|399": performers a|b (a `both` style draws both)
      _pron2=""; case "${PERFORMER_PRONOUNS:-}" in *\|*) _pron2="${PERFORMER_PRONOUNS#*|}";; esac
      [ -n "$_char" ] || die "SHOT_REFS=1 needs CHAR_IDS (the Go Bananas character) in the pack"
      python3 "$RAP_SCRIPTS/shot_refs.py" --project "$P" --plan "$P/build/plan.json" \
        --brief "$P/build/vocal-brief.json" --breakdown "$_bd" --video "$SHOT_REFS_VIDEO" \
        --styles "$STYLES_FILE" --char-id "$_char" --out "$P/build/shot-refs.json" \
        --html "$P/build/shot-refs.html" ${IDENTITY_NOTES:+--identity-notes "$IDENTITY_NOTES"} \
        ${PERFORMER_PRONOUNS:+--pronoun "${PERFORMER_PRONOUNS%%|*}"} \
        ${_pron2:+--pronoun-2 "$_pron2"} \
        ${IDENTITY_NOTES_2:+--identity-notes-2 "$IDENTITY_NOTES_2"} \
        ${SHOT_MOVES:+--moves "$SHOT_MOVES"} \
        $([ "${MOTION_DONOR:-0}" = "1" ] && printf -- "--donor") \
        ${MOTION_DONOR_OWN:+--own-donor "$MOTION_DONOR_OWN"} \
        $([ "${MOTION_DONOR_OWN_AUDIO:-0}" = "1" ] && printf -- "--own-donor-audio") \
        $([ "${SHOT_REFS_GATE:-0}" = "1" ] && printf -- "--gate") \
        || die "shot_refs refused (see above) — fix the named windows, then re-run --from plan"
      python3 "$RAP_SCRIPTS/make_plan.py" "${_plan_args[@]}" "${PROMPT_CLOCK_ARGS[@]}" \
        --vocal-brief "$P/build/vocal-brief.json" ${PERFORMER_PRONOUNS:+--pronouns "$PERFORMER_PRONOUNS"} ${PERFORMER_NAMES:+--performer-names "$PERFORMER_NAMES"} \
        $([ "${EXACT_ONSETS:-1}" = "1" ] && printf -- "--exact-onsets") \
        --shot-refs "$P/build/shot-refs.json" $([ "${MOTION_DONOR:-0}" = "1" ] || [ -n "${MOTION_DONOR_OWN:-}" ] && printf -- "--motion-donor") \
        || die "make_plan --shot-refs failed"
      log "shot-refs: $P/build/shot-refs.html"
    fi
    else
    python3 "$RAP_SCRIPTS/make_plan.py" --project "$P" \
      --styles "$STYLES_FILE" --drawn "$P/build/styles-drawn.json" \
      --identity-ref "$PORTRAIT" --aspect "$ASPECT" ${ROUTE:+--route "$ROUTE"} \
      ${PORTRAIT_2:+--identity-ref-2 "$PORTRAIT_2"} \
      --clip-seconds "$CLIP_SECONDS" ${SECTIONS:+--sections "$SECTIONS"} \
      --voice-source "$VOICE_SOURCE" --voice-wav "$VOICE_WAV" "${PROMPT_CLOCK_ARGS[@]}" \
      $([ "${LYRIC_LANGUAGE:-English}" != "English" ] && printf -- '--no-word-verify') \
      --vocal-brief "$P/build/vocal-brief.json" ${PERFORMER_PRONOUNS:+--pronouns "$PERFORMER_PRONOUNS"} ${PERFORMER_NAMES:+--performer-names "$PERFORMER_NAMES"}
    fi
    log "vocal brief: $P/build/vocal-brief.html"
  fi
  log "plan: $P/build/plan.json"
  # THE PLAN'S GEOMETRY IS HASHED. A re-plan that moves a window makes every selection,
  # cut, sync/shift/cover record, fitted copy and the style collapse describe a film
  # that no longer exists; they are voided here (replace_window --replan), never by hand.
  _ph="$(python3 -c "
import json, hashlib, sys
p = json.load(open(sys.argv[1]))
g = [(j['id'], j.get('startSec'), j.get('seconds'), j.get('trimStartSec'), j.get('styleId'), j.get('voiceRef')) for j in p['jobs']]
print(hashlib.md5(json.dumps(g, sort_keys=True).encode()).hexdigest()[:12])" "$P/build/plan.json")"
  if [ -f "$P/build/plan.hash" ] && [ "$(cat "$P/build/plan.hash")" != "$_ph" ]; then
    log "plan: the window geometry changed ($(cat "$P/build/plan.hash") -> $_ph) — voiding what the old plan derived"
    python3 "$RAP_SCRIPTS/replace_window.py" --project "$P" --replan --reason replan || die "replace_window --replan failed"
  fi
  printf '%s' "$_ph" > "$P/build/plan.hash"
  mark plan
fi

# ---- 7b. vocal map (free): where the song actually sings --------------------
# A sync score answers "does this take follow the vocal" and never "is he mouthing
# when there is no vocal to follow". Windows below the floor are SHOT-LED and need
# a take whose mouth is not readable. Point it at the STEREO original: hook.wav is
# a mono downmix and this measurement is centre-vs-side, so in mono it calls the
# whole song instrumental. It refuses that input rather than reporting it.
# ---- 7c. shot-refs (SHOT_REFS=1): the gate that every sung window's shot reference is real ----
if ! done_stage shot-refs; then
  if [ "${SHOT_REFS:-0}" = "1" ]; then
    python3 - "$P/build/plan.json" "$P/build/shot-refs.json" <<'PYSR' || die "shot-refs gate failed (above)"
import json, os, sys
plan = json.load(open(sys.argv[1], encoding="utf-8"))
refs = json.load(open(sys.argv[2], encoding="utf-8")).get("windows", {}) if os.path.isfile(sys.argv[2]) else {}
bad = []
for j in plan["jobs"]:
    if not j.get("voiceRef") or not j["id"].startswith("w"):
        continue
    w = refs.get(j["id"]) or {}
    if not w:
        bad.append(f"{j['id']}: no shot reference at all"); continue
    if w.get("problems"):
        bad.append(f"{j['id']}: " + "; ".join(w["problems"]))
    if not j.get("shotRef") or not os.path.isfile(j.get("identityRef") or ""):
        bad.append(f"{j['id']}: the plan does not carry its keyframe (re-run --from plan)")
for b in bad:
    print("shot-refs:", b, file=sys.stderr)
sys.exit(1 if bad else 0)
PYSR
    log "shot-refs: every sung window carries its shot ($P/build/shot-refs.html)"
  else
    log "shot-refs: SHOT_REFS unset — skipped"
  fi
  mark shot-refs
fi

if ! done_stage vocal-map; then
  SONG_SRC="$(ls "$P/artifacts/audio/"*.mp3 2>/dev/null | head -1)"
  if [ -n "$SONG_SRC" ]; then
    # WORD TIMINGS ARE THE SOURCE for where the song stops singing. The energy map
    # cannot see a vocal-free stretch — a reverb tail and a held note score like a
    # sung word — and on this film it reported NO gaps at all for a song with three,
    # so every window was pinned with a performer and thirteen seconds of instrumental
    # outro shipped with a mouth moving over it. --lyrics is what lets the map throw
    # away whisper's "thank you for watching" hallucination over the silence, which
    # otherwise pushes the last-word time past the end of the actual singing.
    words_json="$P/build/song-words.json"
    ensure_song_words
    python3 "$RAP_SCRIPTS/vocal_map.py" --song "$SONG_SRC" \
      --plan "$P/build/plan.json" --transcript "$P/build/transcript.json" \
      ${words_json:+--words "$words_json"} \
      $([ -f "$P/references/lyrics.txt" ] && printf -- '--lyrics %s' "$P/references/lyrics.txt") \
      $([ -f "$P/build/vocal-brief.json" ] && printf -- '--brief %s' "$P/build/vocal-brief.json") \
      $([ -f "$P/build/stems/vocals.wav" ] && printf -- '--stem %s' "$P/build/stems/vocals.wav") \
      || warn "vocal_map could not measure this song — shot-led windows are unmarked"
  else
    warn "no stereo song found in $P/artifacts/audio — skipping the vocal map"
  fi
  mark vocal-map
fi

# ---- 8b. broll-plan (free): the pipeline authors its own cutaways ------------
# The lane always CONSUMED B-roll (render-all renders broll-plan.json, `cover` cuts the
# clips into the mouthing stretches) and nothing ever PRODUCED the plan — the operator
# hand-wrote it hours AFTER a delivery, when the mouthing was already on screen. Policy
# was GAPS ONLY: no silent stretch, no B-roll. Since 2026-08-29 every drawn world gets a
# cutaway too (BROLL_EVERY_STYLE, default on) so a cover never has to borrow another
# world's shot — the gap-owners still come first in the list.
if ! done_stage broll-plan; then
  if [ -f "$P/build/vocal-map.json" ]; then
    python3 "$RAP_SCRIPTS/make_broll_plan.py" --plan "$P/build/plan.json" \
      --vocal-map "$P/build/vocal-map.json" \
      --styles-drawn "$P/build/styles-drawn.json" --styles "$STYLES_FILE" \
      --out "$P/build/broll-plan.json" \
      $([ "$BROLL_EVERY_STYLE" = "1" ] && printf -- "--every-style") \
      || die "make_broll_plan failed — the film has mouthing stretches and no way to cover them"
    # EVERY RENDER CARRIES A REFERENCE IMAGE — cutaways included (operator, 2026-09-05:
    # two text-only cutaways came back as another film's look, then a re-plan dropped the
    # hand-run keyframe step and the prompt-pin parked the three good ones). On a
    # style-locked film (SHOT_REFS=1) the cutaway keyframes are part of THIS stage, so a
    # re-plan keeps them and the prompt hash stays what the landed clips were pinned to.
    if [ "${SHOT_REFS:-0}" = "1" ]; then
      [ -n "${BROLL_STYLE_REFS:-}" ] && [ -n "${BROLL_SHOTS:-}" ] \
        || die "SHOT_REFS=1 needs BROLL_STYLE_REFS (styleId=wNN,…: the film's own keyframe that anchors each world) and BROLL_SHOTS (styleId=<breakdown shot>|self,…) in the pack — a cutaway never renders from text alone"
      python3 "$RAP_SCRIPTS/broll_refs.py" --project "$P" --broll-plan "$P/build/broll-plan.json" \
        --breakdown "$P/build/dance-breakdown.json" --video "$SHOT_REFS_VIDEO" --styles "$STYLES_FILE" \
        --style-refs "$BROLL_STYLE_REFS" --shots "$BROLL_SHOTS" \
        || die "broll_refs refused — a cutaway has no keyframe; fix it before anything renders"
    fi
  else
    warn "no vocal-map.json — B-roll demand is unknown, so none is planned. If the song
  has instrumental stretches they will ship as MOUTHING. Re-run --from vocal-map."
  fi
  mark broll-plan
fi

# ---- 8a. inventory (free): what do we ALREADY have for these windows? ---------
# Twenty clips sat on disk while the plan was about to send every window to the lane
# at ~30 min a draw, and three of them fit outright (2026-08-22). Index everything the
# project owns — landed, parked, archived from earlier cuts — with a FIT TABLE judged
# the way the driver judges (the face's own sung seconds), and place the usable fits
# as the window's clip. lane_render then re-verifies them on resume like any clip on
# disk, so the render list is "windows with no fitting clip" and nothing is trusted
# unchecked. Never runs on a dry-run copy (nothing to reuse, and `die` on an empty
# library would be wrong there).
if ! done_stage inventory; then
  if [ "${DRYRUN_SYNTHETIC:-0}" != "1" ]; then
    lib_max="$(awk -v c="$CLIP_SECONDS" -v f="$MV_FPS" 'BEGIN{printf "%.3f", c + 2 + 5/f}')"
    # OTHER PROJECTS' CLIPS. The indexer scans only this project's folders; a part 2 never saw
    # part 1's takes and rendered every window anew (baby-nimbooda-p2, 2026-09-06). The pack
    # names extra sources (paths or globs, ":origin" optional) and each is passed as --source.
    _lib_src=()
    for _s in ${LIBRARY_SOURCES:-}; do _lib_src+=(--source "$_s"); done
    [ "${#_lib_src[@]}" -gt 0 ] && log "inventory: library sources beyond this project: ${LIBRARY_SOURCES}"
    if python3 "$RAP_SCRIPTS/index_library.py" --project "$P" --slug "$SLUG" \
         --aspect "$ASPECT" --max-seconds "$lib_max" --no-strips "${_lib_src[@]}" \
         --plan "$P/build/plan.json" --brief "$P/build/vocal-brief.json" --song "$P/build/hook.wav" \
         --out "$P/build/library-index.json" 2>"$P/build/inventory.log"; then
      python3 "$RAP_SCRIPTS/reuse_clips.py" --plan "$P/build/plan.json" --judge \
        --index "$P/build/library-index.json" ${REUSE_FORCE:+$(printf -- '--force %s ' $REUSE_FORCE)} \
        || die "reuse_clips failed — see above"
      # A PLACED CLIP CHANGES THE PLAN. With render slack on, a window that now has a
      # clip must keep that clip's geometry (make_plan's landed rule), and its slice,
      # prompt and contract follow. So: re-plan once, then run inventory again — the
      # second pass places nothing new (the clips are on disk) and falls through.
      placed="$(python3 -c "import json;print(len(json.load(open('$P/build/reuse-report.json')).get('placed',[])))" 2>/dev/null || echo 0)"
      if [ "${placed:-0}" -gt 0 ] && [ "${RAP_REPLAN_AFTER_REUSE:-}" != "done" ]; then
        log "inventory: placed $placed clip(s) — re-planning so those windows keep their clips' geometry"
        for st in plan vocal-map broll-plan; do sed -i '' "/^$st\$/d" "$STATE"; done
        RAP_REPLAN_AFTER_REUSE=done exec bash "$0" "$PACK" "$SLUG"
      fi
    else
      log "inventory: nothing on disk yet to reuse (first pass) — every window renders"
    fi
  fi
  mark inventory
fi

# ---- 8. preflight + the submit contract (GATE, before any spend) -----------
# Every guard this needs already existed; w13 shipped at 0.00 lip-sync because the
# submits were made by hand and went round them. preflight_higgs runs the same
# validator and writes ONE CARD PER WINDOW — storyboard.html is one card per STYLE,
# which on a 25-window film is seven prompts approved and twenty-five jobs sent.
if ! done_stage preflight; then
  # THE PIPELINE PROVES ITSELF BEFORE THE FIRST RENDER IS SPENT. A synthetic dry run of
  # the whole back half found seven film-stranding bugs in one afternoon — none visible
  # in code review or a green suite, all obvious within seconds of the stages actually
  # running. Once per pack x runner version (the stamp is a hash of the runner and its
  # scripts, so editing the pipeline re-arms the check — a cache key must carry
  # everything that changes the output). RAP_SKIP_DRYRUN=1 is the escape hatch and it
  # is per-run, deliberate, and announced.
  case "$SLUG" in *-dryrun) ;; *)
    if [ "${RAP_SKIP_DRYRUN:-0}" = "1" ]; then
      warn "preflight: RAP_SKIP_DRYRUN=1 — the pipeline dry run is SKIPPED this run"
    else
      runner_stamp=$(cat "$RAP_SCRIPTS/make-rap-mv.sh" "$RAP_SCRIPTS"/*.py 2>/dev/null | md5 -q)
      # THE ENGINE IS PROVED ON THE FIXTURES BEFORE ANY FILM. A solo and a duet film built
      # from nothing (rap_fixture.py) must reach qc on these exact scripts — ten minutes
      # of CPU that executes the handover, gap-section and short-line paths a real solo
      # film never reaches (film #2's rows 7, 12, 17 cost five hours of lane time to find).
      engine_stamp=$(cat "$RAP_SCRIPTS/make-rap-mv.sh" "$RAP_SCRIPTS"/*.py "$RAP_SCRIPTS/lib/common.sh" 2>/dev/null | md5 -q)
      if [ ! -f "$VCLAW_WORKSPACE/tools/rap-proof/$engine_stamp.ok" ]; then
        log "preflight: these scripts have not been proved on the fixtures — running npm run smoke:rap-dryrun (solo + duet, ~10 min, no spend)..."
        # ... IN A CLEAN ENVIRONMENT. The film's pack is already exported here (a second
        # performer's notes, its pronouns, its modes); the fixture packs set their own keys
        # and the runner never unsets the rest, so the solo fixture ran with this film's
        # PORTRAIT_2 and no second pronoun and compose_prompts refused it — the proof
        # failed on a healthy engine inside the only run that gates on it (Baby Ram &
        # Sita v8, 2026-09-02). Only the machine's own variables cross into the proof.
        _proof() { env -i HOME="$HOME" PATH="$PATH" LANG="${LANG:-en_US.UTF-8}" TMPDIR="${TMPDIR:-/tmp}" \
                     VCLAW_WORKSPACE="$VCLAW_WORKSPACE" FFMPEG_FULL="${FFMPEG_FULL:-}" \
                     bash "$RAP_SCRIPTS/dryrun.sh" "$@"; }
        ( cd "$MAIN" && _proof --fixture solo && _proof --fixture duet && _proof --stamp ) \
          || die "the engine does not reach qc on the fixtures — no render slot will be spent on it. See
  $VCLAW_WORKSPACE/projects/rap-fixture-{solo,duet}-dryrun/build/dryrun.log, fix, and re-run."
        rm -rf "$VCLAW_WORKSPACE/projects/rap-fixture-solo" "$VCLAW_WORKSPACE/projects/rap-fixture-duet" \
               "$VCLAW_WORKSPACE/projects/rap-fixture-solo-dryrun" "$VCLAW_WORKSPACE/projects/rap-fixture-duet-dryrun"
      fi
      # RAP_PROOF=once (pack): prove the back half ONCE per film, not once per script
      # edit. Eight re-proofs in one night (~20 min each) were 3 h of the single day
      # this film had; each was for a one-line change in a stage the proof had already
      # passed. The stamp still records what was proven.
      if [ "${RAP_PROOF:-each}" = "once" ] && [ -s "$P/build/dryrun-ok" ]; then
        log "preflight: RAP_PROOF=once — the back half was proven on $(stat -f %Sm "$P/build/dryrun-ok"); not re-proving for this script change"
      elif [ "$(cat "$P/build/dryrun-ok" 2>/dev/null)" != "$runner_stamp" ]; then
        log "preflight: proving the back half on a SYNTHETIC copy first (once per pack
  x runner version, ~10 min of local ffmpeg, no renders, no spend)..."
        if bash "$RAP_SCRIPTS/dryrun.sh" "$PACK" "$SLUG" --synthetic; then
          echo "$runner_stamp" > "$P/build/dryrun-ok"
          rm -rf "$(project_dir "$SLUG-dryrun")"
          log "preflight: the back half reaches deliver+qc — proceeding"
        else
          die "the back half of the pipeline is BROKEN on a synthetic copy — no render
  slot will be spent on it. Debug the copy at $(project_dir "$SLUG-dryrun")
  (its build/dryrun.log has the failing stage), fix, and re-run."
        fi
      fi
    fi
  esac

  # DO THE NUMBERS AGREE? Four separate bugs this session were the same shape: two
  # values that must match, that nothing compared, in artifacts each of which looked
  # correct alone — a film covering 26% of its song, an 8s voice slice driving a 20s
  # window, a 12s library ceiling rejecting 14s clips, B-roll too short to fill a cut.
  # Every one was found by a human watching the output, hours after the renders.
  python3 "$RAP_SCRIPTS/plan_coherence.py" --plan "$P/build/plan.json" \
    $([ -f "$P/build/vocal-brief.json" ] && printf -- "--vocal-brief %s" "$P/build/vocal-brief.json") \
    --song "$SONG" ${BROLL_DIR:+--broll "$BROLL_DIR" \
    --vocal-map "$P/build/vocal-map.json" --broll-plan "$P/build/broll-plan.json"} \
    || die "the plan's numbers disagree (above). Fix them BEFORE rendering — each of \
those has shipped a finished, plausible, wrong film before."
  # B-roll rides the same approval: render-all hands both plans to lane_render, and a
  # job absent from the contract is refused there after the operator approved.
  python3 "$RAP_SCRIPTS/preflight_higgs.py" --plan "$P/build/plan.json" \
    $([ -f "$P/build/broll-plan.json" ] && printf -- "--broll %s" "$P/build/broll-plan.json") \
    --song "$P/build/hook.wav" --pronouns "${PERFORMER_PRONOUNS:-he|she}" --styles "$STYLES_FILE" \
    || die "preflight refused this plan — fix the windows it listed, then re-run"
  # HEAR EVERY SLICE BEFORE THE OPERATOR DOES. The page used to CLAIM which lines a
  # slice carried; the operator listened and found a couplet cut in half. slice_check
  # transcribes each render slice and compares it with its card; a mismatch is a
  # refusal, a match is a HEARD ✓ badge on the card (2026-08-23).
  # SLICE_CHECK=0 (pack): skip the per-slice whisper proof — it is minutes of listening
  # per re-plan, and the operator turned it off for the New Era restart ("not sure if it
  # helps", 2026-08-31). slices.html still shows every slice with a player; the first-take
  # gate measures the real render.
  if [ "${SLICE_CHECK:-1}" = "1" ]; then
    python3 "$RAP_SCRIPTS/slice_check.py" --plan "$P/build/plan.json" \
      --contract "$P/build/submit-contract.json" --out "$P/build/slice-check.json" \
      ${SONG_LANGUAGE:+--language "$SONG_LANGUAGE"} --model "$WHISPER_MODEL" \
      || die "a voice slice does not carry the lines its card claims (above) — the windows or the \
line table are wrong; do not show this page as correct"
  else
    log "slice check skipped (SLICE_CHECK=0) — slices.html is the review; the first take is the proof"
    rm -f "$P/build/slice-check.json"
  fi
  python3 "$RAP_SCRIPTS/preflight_higgs.py" --plan "$P/build/plan.json" \
    $([ -f "$P/build/broll-plan.json" ] && printf -- "--broll %s" "$P/build/broll-plan.json") \
    --song "$P/build/hook.wav" --pronouns "${PERFORMER_PRONOUNS:-he|she}" --styles "$STYLES_FILE" \
    --slice-check "$P/build/slice-check.json" >/dev/null \
    || die "preflight could not stamp the slice verdicts"
  # Watch what the contract is ACTUALLY built from. compose_prompts.py reads the
  # styles files and the keyframe dir; it never reads plan.json. Naming plan.json
  # here made the gate fire on EVERY first run, because stage 6b builds the contract
  # and stage 7 writes the plan two seconds later — so "STALE" was structural, not
  # real. A gate that cries wolf on the happy path is one people learn to click
  # through, and this is the gate standing between a typo and twenty-five paid jobs.
  # UNATTENDED=1 on the FREE lane (this call is --credits 0): the contract is approved on
  # the operator's standing word, with RAP_APPROVE_FORCE=1 and its own audit line — the
  # free-lane directive (2026-08-29). A paid route never reaches this branch.
  if [ "${UNATTENDED:-0}" = "1" ] && ! python3 "$RAP_SCRIPTS/spend_gate.py" --build-dir "$P/build" \
       --label "batch:$(basename "$P")" --credits 0 --input "$STYLES_FILE" --input "$P/build/styles-drawn.json" >/dev/null 2>&1; then
    _chash="$(python3 -c "import hashlib,sys;print(hashlib.sha256(open(sys.argv[1],'rb').read()).hexdigest()[:8])" "$P/build/submit-contract.json")"
    RAP_APPROVE_FORCE=1 python3 "$RAP_SCRIPTS/spend_gate.py" --build-dir "$P/build" --approve --hash "$_chash" \
      || die "UNATTENDED: could not approve contract $_chash on the free lane (see above)"
    printf '{"at":"%s","event":"contract-approved","hash":"%s","by":"UNATTENDED=1 on the free lane (the operator'"'"'s standing word; RAP_APPROVE_FORCE=1 logged by spend_gate)"}\n' \
      "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$_chash" >> "$P/project-audit.jsonl"
    log "preflight: contract $_chash approved unattended (free lane)"
  fi
  python3 "$RAP_SCRIPTS/spend_gate.py" --build-dir "$P/build" \
    --label "batch:$(basename "$P")" --credits 0 \
    --input "$STYLES_FILE" --input "$P/build/styles-drawn.json" \
    || gate "review the per-window submit contract before rendering" \
"Open '$P/build/submit-contract.html' — one card per WINDOW with the payload, the
  provider body, the sung lines and both references exactly as they will be sent.
  The page header prints the contract's 8-character hash. Then, from YOUR OWN
  terminal (an agent session is refused — approval is the operator's act):
    python3 '$RAP_SCRIPTS/spend_gate.py' --build-dir '$P/build' --approve --hash <8 hex from the page> [--allow w05,w06]
Re-run to submit."
  mark preflight
fi

# ---- 9. render every window (free lane: the vendored Higgsfield engine) ----
# THIS IS THE STAGE TWO FILMS DIED AT, and neither death was noticed at the time.
# It used to call explore_queue, a supervisor over `vclaw video batch-submit` — and
# `submitBatch` calls `submitSeedanceDirectNative` DIRECTLY, never consulting
# VCLAW_SEEDANCE_DIRECT_ADAPTER. So the free in-tree engine was unreachable through
# the runner's own supervisor: it refused on spend, never submitted, then polled a
# queue that was never created, which looks exactly like a slow queue. Both films
# stopped here and got a hand-built back half, which is where every defect an
# operator later found on screen came from.
#
# lane_render drives the adapter's own SUBMIT/POLL contract through the shared lane.
# explore_queue is still the PLAN VALIDATOR (lane_render imports load_plan), so every
# guard it grew — no synced-without-a-voiceRef, no keyframe reference, one video ref —
# still runs. Only the transport changed.
#
# One list, one slot: an optional build/broll-plan.json is rendered in the SAME queue
# rather than by a second driver. Two drivers on a single-slot lane starve each other
# and it reads exactly like moderation failure. Give that plan
# "queueDir": "<project>/build/broll" so `cover` finds its clips.
# ---- 8b. first-take (GATE) — ONE window renders, the operator judges it, then the rest -
# The operator's rule after the New Era film ("do one test first to see if this theory
# works"): render the first sung window alone, measure it with the primed word check, put
# its filmstrip and numbers on a page, and stop. Twelve lane-hours went into fifteen
# windows that all shared one defect (a padded render) and one face that was not his — a
# single take would have shown both in forty minutes. FIRST_TAKE_WINDOW in the pack picks
# the window (default: the first synced one); `touch build/first-take-approved` is his word.
if ! done_stage first-take; then
  # A pack that predates the approved recipe (no AUDIO_MODE at all) is refused here, before
  # a single lane-hour: the template carries it; an old pack must say record|vocal-swap.
  [ -n "${AUDIO_MODE:-}" ] || die "this pack has no AUDIO_MODE — it predates the approved recipe (2026-08-31).
    Set AUDIO_MODE=\"vocal-swap\" (the record's beat + each take's own voice; the default in
    skills/rap-avatar-mv/_template.rap.pack) or AUDIO_MODE=\"record\" on purpose."
  if [ -f "$P/build/first-take-approved" ]; then
    log "first-take: approved ($(cat "$P/build/first-take-approved" 2>/dev/null || echo yes))"
  else
    _ft="${FIRST_TAKE_WINDOW:-$(python3 -c "
import json,sys
p=json.load(open(sys.argv[1]))
print(next((j['id'] for j in p['jobs'] if j.get('voiceRef') and j.get('synced') is not False), p['jobs'][0]['id']))" "$P/build/plan.json")}"
    _ft_clip="$P/build/queue/explore/clips/$_ft.mp4"
    if [ ! -f "$_ft_clip" ]; then
      log "first-take: rendering $_ft alone (one draw; the rest waits for the operator)"
      python3 "$RAP_SCRIPTS/lane_render.py" --plan "$P/build/plan.json" --only "$_ft" --draws "${FIRST_TAKE_DRAWS:-1}" || true
    fi
    [ -f "$_ft_clip" ] || die "first-take: $_ft did not land — read build/lane-render.log (moderation is random: re-run; a dead session needs a login)"
    python3 "$RAP_SCRIPTS/first_take.py" --plan "$P/build/plan.json" --window "$_ft" --clip "$_ft_clip" \
      --portrait "$PORTRAIT" --out "$P/build/first-take.html" --json "$P/build/first-take.json" \
      --song "$P/build/hook.wav" \
      || die "first_take.py failed"
    # UNATTENDED=1: the primed measure decides — a take that follows its lines at a sane
    # rate is approved and logged; one that sings slow or drops words still stops, because
    # that means the sizing rule failed and the rest must not render on it.
    if [ "${UNATTENDED:-0}" = "1" ] && python3 - "$P/build/first-take.json" "${FIRST_TAKE_MAX_RATE:-1.25}" "${FIRST_TAKE_MIN_WORDS:-90}" <<'PY'
import json, re, sys
d = json.load(open(sys.argv[1]))
# NO MEASUREMENT IS NOT A PASS. A silent window measures nothing (rate None), and reading
# that as "on speed" auto-approved a first take that proved no lip-sync at all
# (2026-08-31). Only a window that was actually measured can clear this gate unattended.
if d.get("rate") is None:
    print(f"first-take measure: {d.get('window')} has no rate — it is an instrumental window and proves "
          f"nothing about lip-sync; pick a SUNG window (leave FIRST_TAKE_WINDOW empty) -> STOP", file=sys.stderr)
    raise SystemExit(1)
rate = float(d["rate"])
verdict = str(d.get("verdict") or "")
m = re.search(r"\((\d+)% of the words\)", verdict); words = int(m.group(1)) if m else 100
ok = rate <= float(sys.argv[2]) and words >= int(sys.argv[3])
# A CHANT CANNOT BE RATED. Two unique words repeated seven times gave rate x6.2 (a
# nonsense number) while the judge said "too little vocabulary — leaving the verdict to
# the timing check, on the bar" (Baby Nimbooda part 2 w09, 2026-09-06). When the judge
# has deferred to timing and passed, the timing verdict is the measure.
if not ok and "too little vocabulary" in verdict and d.get("ok"):
    ok = True
    print(f"first-take measure: the word-rate cannot judge a chant ({verdict[:90]}) — the timing check passed -> approved", file=sys.stderr)
else:
    print(f"first-take measure: rate x{rate:.3f} (max {sys.argv[2]}), words {words}% (min {sys.argv[3]}) -> {'approved' if ok else 'STOP'}", file=sys.stderr)
raise SystemExit(0 if ok else 1)
PY
    then
      echo "$(date +%F) UNATTENDED=1 — approved on the primed measure" > "$P/build/first-take-approved"
      printf '{"at":"%s","event":"first-take-approved","window":"%s","by":"UNATTENDED=1 (primed measure within FIRST_TAKE_MAX_RATE/MIN_WORDS)"}\n' \
        "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$_ft" >> "$P/project-audit.jsonl"
    else
    # the sync page for this window: the take SILENT against the record / the stems / its own
    # voice, the sheet's words lit on whisper's clock — so the ear judges it, not the model's own audio
    python3 "$RAP_SCRIPTS/sync_review.py" --project "$P" --windows "$_ft" --no-master >/dev/null 2>&1 || true
    # THE MEASURE'S STOP IS A STOP. Under UNATTENDED=1 the generic gate below auto-passes,
    # which let a STOP verdict (rate x6.2) roll straight into render-all (2026-09-06). A
    # take the measure refuses waits for a human: his word is `first-take-approved`.
    [ "${UNATTENDED:-0}" = "1" ] && die "first-take: the primed measure said STOP for $_ft — a human must look at
    $P/build/first-take.html (face, speed, the slice it sang to). His word:
      echo \"$(date +%F) <your word>\" > $P/build/first-take-approved   and re-run.
    Not auto-approved: UNATTENDED covers the free gates, not a failed measure."
    gate "judge the first take: $_ft" "Open $P/build/first-take.html — the take's filmstrip (one frame a second) beside the
  portrait, the primed word measure (rate, spread, drift) and the slice it sang to.
  * sync: $P/build/sync-review.html — the picture silent; fade in the record, the stem, or its own voice.
  * FACE: is it him in every frame?   * SPEED: rate 0.97-1.03 and spread < 300 ms?
  * If yes:   echo \"$(date +%F) <your word>\" > $P/build/first-take-approved   and re-run.
  * If the face drifts: fix the portrait (a sharper frame / a character sheet) and --from plan.
  * If it sings slow: the sung-length rule has failed — say so; do not render the rest."
    fi
  fi
  mark first-take
fi

if ! done_stage render-all; then
  log "render-all: every window on the free Higgsfield lane — this runs for hours"
  node "$MAIN/dist/cli/vclaw.js" video portal --project "$SLUG" --root "$VCLAW_WORKSPACE" \
    --surface run >/dev/null 2>&1 || true
  python3 "$RAP_SCRIPTS/lane_nav.py" "$P"/*.html "$P"/build/*.html >/dev/null 2>&1 || true   # one menu on every page
  log "run dashboard: $P/run.html"
  render_args=(--plan "$P/build/plan.json")
  # B-roll rides the SAME work list on the one slot. The plan is authored by the
  # broll-plan stage (gaps-only); BROLL_PER_STYLE is retired — the stage replaced it.
  [ -f "$P/build/broll-plan.json" ] && render_args+=(--plan "$P/build/broll-plan.json")
  # --replace wNN renders THAT window. Without --only the pass swept everything the plan
  # lacked, and a deferred cutaway took the slot for 30 minutes before the replaced take
  # (Baby Ram & Sita, 2026-09-01).
  # ... on the FIRST pass only: the retries below run without --only, so the windows
  # the replaced one displaced (an earlier pass's refusals, a parked stale cutaway)
  # are rendered once it has landed.
  first_args=("${render_args[@]}")
  [ -n "${RENDER_ONLY:-}" ] && first_args+=(--only "$RENDER_ONLY")
  # Exit 10 = some window never landed. That is a GATE, not a crash: the film can
  # still be cut from what did land, and re-running renders only what is missing.
  #
  # Captured with `|| rc=$?`, NOT with `if ! cmd; then rc=$?`. The `!` inverts the
  # status, so inside that branch $? is 0 and every failure reads as exit 10 — the
  # same class of mistake as reading $? after a pipe and getting `tail`'s status.
  rc=0
  python3 "$RAP_SCRIPTS/lane_render.py" "${first_args[@]}" || rc=$?
  if [ -f "$P/build/STOP" ]; then
    log "render-all: STOPPED on request (build/STOP) — the clip in flight landed, nothing else was submitted. rm build/STOP and re-run to resume."
    exit 0
  fi
  # UNATTENDED=1: moderation is random (~50 % a draw) — re-run while a pass lands
  # something new, up to UNATTENDED_RENDER_PASSES; never rewrite a prompt.
  if [ "${UNATTENDED:-0}" = "1" ] && [ "$rc" = "10" ]; then
    _pass=1; _landed="$(ls "$P/build/queue/explore/clips" "$P/build/broll/clips" 2>/dev/null | grep -c '\.mp4$')"
    while [ "$rc" = "10" ] && [ "$_pass" -lt "${UNATTENDED_RENDER_PASSES:-6}" ]; do
      _pass=$((_pass + 1)); log "render-all: pass $_pass (UNATTENDED=1) — retrying what did not land"
      rc=0; python3 "$RAP_SCRIPTS/lane_render.py" "${render_args[@]}" || rc=$?
      _now="$(ls "$P/build/queue/explore/clips" "$P/build/broll/clips" 2>/dev/null | grep -c '\.mp4$')"
      [ "$_now" = "$_landed" ] && [ "$rc" = "10" ] && { warn "render-all: pass $_pass landed nothing new — stopping the retries"; break; }
      _landed="$_now"
    done
  fi
  # PAID_WINDOWS (pack): the named windows the free lane did not land are bought ONE at a
  # time on the Higgsfield API pool (paid_take.py — quoted, bound to the approved contract,
  # judged, logged like any draw). The standing word (UNATTENDED=1) covers the FREE lane
  # only — a paid take is attended (always-use-the-free-lane), so the two are refused together.
  if [ -n "${PAID_WINDOWS:-}" ]; then
    [ "${UNATTENDED:-0}" = "1" ] && die "PAID_WINDOWS=$PAID_WINDOWS with UNATTENDED=1: the standing word covers the free lane only — run this pass attended, or unset PAID_WINDOWS"
    _paid_landed=0
    for _pw in ${PAID_WINDOWS//,/ }; do
      [ -z "$_pw" ] && continue
      if [ -s "$P/build/queue/explore/clips/$_pw.mp4" ]; then log "render-all: $_pw is on disk — not bought"; continue; fi
      log "render-all: $_pw on the PAID Higgsfield pool (paid_take.py, one take)"
      if python3 "$RAP_SCRIPTS/paid_take.py" --plan "$P/build/plan.json" --window "$_pw" --confirm-spend; then
        _paid_landed=$((_paid_landed + 1))
      else
        warn "render-all: the paid take for $_pw did not land (exit $?) — see $P/build/lane-render.log"
      fi
    done
    # A paid take that landed fills a hole the free pass reported: re-read the work list
    # (nothing is submitted — every clip on disk is verified, only the missing ones exit 10).
    if [ "$_paid_landed" -gt 0 ] && [ "$rc" = "10" ]; then
      rc=0; python3 "$RAP_SCRIPTS/lane_render.py" "${render_args[@]}" --dry-run || rc=$?
    fi
  fi
  # the Draws page is derived from the queue + lane log — rebuild it after every pass
  python3 "$RAP_SCRIPTS/draws_review.py" --project "$P" >/dev/null 2>&1 || true
  python3 "$RAP_SCRIPTS/sync_review.py" --project "$P" --no-master >/dev/null 2>&1 || true
  # Clear the one-shot marker on a clean render, or a run that succeeded after an
  # earlier shortfall would leave it behind and silently rob some LATER failure of its
  # free retry. A one-shot that is never re-armed is a one-shot that fires once, ever.
  [ "$rc" = "0" ] && rm -f "$P/build/render-all-incomplete"
  if [ "$rc" != "0" ]; then
    [ "$rc" = "10" ] || die "lane_render failed (exit $rc) — see $P/build/lane-render.log"
    # THE GATE HAS TO BE ABLE TO END. `mark render-all` sat after this block, and gate()
    # exits — so a window that could not render trapped the film here for ever: re-run,
    # retry, gate, re-run, retry, gate. The text below promised "continue ... by
    # re-running once more" and the code could not honour it. Two films died just BEFORE
    # this stage; this is the same death one stage later.
    #
    # So the promise is now kept literally. The first failure retries (that is what the
    # operator usually wants — moderation is a coin flip and a re-run is free). The
    # second says the lane has been given its chances and cuts the film from what landed.
    # A REPLACED WINDOW THAT DID NOT LAND IS A STOP, NOT A GATE. The gate below exists
    # for a lane that is short of a few windows on a first pass; a window the operator
    # asked to replace and did not get back cannot be "continued without" — the old
    # take is parked and select_cut refuses a hole (v8, 2026-09-02).
    for _w in ${RENDER_ONLY//,/ }; do
      [ -n "$_w" ] && [ ! -s "$P/build/queue/explore/clips/$_w.mp4" ] \
        && die "render-all: $_w was to be replaced and has not landed — see $P/build/lane-render.log; re-run to try again (nothing else is touched)"
    done
    tried="$P/build/render-all-incomplete"
    if [ -f "$tried" ]; then
      warn "render-all: still short after a retry — continuing with the windows that
  landed. The missing ones are listed in $P/build/lane-render.log; \`select\` will
  refuse if what is left cannot make a coherent film."
      rm -f "$tried"
    else
      : > "$tried"
      gate "some windows did not render" \
"lane_render listed them above and they are ALSO in $P/build/lane-render.log.
Every clip that DID land is on disk and will not be re-rendered — re-running this
command renders only what is missing.

  * 'moderation refused' — random, ~50% a draw. Re-run; do NOT rewrite the prompt.
  * 'never got the lane'  — another machine is rendering. Re-run later.
  * 'session is GENUINELY dead' — a human must log in to higgsfield.ai in Chrome.

Re-run to try them again, or continue with fewer windows by re-running once more."
    fi
  fi
  mark render-all
fi

# ---- 10b. library (free): index every clip this project already has ---------
# The best shot for a window is often one you already own — an earlier pass, a render
# rejected for a different window, something still in the provider account. The cut
# stage used to see only one output directory.
if ! done_stage library; then
  # THE CEILING MUST KNOW HOW LONG A WINDOW IS. index_library defaults --max-seconds
  # to 12, which was right when every window was 8s: it is what stops a 20s clip from
  # ANOTHER film scoring its way in on audio correlation alone. But it is a fixed
  # number describing a variable thing, and at 14s windows it rejects the film's OWN
  # clips — the library comes back empty and `select` refuses, hours after the renders
  # finished. Same family as the Runway cap: a constant that does not know what it is
  # protecting. Derived here, with two seconds for the provider's overshoot (a 14s
  # request lands at 14.08s).
  # Provider MP4s commonly overshoot the requested duration by a few frames. B-roll
  # asks for 16s beside 14s performance windows and lands at 16.064s, so a 16.0s
  # ceiling rejects the film's own scenery. Keep the two-second structural allowance
  # plus five frames at 24fps; foreign long-form clips remain excluded.
  lib_max="$(awk -v c="$CLIP_SECONDS" -v f="$MV_FPS" 'BEGIN{printf "%.3f", c + 2 + 5/f}')"
  python3 "$RAP_SCRIPTS/index_library.py" --project "$P" --slug "$SLUG" \
    --aspect "$ASPECT" --max-seconds "$lib_max" \
    --plan "$P/build/plan.json" --brief "$P/build/vocal-brief.json" --song "$P/build/hook.wav" \
    --gallery "$P/build/library.html" || die "index_library failed"
  mark library
fi

# ---- 10b2. transcribe (free): what is each clip ACTUALLY singing? -----------
# The model generates the vocal on this route, so a clip's own audio IS the
# performance and whisper recovers the words. Every downstream edit decision then
# stops being a guess about energy and becomes a lookup: which bar, is he singing at
# all, how far off and in what shape. The film this was learned on had a shot cut by
# envelope correlation, measured "0ms", declared fixed and delivered — its words put
# it 730ms early, and the operator found it on screen.
if ! done_stage transcribe; then
  require_whisper
  # THE QUEUE DIR FIRST — it is where lane_render actually lands clips
  # (<queueDir>/clips/<id>.mp4, the same path index_library and provenance use). This
  # stage was written during a hand-driven session and listed only the locations that
  # session happened to use, so the first time it ran under the runner it transcribed
  # the song and NOTHING ELSE: an empty store, no error, and every word-level verdict
  # downstream silently unavailable. The other paths stay for projects that were driven
  # by hand; a directory that does not exist is skipped, not an error.
  tx_args=(--song "$SONG" --out "$P/artifacts/clip-transcripts.json")
  for d in "$P"/build/queue/*/clips "$P/build/shifted-"* "$P/build/higgs/stage" \
           "$P/build/clips" "$P/build/broll/clips"; do
    [ -d "$d" ] && tx_args+=(--clips "$d")
  done
  [ -f "$P/references/lyrics.txt" ] && tx_args+=(--song-prompt "$P/references/lyrics.txt")
  python3 "$RAP_SCRIPTS/transcribe_clips.py" "${tx_args[@]}" --model "$WHISPER_MODEL" \
    || die "transcribe_clips failed — word-level sync decisions are unavailable"
  # An empty store is not a store. Every verdict that decides whether a bad window
  # costs nothing or costs ~100min of a single-slot queue reads this file.
  python3 -c "
import json,sys
d=json.load(open('$P/artifacts/clip-transcripts.json'))
if not d.get('clips'):
    sys.exit('transcribe: the store has NO CLIPS. Nothing was found in: ${tx_args[*]}')
print(f\"transcribe: {len(d['clips'])} clip(s) in the store\")" || die "transcribe produced an empty store"
  mark transcribe
fi

# ---- 10c. select (free): choose a clip per window, refuse a cut that can't be right --
# AUDIO_MODE=vocal-swap: a take's correlation against the RECORD is not this film's sync.
check_sync_swap=()
[ "$(film_mode)" = "vocal-swap" ] && check_sync_swap=(--no-sync "AUDIO_MODE=vocal-swap: the film carries each take's own voice (audio-swap stage), so a correlation against the record measures the swap, not the sync")
if ! done_stage select; then
  # CUT_OWN_TAKES=1 (pack): every window takes ITS OWN take — one film walking through
  # its worlds, no choice to make — so the cut files are authored from the library index
  # and the gate is passed honestly, unattended (New Era, 2026-08-31).
  if [ "${CUT_OWN_TAKES:-0}" = "1" ]; then
    python3 "$RAP_SCRIPTS/author_cuts.py" --plan "$P/build/plan.json" --library "$P/build/library-index.json" \
      --styles-drawn "$P/build/styles-drawn.json" --build "$P/build" --fps "$MV_FPS" || die "author_cuts failed"
  fi
  # Under AUDIO_MODE=vocal-swap the film's audio will follow the picture, so a take
  # that does not correlate with the RECORD is not a refusal here.
  [ "$(film_mode)" = "vocal-swap" ] && SYNC_ADVISORY=1
  for sid in $(drawn_styles); do
    [ -f "$P/build/cut-$sid.json" ] || [ "${CUT_AUTO:-0}" = "1" ] || \
      gate "author the cut for '$sid'" \
"Open $P/build/library.html — every candidate clip, one frame per SECOND of it.
  Read each strip left to right: a prop that hangs unsupported, a figure walking in
  from the edge, a shot that changes style — none of that is audible, so nothing
  upstream of your eyes has looked for it. The old three-frame strip passed a clip
  whose bat floated for two seconds.
  Then write $P/build/cut-$sid.json:
      {\"assignments\": [{\"window\": 0, \"clipId\": \"c012\"}, ...]}

  * A window whose mouth MOVES is only usable on the bar it was rendered against.
    'synced' is carried from render provenance, never guessed from a picture — pass
    --force-synced only when you have proved it by hand.
  * Every other window needs a CLOSED MOUTH, not a hidden face: waist-up or closer,
    face legible, lips together.
  * Or run with CUT_AUTO=1 for a derived fallback."
    python3 "$RAP_SCRIPTS/select_cut.py" --project "$P" --style "$sid" --fps "$MV_FPS" \
      --index "$P/build/library-index.json" --hook-json "$HOOK_JSON" \
      --transcript "$TRANSCRIPT" --assign "$P/build/cut-$sid.json" \
      --plan "$P/build/plan.json" --vocal-map "$P/build/vocal-map.json" \
      --out-selection "$P/build/selection-$sid.json" \
      --out-manifest "$P/build/sync-$sid.json" \
      --out-windows "$P/build/windows-$sid.json" \
      --gallery "$P/build/cut-$sid.html" ${CUT_AUTO:+--auto} \
      || die "select_cut refused the cut for '$sid' (see above)"
    # MEASURED, not eyeballed: a clip on the wrong bar correlates ~0.2 against ~0.98.
    #
    # --offset-advisory because SLIDE HAS NOT RUN YET. The fatal question here is
    # whether the take is on this bar at all (correlation); a steady offset is the very
    # thing the next stage takes up for free. Without it the pipeline deadlocks: eight
    # windows measured 0.61-0.92 — every one on its own bar — and `select` refused the
    # film because six of them were more than 80ms out, which is precisely what `slide`
    # exists to fix. The offsets are still printed, tagged `note`, and `sync-gate`
    # judges what survives at the 80ms delivery bar.
    # SYNC_ADVISORY=1: the operator has judged the takes himself and wants the film
    # built — the refusal becomes a printed warning. `sync-gate` still measures the
    # finished master at the 80ms delivery bar, so nothing ships unmeasured; this only
    # moves the argument from numbers-before-the-cut to the cut itself. Never the
    # default: a take that is genuinely on another bar has to be caught somewhere.
    # AUDIO_MODE=vocal-swap: the film carries each take's OWN voice, so correlating a
    # take against the RECORD measures the swap, not the sync — it printed "NOT SYNCED,
    # its mouth is moving to different words" for a window whose audio matched its own
    # take at corr 0.97 (2026-09-01). Say so instead of crying wolf.
    if ! python3 "$RAP_SCRIPTS/check_sync.py" --song "$P/build/hook.wav" \
      --manifest "$P/build/sync-$sid.json" --offset-advisory \
      ${check_sync_swap[@]+"${check_sync_swap[@]}"} \
      --json-out "$P/build/sync-report-$sid.json"; then
      [ "${SYNC_ADVISORY:-0}" = "1" ] || die "check_sync refused the cut for '$sid' — a window is not synced to its own bar"
      log "check_sync refused '$sid' — SYNC_ADVISORY=1, continuing on the operator's call (the sync-gate still measures the master)"
    fi
  done
  # ONE FILM WHEN THE VARIANTS ARE IDENTICAL — and, just as important, N films when
  # they are NOT. collapse_styles.py proves which case this is (exact comparison of the
  # selections minus their style field) and writes/removes styles-effective.json, which
  # film_styles() serves to every later stage. Extracted so BOTH directions are tested:
  # a collapse that fired on real variety would silently drop whole films.
  python3 "$RAP_SCRIPTS/collapse_styles.py" --build "$P/build" || \
    warn "collapse_styles failed — continuing with every drawn style"
  mark select   # before the gate: gate() exits, so a mark after it never runs
  gate "approve the cut" \
"Open $P/build/cut-*.html — the chosen clip per window, with its provenance and
whether it is lip-synced. Sync has already been MEASURED; this gate is for the
pictures. Re-run to approve."
fi

# ---- 10d. slide (free): put every steady-offset clip ON its bar before cutting --
# ALWAYS runs before the cut, and always before anyone considers a re-render. A clip
# sitting at a steady 300ms is in the wrong PLACE, not badly performed; sliding it is
# free and takes seconds, where a re-render is ~100min of a single-slot queue and a
# coin flip on moderation. sync_shift refuses to slide a clip whose offsets disagree,
# so what survives to the re-render list genuinely needs one.
if ! done_stage slide; then
  # AUDIO_MODE=vocal-swap: the film's audio follows the picture (audio-swap stage), so a
  # take is never retimed or slid against the record — a slide would move the take's
  # frames AND its voice off the window geometry vocal_swap reads (2026-08-31).
  if [ "$(film_mode)" = "vocal-swap" ]; then
    log "slide: no retime/slide under AUDIO_MODE=vocal-swap — instead every cut moves later so the take finishes its last word (join_cuts)"
    for sid in $(film_styles); do
      [ -f "$P/build/selection-$sid.json" ] || continue
      # 1. fit every take to the record's tempo and line onset (picture+voice together)
      python3 "$RAP_SCRIPTS/fit_takes.py" --selection "$P/build/selection-$sid.json" --plan "$P/build/plan.json" \
        --store "$P/artifacts/clip-transcripts.json" --out-dir "$P/build/fitted-$sid" \
        --out-selection "$P/build/selection-$sid.json" --json "$P/build/fits-$sid.json" --fps "$MV_FPS" \
        ${FIT_MAX_RATE:+--max-rate "$FIT_MAX_RATE"} || die "fit_takes failed for '$sid'"
      # 2. whatever still runs past a cut: move the cut, trim the next lead-in
      python3 "$RAP_SCRIPTS/join_cuts.py" --selection "$P/build/selection-$sid.json" --plan "$P/build/plan.json" \
        --store "$P/artifacts/clip-transcripts.json" --extra-words "$P/build/fitted-$sid/words.json" \
        --out-dir "$P/build/joined-$sid" \
        --out-selection "$P/build/selection-$sid.json" --json "$P/build/joins-$sid.json" --fps "$MV_FPS" \
        || die "join_cuts failed for '$sid'"
    done
  fi
  for sid in $([ "$(film_mode)" = "vocal-swap" ] || film_styles); do
    [ -f "$P/build/selection-$sid.json" ] || continue
    # RATE FIRST, THEN OFFSET. A take that sings the right words at a uniformly wrong
    # SPEED (the free lane sang a croon 9-12% slower than the track on nine renders,
    # 2026-08-29) is a slope no slide can fix and no redraw fixed either; rate_fit
    # retimes video+audio by the fitted rate and leaves the constant offset to sync_shift.
    # Noisy fits (a wander) and tiny rates (a slide's job) are left alone.
    #
    # THE SYNC REPORT SAYS WHAT IS ALREADY ON THE BAR. Grid w12 was already passing
    # (corr 0.74, before slide) and got retimed anyway on a clean-looking fit over a
    # 9-of-29 mis-pairing, landing below the master gate (film #3, 2026-09-07). `select`
    # writes this report a stage earlier; pass it along when it exists so rate_fit can
    # leave a passing window alone.
    rate_fit_sync=()
    [ -f "$P/build/sync-report-$sid.json" ] && rate_fit_sync=(--sync-report "$P/build/sync-report-$sid.json")
    python3 "$RAP_SCRIPTS/rate_fit.py" --selection "$P/build/selection-$sid.json" \
      --store "$P/artifacts/clip-transcripts.json" --song-words "$P/build/song-words.json" \
      --stage "$P/build/clips" --out-dir "$P/build/rated-$sid" --fps "$MV_FPS" \
      --out-selection "$P/build/selection-$sid.json" --json "$P/build/rate-report-$sid.json" \
      ${rate_fit_sync[@]+"${rate_fit_sync[@]}"} \
      || die "rate_fit failed for '$sid'"
    python3 "$RAP_SCRIPTS/sync_shift.py" --song "$P/build/hook.wav" \
      --selection "$P/build/selection-$sid.json" --vocal-map "$P/build/vocal-map.json" \
      --stage "$P/build/clips" --out "$P/build/shifted-$sid" \
      --out-selection "$P/build/selection-$sid.json" \
      --json "$P/build/shift-report-$sid.json" \
      || die "sync_shift failed for '$sid'"
  done
  # the sync page now has the shifted / fitted copies and the shift reports to read
  python3 "$RAP_SCRIPTS/sync_review.py" --project "$P" --no-master >/dev/null 2>&1 || true
  mark slide
fi

# ---- 10d2. needs (free): one verdict per window, and the exact next command ------
# The four questions after a render — on the bar? slide? cover where? re-render with
# what change? — each had an answer in a different file and a person joined them by
# hand, four deliveries in a row. needs_report joins the render records, the slide
# report, the library's fit table, the salvage spans and the vocal map into ONE page.
# Do the free fixes first (slide), then covers, then reuse, and only then a re-render
# with the named change. It gates only when a cover needs a DEFERRED cutaway rendered.
if ! done_stage needs; then
  needs_asks=""
  for sid in $(film_styles); do
    python3 "$RAP_SCRIPTS/needs_report.py" --project "$P" --slug "$SLUG" --style "$sid" --pack "$PACK" --audio-mode "$(film_mode)" \
      --plan "$P/build/plan.json" --broll-plan "$P/build/broll-plan.json" \
      --library "$P/build/library-index.json" --shift-report "$P/build/shift-report-$sid.json" \
      --rate-report "$P/build/rate-report-$sid.json" \
      --vocal-map "$P/build/vocal-map.json" --salvage "$P/build/salvage-cover.json" \
      --out "$P/build/needs-$sid.html" --json-out "$P/build/needs-$sid.json" \
      || die "needs_report failed for '$sid'"
    asks="$(python3 -c "import json;print(' '.join(json.load(open('$P/build/needs-$sid.json')).get('deferredAsks',[])))")"
    [ -n "$asks" ] && needs_asks="$needs_asks $asks"
  done
  python3 "$RAP_SCRIPTS/lane_nav.py" "$P"/build/needs-*.html >/dev/null 2>&1 || true
  log "needs: $P/build/needs-<style>.html"
  mark needs   # before the gate: gate() exits, so a mark after it never runs
  if [ -n "$needs_asks" ] && [ "${DRYRUN_SYNTHETIC:-0}" != "1" ]; then
    needs_only="$(printf '%s\n' $needs_asks | sort -u | paste -sd, -)"
    if [ "${UNATTENDED:-0}" = "1" ]; then
      log "needs: rendering the deferred cutaway(s) a cover needs (UNATTENDED=1): $needs_only"
      python3 "$RAP_SCRIPTS/lane_render.py" --plan "$P/build/broll-plan.json" --only "$needs_only" \
        || warn "needs: a deferred cutaway did not land — cover falls back to another world's"
    else
    gate "render the deferred cutaway(s) a cover needs: $needs_only" \
"The NEEDS report ($P/build/needs-<style>.html) covers a window whose own world's cutaway
  was approved with the contract but DEFERRED (not rendered). Render just those — one slot,
  ~30 min each — then re-run:
    python3 '$RAP_SCRIPTS/lane_render.py' --plan '$P/build/broll-plan.json' --only $needs_only
  Or pin another world's cutaway with COVER_PINS / COVER_SPANS and re-run without rendering."
    fi
  fi
fi

# ---- 10e. cover (free): cut away where the song is not singing --------------
# A DIFFERENT defect class from sync, and invisible to both sync gates: the window is
# on its bar, but for part of it there is no vocal at all and the performer is mouthing
# anyway. Correlation against silence is meaningless rather than bad, so nothing flags
# it, and a re-render does not help — the model performed what it was asked for. An
# operator found this in a delivered master that three gates had passed.
if ! done_stage cover; then
  # AUDIO_MODE=vocal-swap: the take's own voice plays wherever its mouth moves, so
  # "mouthing over the record's silence" is not a defect to cover; and cover_mouthing
  # works in the slide stage's shifted-<sid> dir, which vocal-swap never creates. An
  # operator-directed COVER_PINS/COVER_SPANS still runs, against the plain clips.
  if [ "$(film_mode)" = "vocal-swap" ] && [ -z "${COVER_PINS:-}${COVER_SPANS:-}" ]; then
    log "cover: skipped — AUDIO_MODE=vocal-swap (the take's voice follows its mouth; no auto-derived covers)"
  fi
  for sid in $(film_styles); do
    [ -f "$P/build/selection-$sid.json" ] || continue
    # ... and under vocal-swap with no direction, a style whose record already holds
    # covers still runs: a re-fit rebuilt the clip clean while the record and the swap
    # said "covered" (review finding, 2026-09-02) — the replay puts the covers back.
    if [ "$(film_mode)" = "vocal-swap" ] && [ -z "${COVER_PINS:-}${COVER_SPANS:-}" ] \
        && [ ! -s "$P/build/cutaways-$sid.json" ]; then continue; fi
    cover_stage_dir=""                                        # per style: never inherit the previous style's dir
    [ -d "$P/build/broll/clips" ] || { say "no B-roll to cut away to — skipping cover for '$sid'"; continue; }
    [ -d "$P/build/shifted-$sid" ] || cover_stage_dir="$P/build/clips-$sid"   # per style: a shared dir handed style 2 style 1's pristine take (review finding, 2026-09-02)
    # COVER_PINS (pack/env, optional): "wNN=<file>,wNN=<file>" — pin a chosen cutaway
    # to a window (e.g. the burning-lane walk as the film's closing tail).
    # COVER_SPANS (pack/env, optional): "wNN:START-END[:BROLL],..." — EXPLICIT spans the
    # operator directed (a drifting stretch, a short gap the auto-derivation will not
    # touch, a mangled turn). Applies even to exempt windows; idempotent re-runs
    # rebuild from each clip's .precover.mp4. wNN is the PLAN's window id (the one every
    # page shows) — resolved to the cut's grid through the selection, so on a film with
    # gap sections it no longer means the grid index (2026-09-02); START-END are song
    # seconds or the film clock (1:48-1:53) once a delivery's cards.json exists.
    cover_pins=()
    _pins="${COVER_PINS:-}"; _spans="${COVER_SPANS:-}"      # bash >= 4.4 refuses ${unset//x/y} under set -u
    for pin in ${_pins//,/ }; do cover_pins+=(--cover "$pin"); done
    for spn in ${_spans//,/ }; do cover_pins+=(--span "$spn"); done
    # RESOLUTION is <w>x<h> in the pack; cover_mouthing defaults to 720x1280 PORTRAIT,
    # which silently letterboxed/rescaled a 16:9 film's covered clips (noir, 2026-08-25).
    # ONE RECORD PER STYLE. Every style wrote and read the same cutaways.json, keyed by
    # window id — so style 2 saw style 1's spans as already covered, dropped its own
    # derived spans and went uncovered while the gates read a record that described
    # another film (2026-08-29). The record now lives beside its selection by style.
    # PAUSE_COVER (pack/env, optional seconds): a silence INSIDE a window, too short to
    # open its own --min-cover section, still gets a cutaway — measured against the
    # vocal stem directly (build/stems/vocals.wav) rather than waiting on the vocal
    # map's section-level gaps. See MIN_PAUSE_COVER_S in cover_mouthing.py.
    python3 "$RAP_SCRIPTS/cover_mouthing.py" --selection "$P/build/selection-$sid.json" \
      ${cards_args[@]+"${cards_args[@]}"} \
      --vocal-map "$P/build/vocal-map.json" --stage "${cover_stage_dir:-$P/build/shifted-$sid}" \
      --broll "$P/build/broll/clips" --fps "$MV_FPS" --record "$P/build/cutaways-$sid.json" \
      --width "${RESOLUTION%x*}" --height "${RESOLUTION#*x}" ${cover_pins[@]+"${cover_pins[@]}"} \
      ${PAUSE_COVER:+--pause-cover "$PAUSE_COVER"} \
      $([ "$(film_mode)" = "vocal-swap" ] && printf -- "--no-derived") \
      || die "cover_mouthing failed for '$sid'"
  done
  mark cover
fi

# ---- 11. cut (free: the beat-exact assembler) -----------------------------
if ! done_stage cut; then
  for sid in $(film_styles); do
    cfg="$P/build/mv-$sid.json"
    if [ -f "$P/build/selection-$sid.json" ]; then
      # Versioned, and it REFUSES to overwrite. The cut used to write
      # $SLUG-$sid.mp4 in place, so a re-run destroyed the previous master — and
      # this lane iterates: on the film this came from the operator asked, at v7,
      # for a clip to be brought back from v2.
      mv_next=$(python3 "$RAP_SCRIPTS/master_version.py" next \
        --project "$P" --slug "$SLUG" --style "$sid") || die "master_version next failed"
      master=$(python3 -c "import json,sys;print(json.loads(sys.argv[1])['path'])" "$mv_next")
      # THE MASTER MUST BE THE PROJECT'S SHAPE. build_mv_config defaults to 1920x1080
      # and nothing here ever told it otherwise, so a 9:16 project cut its portrait
      # clips into a LANDSCAPE master — and `bookends` then cropped that landscape
      # frame back to portrait for the film. The result is a double crop: the first
      # threw away the top of the head and everything below the chest, the second left
      # an extreme close-up of a nose and a mouth. Every duration, frame-count and
      # stream check passed it, because none of them look at shape.
      # (See [[verify-delivered-aspect-at-the-pixels]] — this is the third time.)
      mv_res="${RESOLUTION:-}"
      if [ -z "$mv_res" ]; then
        case "${ASPECT:-9:16}" in
          9:16) mv_res=1080x1920 ;;
          1:1)  mv_res=1080x1080 ;;
          *)    mv_res=1920x1080 ;;
        esac
      fi
      mv_w="${mv_res%%x*}"; mv_h="${mv_res##*x}"
      case "$mv_w$mv_h" in *[!0-9]*|"") die "RESOLUTION='$mv_res' is not <width>x<height>";; esac
      python3 "$RAP_SCRIPTS/build_mv_config.py" --hook-json "$HOOK_JSON" \
        --selection "$P/build/selection-$sid.json" --out "$cfg" --fps "$MV_FPS" \
        --width "$mv_w" --height "$mv_h" \
        --output "$master" || die "build_mv_config failed"
      # The one-cut-per-window pinning rests on planner internals; depending on that
      # without checking is how a silent wrong-clip ships.
      python3 "$RAP_SCRIPTS/select_cut.py" --verify-plan --config "$cfg" \
        --selection "$P/build/selection-$sid.json" \
        || die "the assembler's plan no longer matches the selection (see above)"
      # --verify-lip-sync measures each cut against the bar it sits on and refuses a
      # master whose mouth is on the wrong words — the defect that shipped twice
      # before it was measurable. Set RAP_SKIP_SYNC=1 only to inspect a known-bad cut.
      # The bar follows RAP_BAR: the operator's relaxed keep-bar (0.5) or the default
      # 0.6 — the whole dhurandhar-couple rebuild ran RAP_SKIP_SYNC=1 because the
      # assembler's fixed 0.6 refused windows the delivery gate passes at 0.5, which
      # threw away the wrong-words protection along with the bar dispute.
      # AUDIO_MODE=vocal-swap: the film's audio is rebuilt from the takes' own vocals after
      # this stage, so the assembler's lip-sync veto (take vs record) is moot here.
      if [ "${RAP_SKIP_SYNC:-0}" = "1" ] || [ "$(film_mode)" = "vocal-swap" ]; then verify_sync=""; else verify_sync=--verify-lip-sync; fi
      sync_min=$([ "${RAP_BAR:-}" = "keep" ] && echo 0.5 || echo 0.6)
      # --sync-offset-advisory: the assembler still REFUSES a cut whose mouth is on the
      # wrong words (that is what this check is for), but a cut that is on its bar and
      # merely off the beat is reported rather than fatal. `slide` has already taken up
      # everything it can by now, and this lane renders each window at the cut's own
      # length — a 14.08s clip in a 14s cut has 0.08s of slack, so the "move the cut
      # point" remedy the assembler suggests cannot physically be carried out. Measured
      # on this film: only 2 of 8 windows landed inside 80ms naturally, so blocking here
      # refuses very nearly every film. `sync-gate`, three lines down, is where the 80ms
      # delivery bar belongs.
      if ! node "$MAIN/dist/cli/vclaw.js" video music-video --config "$cfg" --execute \
           $verify_sync --sync-min "$sync_min" --sync-offset-advisory; then
        # The assembler writes the master BEFORE verifying it (as it already does
        # for the drift assertion), so a failed lip-sync leaves a finished file
        # sitting on a version number with no VERSIONS entry and no selection
        # sidecar. `latest` would then hand that unverified master to the review
        # board, which refuses it — a confusing dead end that gets worse every
        # re-run. Move it aside: the numbering regex only matches `-v<N>.mp4`, so
        # the slot is freed, and the file stays on disk to be looked at.
        # ... into build/rejected/, not final/: final/ holds deliverables only (final_qc's
        # foreign-content check refused a re-cut over a rejected master, 2026-09-01).
        if [ -f "$master" ]; then
          mkdir -p "$P/build/rejected"
          mv -f "$master" "$P/build/rejected/$(basename "${master%.mp4}").rejected.mp4"
          warn "moved the unverified master aside: build/rejected/$(basename "${master%.mp4}").rejected.mp4"
        fi
        die "the cut for '$sid' failed to build or failed lip-sync (see above)"
      fi
      python3 "$RAP_SCRIPTS/master_version.py" record --project "$P" --slug "$SLUG" \
        --style "$sid" --master "$master" --selection "$P/build/selection-$sid.json" \
        ${OVERRIDES:+--overrides "$OVERRIDES"} \
        || die "master_version record failed — the master exists but is unlogged"
      continue
    fi
    # The hero/B-roll fallback that used to live here is gone with the split. It
    # globbed outputs/ for B-roll and passed --hero build/hero-<sid>.mp4, a file
    # nothing produces any more, so reaching it now means the `select` stage did
    # not write a selection — say that instead of failing inside the config builder.
    die "no selection for style '$sid'. The cut is built from select_cut.py's
  selection-$sid.json, which the `select` stage writes once a clip is assigned to
  every window. Re-run --from select, or set CUT_AUTO=1 to take its deterministic
  longest-window-first assignment."
  done
  mark cut
fi

# ---- 11a. sync-gate (free): the DELIVERY bar, per 2s span, in FILM TIME ------
# check_sync at stage 10c answers "is this take on the right bar of the song" at the
# ~400ms KEEP threshold. That is not the same question as "is this film ready to show
# anyone", and treating it as though it were is how a film went out with 15 of 16
# windows "passing" while the operator watched it and found the sync bad throughout.
# This is the ship-it gate: 80ms, measured on short spans so within-window drift is
# visible at all. Exit 5 means do not deliver.
# ---- 11a0. audio-swap (free, local): the record's beat, the take's voice ----------
# AUDIO_MODE=vocal-swap (pack). The operator's call on New Era (2026-08-31): a lip-sync
# model's mouth always matches its OWN voice, so the film's audio is rebuilt as the
# original instrumental stem + each take's Demucs vocal where it sings (level-matched,
# cross-faded) + the original vocal elsewhere. Sync is exact by construction; the
# sync gate below is then skipped. The record-audio master is kept beside it.
# VOCAL_SWAP_KEEP_RECORD="A-B,C-D": film-second spans where the RECORD's vocal stays —
# for a stretch the take sings wrongly (a window that straddles a performer handover puts
# one child's voice on the other's line: Baby Ram & Sita w04, 2026-09-01).
keep_record_args=()
_kr="${VOCAL_SWAP_KEEP_RECORD:-}"                            # bash >= 4.4 refuses ${unset//x/y} under set -u
for _sp in ${_kr//,/ }; do keep_record_args+=(--keep-record "$_sp"); done
if ! done_stage audio-swap; then
  if [ "$(film_mode)" = "vocal-swap" ] && [ ! -f "$P/build/stems/_demucs/htdemucs/hook/no_vocals.wav" ]; then
    warn "audio-swap: no instrumental stem at build/stems/_demucs/htdemucs/hook/no_vocals.wav — the record's audio stays (a synthetic dry run has no stems)"
  elif [ "$(film_mode)" = "vocal-swap" ]; then
    for sid in $(film_styles); do
      master=$(python3 "$RAP_SCRIPTS/master_version.py" latest --project "$P" --slug "$SLUG" --style "$sid" 2>/dev/null \
        | python3 -c "import json,sys
t=sys.stdin.read().strip()
try: print(json.loads(t).get('path',''))
except Exception: print(t)" 2>/dev/null || true)
      [ -n "$master" ] && [ -f "$master" ] || die "audio-swap: no current master for '$sid' — run the cut stage"
      python3 "$RAP_SCRIPTS/vocal_swap.py" --plan "$P/build/plan.json" --selection "$P/build/selection-$sid.json" \
        ${cards_args[@]+"${cards_args[@]}"} \
        --store "$P/artifacts/clip-transcripts.json" --extra-words "$P/build/fitted-$sid/words.json" \
        --song "$P/build/hook.wav" --stems "$P/build/stems" --master "$master" \
        ${keep_record_args[@]+"${keep_record_args[@]}"} \
        --out "$P/build/audio-vocalswap-$sid.wav" --json "$P/build/vocal-swap-$sid.json" --fade "${VOCAL_SWAP_FADE:-0.15}" \
        || die "vocal_swap failed for '$sid'"
    done
  else
    log "audio-swap: mode=$(film_mode) — the record's audio stays (set AUDIO_MODE=vocal-swap for the takes' voices)"
  fi
  mark audio-swap
fi

if ! done_stage sync-gate; then
  # EVERY style is measured before anyone is asked anything. Two failure modes have
  # to be dodged AT ONCE here. (1) The forever-gate: the gate once sat inside this
  # loop with `mark` after it — gate() exits, the mark never ran, an unattended
  # supervisor sat on it until its stall detector gave up. (2) The silent accept:
  # the fix for (1) was `mark` BEFORE the gate — which made one bare re-run accept
  # every failing verdict, and that is how an UNMEASURABLE window shipped 825ms late
  # (2026-08-24). The resolution is the accepts file: the stage re-measures on every
  # pass and marks only when clean, and what makes it TERMINABLE is that a verdict
  # the operator's ear overrules gets an explicit, per-window, md5-keyed accept that
  # the next measurement honours.
  below_bar=""
  # AUDIO_MODE=vocal-swap: the film's audio follows the picture (audio-swap stage), so
  # there is no record to measure the takes against — nothing is below the bar.
  [ "$(film_mode)" = "vocal-swap" ] && log "sync-gate: skipped — AUDIO_MODE=vocal-swap, the audio follows the picture by construction"
  for sid in $([ "$(film_mode)" = "vocal-swap" ] || film_styles); do
    [ -f "$P/build/selection-$sid.json" ] || continue
    # WORDS FIRST. It is the gate that decides whether a bad window costs nothing or
    # costs ~100min of a single-slot queue, and on the film this was built from it
    # disagreed with the energy gate on 4 of 14 windows and was right every time.
    #
    # --cutaways IS NOT OPTIONAL when the file exists. A covered second has no vocal in
    # the clip BY DESIGN, so without it every deliberate edit reads as WRONG-LYRIC.
    # Measured on the reference film: exit 5 with three false alarms without it, exit 0
    # with it. `cover` writes the file, so this closes its own loop.
    word_args=(--store "$P/artifacts/clip-transcripts.json"
      --selection "$P/build/selection-$sid.json" --vocal-map "$P/build/vocal-map.json"
      --json "$P/build/word-sync-$sid.json")
    cutaways_json="$(cutaways_for "$sid")"
    [ -n "$cutaways_json" ] && word_args+=(--cutaways "$cutaways_json")
    # NOT `|| true`. Exit 6 means the transcript store describes clips that have since
    # been re-rendered — every verdict below it would be about takes that no longer
    # exist, which is worse than no verdict. Exit 5 (windows need work) is reported by
    # the profile gate below, so it stays non-fatal here.
    wrc=0
    python3 "$RAP_SCRIPTS/word_sync.py" "${word_args[@]}" || wrc=$?
    [ "$wrc" = "6" ] && die "the clip-transcript store is stale — re-run --from transcribe. \
It now caches by content, so only the changed clips cost anything."
    python3 "$RAP_SCRIPTS/sync_profile.py" --song "$P/build/hook.wav" \
      --selection "$P/build/selection-$sid.json" --vocal-map "$P/build/vocal-map.json" \
      --stage "$P/build/shifted-$sid" --json "$P/build/sync-profile-$sid.json" \
      --accepts "$P/build/sync-accepts.json" && continue
    rc=$?
    [ "$rc" = "6" ] && die "sync_profile could not resolve a performer clip for '$sid'"
    below_bar="$below_bar $sid"
  done
  # MARK ONLY WHEN CLEAN. The old mark-before-gate meant one re-run silently accepted
  # every failing verdict — that is exactly how an UNMEASURABLE window shipped 825ms
  # late on 2026-08-24 (the film-time table said so; the re-run clicked through it).
  # The gate can still END (the "a gate must be able to end" rule): every failing
  # window either gets FIXED (slide/cover/re-render) or gets an EXPLICIT, per-window,
  # md5-keyed accept — and the next pass then measures clean and marks.
  if [ -n "$below_bar" ]; then
    gate "sync is below the delivery bar for:$below_bar" \
"The tables above list every window that misses 80ms, in FILM TIME.

  * 'slide it'    — re-run --from slide; the offset is steady and costs nothing to fix.
  * 'WANDERS'     — drift inside the take, OR a repeated-phrase lock-on: LISTEN at the
                    printed times. A real drift needs a re-render or a cover
                    (cover_mouthing.py --span). A take your ear passes gets an accept:
      python3 $RAP_SCRIPTS/sync_profile.py --accept wNN --reason 'why it is fine' \\
        --song '$P/build/hook.wav' --selection '$P/build/selection-<style>.json' \\
        --vocal-map '$P/build/vocal-map.json' --stage '$P/build/shifted-<style>'
  * 'MOUTHING'    — the song has no vocal there. Cut away; do not re-render.

  Accepts are per-window and md5-keyed to the exact clip: fixing or replacing the
  clip voids its accept. Re-run to re-measure; the stage completes only when every
  window is ok, exempt, or explicitly accepted."
  fi
  mark sync-gate
fi

# ---- 11b. board (free): per-window review of the CURRENT master -------------
# The page the operator actually looks at. It is built from the artifacts — the
# master's own selection sidecar, the library index, the plan — so it cannot show
# a stale cut, and it accounts for every clip on disk rather than quietly dropping
# the ones it has no slot for. Both were real defects: a four-versions-old review
# page, and three clips from a different film that stayed invisible while scoring
# their way into the cut.
if ! done_stage board; then
  for sid in $(film_styles); do
    sync_report="$P/build/sync-report-$sid.json"
    cutaways_json="$(cutaways_for "$sid")"
    # --profile + --cutaways feed the per-window risk lines (listen-times, verdicts,
    # deliberate covers); the 6fps strips build by default, cached by clip content.
    # THE KNOWN-ISSUES LIST that ships with every delivery: the same join, now in film
    # time from the sync gate, the word-sync verdicts and the cutaway record. Never
    # hand-typed, so the operator reviews what is NEW rather than rediscovering what
    # was already known (four deliveries of one film, 2026-08-29).
    _ki_cut="$P/build/cutaways-$sid.json"; [ -f "$_ki_cut" ] || _ki_cut="$P/build/cutaways.json"
    python3 "$RAP_SCRIPTS/needs_report.py" --project "$P" --slug "$SLUG" --style "$sid" --pack "$PACK" --audio-mode "$(film_mode)" \
      --plan "$P/build/plan.json" --broll-plan "$P/build/broll-plan.json" \
      --library "$P/build/library-index.json" --shift-report "$P/build/shift-report-$sid.json" \
      --vocal-map "$P/build/vocal-map.json" --salvage "$P/build/salvage-cover.json" \
      --profile "$P/build/sync-profile-$sid.json" --word-sync "$P/build/word-sync-$sid.json" \
      --cutaways "$_ki_cut" --master "$(python3 "$RAP_SCRIPTS/master_version.py" latest --project "$P" --slug "$SLUG" --style "$sid" 2>/dev/null || true)" \
      --known-issues "$P/final/videos/KNOWN-ISSUES-$sid.md" \
      --out "$P/build/needs-$sid.html" --json-out "$P/build/needs-$sid.json" \
      || die "needs_report (film time) failed for '$sid'"
    python3 "$RAP_SCRIPTS/review_board.py" --project "$P" --slug "$SLUG" --style "$sid" \
      --library "$P/build/library-index.json" --plan "$P/build/plan.json" \
      ${sync_report:+--sync "$sync_report"} \
      --profile "$P/build/sync-profile-$sid.json" \
      ${cutaways_json:+--cutaways "$cutaways_json"} \
      --out "$P/build/review-$sid.html" --json-out "$P/build/review-$sid.json" \
      || die "review_board refused to build the board for '$sid' (see above)"
    # the master, silent, against the record and the stems — the primary use of the sync page
    python3 "$RAP_SCRIPTS/sync_review.py" --project "$P" --style "$sid" >/dev/null 2>&1 || true
    log "sync review: $P/build/sync-review.html"
  done
  mark board
fi

# ---- 13. meta (gate: final sign-off) --------------------------------------
# AUDIO_MODE=vocal-swap: the master's windows carry the takes' own voices, so a
# correlation against the record would measure the swap, not the sync (by construction).
check_master_sync=()
[ "$(film_mode)" = "vocal-swap" ] && check_master_sync=(--no-sync "AUDIO_MODE=vocal-swap: every synced window carries its take's own voice (audio-swap stage); sync is by construction")
if ! done_stage meta; then
  ok=1
  # Iterate STYLES and ask for each one's latest version. Globbing the directory
  # would now sweep up every historical version and derive a style id of
  # "gold-v2" from the filename, pointing --config at a file that never existed.
  for sid in $(film_styles); do
    m=$(python3 "$RAP_SCRIPTS/master_version.py" latest --project "$P" --slug "$SLUG" \
      --style "$sid" 2>/dev/null | python3 -c "import json,sys;d=sys.stdin.read().strip();print(json.loads(d)['path'] if d else '')") || m=""
    [ -n "$m" ] && [ -f "$m" ] || continue
    _cm_cut="$P/build/cutaways-$sid.json"; [ -f "$_cm_cut" ] || _cm_cut="$P/build/cutaways.json"
    python3 "$RAP_SCRIPTS/check_master.py" --master "$m" --hook-json "$HOOK_JSON" \
      --config "$P/build/mv-$sid.json" --fps "$MV_FPS" --frame0 ${check_master_sync[@]+"${check_master_sync[@]}"} \
      --vocal-brief "$P/build/vocal-brief.json" --cutaways "$_cm_cut" \
      --contact-sheet "$P/build/sheet-$sid.jpg" || ok=0
  done
  [ "$ok" = "1" ] || die "check_master failed — fix the master before sign-off (see above)"
  # ADVISORY. The generic project QC sums every mp4 under final/ as "scenes" against the
  # last one as "master" — meaningless here (masters, the FILM, the YT copy), so its
  # duration-drift line is noise; it read 944 s on a routine re-cut (2026-09-01). The
  # codec/audio findings are worth a glance; final_qc below is the gate.
  log "qc: vclaw video qc is advisory on this lane — ignore its duration-drift; final_qc is the gate"
  node "$MAIN/dist/cli/vclaw.js" video qc --project "$SLUG" --root "$VCLAW_WORKSPACE" || true
  mark meta   # before the gate: gate() exits, so a mark after it never runs
  gate "final sign-off" \
"1. OPEN THE CONTACT SHEET: $P/build/sheet-*.jpg — the whole film, one frame a
   second. Nothing above measured the PICTURE. Sync, lyric coverage and
   correlation are all deaf to physics, and an operator has found all of these on
   cuts that passed every automated gate:
     * a prop hanging unsupported in mid-air, or teleporting into a hand
     * extra figures walking in from the frame edges (that one began at ~4s, so a
       single mid-clip grab missed it across EIGHT clips)
     * a shot that changes render style because no face is in it
   Read it left to right, row by row. It is two seconds to build and it is the
   only place these show up before the operator sees them on screen.

2. Open $P/build/review-*.html — one card per window showing the clip THIS master
   actually plays, its alternates, and every clip on disk that is not in the film
   with the reason why. Built from the current master, so it cannot be stale.

3. Watch both masters end to end with sound, and run the full suite:
       bash '$VCLAW_WORKSPACE/brs-full-qc.sh' $SLUG
   Check frame 0 is a composed hero frame (it is the feed thumbnail), the lips
   hold through every cutaway, and the two variants read as different films.

Re-run to sign off."
fi

# ---- 13b. bookends (free): ident, end card, partner board around the body ----
# AFTER meta on purpose. check_master asserts the master's duration against the plan
# to within a frame, so wrapping before sign-off breaks that by construction. meta
# keeps its exact meaning — the checks and the human sign-off of the BODY — and this
# then wraps it into a separate -FILM.mp4 and carries its own assertion.
if ! done_stage bookends; then
  built=0
  for sid in $(film_styles); do
    body=$(python3 "$RAP_SCRIPTS/master_version.py" latest --project "$P" --slug "$SLUG" \
      --style "$sid" 2>/dev/null | python3 -c "import json,sys;d=sys.stdin.read().strip();print(json.loads(d)['path'] if d else '')") || body=""
    [ -n "$body" ] && [ -f "$body" ] || continue
    python3 "$RAP_SCRIPTS/make_bookends.py" --out-dir "$P/build/bookends" \
      --slug "$SLUG" --json-out "$P/build/bookends/cards.json" \
      || die "make_bookends failed for '$sid'"
    # STINGER (pack/env, optional): a clip appended AFTER the outro card — the film's
    # post-credits beat ("add this video at the end with no music on it", 2026-08-24).
    # STINGER_AUDIO=own keeps its audio; the default is silent.
    stinger_args=()
    if [ -n "${STINGER:-}" ]; then
      [ -f "$STINGER" ] || die "STINGER is set but not found: $STINGER"
      stinger_args=(--stinger "$STINGER" --stinger-audio "${STINGER_AUDIO:-silent}")
    fi
    bash "$RAP_SCRIPTS/build_bookends.sh" --body "$body" --song "$P/build/hook.wav" \
      --work "$P/build/bookends" --project "$P" --slug "$SLUG" \
      --cards "$P/build/bookends/cards.json" --fps "$MV_FPS" ${stinger_args[@]+"${stinger_args[@]}"} \
      || die "build_bookends failed for '$sid' (it refuses rather than touch the body)"
    # DERIVED FROM THE BODY, never re-typed. build_bookends.sh names its output after
    # the body master it wrapped, which is VERSIONED — krish-<sid>-v1-FILM.mp4. This
    # line used to rebuild the path from $SLUG and $sid and lost the -v1, so it named a
    # file that never exists. ffprobe on a missing file prints nothing, so the check
    # below got --expect-seconds '' and died in argparse — a usage dump, on the one
    # stage whose output is the thing the operator actually watches.
    film="$P/final/videos/film/$(basename "${body%.mp4}")-FILM.mp4"
    [ -f "$film" ] || die "build_bookends reported success but no film is at $film"
    # NOT --expect-seconds: build_bookends.sh already asserts its own output against
    # the REAL durations of the parts it built, within two frames. Recomputing it here
    # from the manifest's NOMINAL seconds is the same check with worse information —
    # xfade returns a hair under nominal, so it failed a correct film by 49ms. What is
    # worth checking on the WRAPPED file is what the wrap can break: streams present,
    # audio and video the same length, and a composed first frame.
    python3 "$RAP_SCRIPTS/check_master.py" --master "$film" --hook-json "$HOOK_JSON" \
      --config "$P/build/mv-$sid.json" --fps "$MV_FPS" ${check_master_sync[@]+"${check_master_sync[@]}"} \
      --expect-seconds "$(python3 -c "
import subprocess
print(subprocess.run(['ffprobe','-v','error','-show_entries','format=duration',
  '-of','csv=p=0','$film'],capture_output=True).stdout.decode().strip())")" \
      || die "the wrapped film failed its checks"
    built=$((built + 1))
  done
  if [ "$built" = "0" ]; then
    log "bookends: no body master found — nothing to wrap"
  else
  mark bookends   # before the gate: gate() exits, so a mark after it never runs
    gate "sign off the FILM" \
"Watch $P/final/videos/film/$SLUG-*-FILM.mp4 end to end, with sound.

  * Frame 0 is the feed thumbnail — it must be a composed card, never black.
  * Any foreword is a REAL person's words in their name. Get them approved.
  * The body master is untouched at $P/final/videos/ — a festival cut without
    the club ident.
Re-run to approve."
  fi
fi

# ---- 13c. captions (free): burn the lyric subtitles into the wrapped film ----
# Only when the operator asks (CAPTIONS=1) — plenty of music videos ship without.
if ! done_stage captions; then
  if [ "${CAPTIONS:-0}" = "1" ]; then
    require_ffmpeg_full
    for film in "$P"/final/videos/film/"$SLUG"-*-FILM.mp4; do
      [ -f "$film" ] || continue
      case "$film" in *-SUBTITLED.mp4) continue;; esac
      ass="$P/build/captions.ass"
      # line_subs by default, make_subtitles as the fallback. The difference is which
      # unit carries the timing: make_subtitles keeps whisper's SEGMENT boundaries and
      # replaces only the text, which is right when segments and lyric lines correspond
      # — on a dense rap one segment swallowed two or three sheet lines, which put FOUR
      # display lines on screen at once and left a line sung at 1:08 still showing at
      # 1:13. line_subs gives each lyric line its own in and out from WORD timings, so
      # it needs a word-level transcript and falls back when there isn't one.
      #
      # It also refuses (exit 5) rather than emitting a caption too wide for the frame.
      # That is not fussiness: the wrap limit used to be 42 characters because 42 is a
      # round number, a 41-character line therefore stayed on one line, rendered ~860px
      # inside a 720px frame, and was clipped off BOTH edges in the delivered cut.
      caption_args=(--lyrics "$P/references/lyrics.txt" --out "$ass"
        --offset-from-cards "$P/build/bookends/cards.json"
        --play-res "${RESOLUTION:-720x1280}")
      [ -n "${CAPTION_FONT:-}" ] && caption_args+=(--font "$CAPTION_FONT")
      [ -n "${CAPTION_SIZE:-}" ] && caption_args+=(--size "$CAPTION_SIZE")
      words_tx="$P/build/transcript-words.json"
      # AUDIO_MODE=vocal-swap: the film's voice inside every synced window is the TAKE's,
      # phrased its own way — a caption timed from the record sits on the wrong mouth.
      # swap_words.py re-times the words from the takes' own transcripts (2026-08-31).
      if [ "$(film_mode)" = "vocal-swap" ]; then
        film_sid="$(basename "$film" -FILM.mp4)"; film_sid="${film_sid#"$SLUG"-}"; film_sid="${film_sid%-v[0-9]*}"
        if [ -f "$P/build/vocal-swap-$film_sid.json" ]; then
          python3 "$RAP_SCRIPTS/swap_words.py" --record "$words_tx" --swap "$P/build/vocal-swap-$film_sid.json" \
            --clip-transcripts "$P/artifacts/clip-transcripts.json" --extra-words "$P/build/fitted-$film_sid/words.json" \
            --out "$P/build/transcript-words-vocalswap-$film_sid.json" \
            && words_tx="$P/build/transcript-words-vocalswap-$film_sid.json" \
            || warn "swap_words failed — captions timed from the record"
        else
          warn "vocal-swap: no build/vocal-swap-$film_sid.json — captions timed from the record"
        fi
      fi
      # WORD TIMINGS OR NOTHING. The segment-timed fallback put four lines on screen at
      # once; when the word file was found clobbered (0 words, 2026-08-29) the same
      # whisper run's transcript.json still had them, so re-derive — and refuse when
      # neither has any. CAPTIONS_FALLBACK=segments is the explicit, announced escape.
      if python3 "$RAP_SCRIPTS/caption_words.py" --words "$words_tx" --transcript "$TRANSCRIPT"; then
        rc=0
        python3 "$RAP_SCRIPTS/line_subs.py" --transcript "$words_tx" "${caption_args[@]}" || rc=$?
        [ "$rc" = "0" ] || die "line_subs failed (exit $rc). Exit 5 means a lyric line \
cannot fit the frame at this font size — lower CAPTION_SIZE or shorten the line; it is \
refusing to ship a caption clipped off both edges."
      elif [ "${CAPTIONS_FALLBACK:-}" = "segments" ]; then
        warn "captions: CAPTIONS_FALLBACK=segments — SEGMENT-timed captions (several lyric lines per cue)"
        python3 "$RAP_SCRIPTS/make_subtitles.py" --transcript "$TRANSCRIPT" \
          --lyrics "$P/references/lyrics.txt" \
          --offset-from-cards "$P/build/bookends/cards.json" --out "$ass" \
          ${CAPTION_FONT:+--font "$CAPTION_FONT"} ${CAPTION_SIZE:+--size "$CAPTION_SIZE"} \
          || die "make_subtitles failed"
      else
        die "captions: no word timings — re-run --from map (whisper --word_timestamps). \
CAPTIONS_FALLBACK=segments ships segment-timed captions instead, on purpose."
      fi
      out="${film%.mp4}-SUBTITLED.mp4"
      # `-ss` AFTER `-i`. Before it, ffmpeg rebases the output timeline to zero, so
      # libass looks for a cue at t=0 and you get a clean render with NO subtitles and
      # no error at all. (Not used here — the whole film is burned — but the same trap
      # bites every time someone spot-checks a frame.)
      "$FFMPEG_FULL" -v error -y -i "$film" \
        -vf "ass=$ass:fontsdir=/System/Library/Fonts" \
        -c:v libx264 -crf 18 -preset medium -c:a copy -movflags +faststart "$out" \
        || die "the caption burn failed"
      # A burn that silently soft-muxed is the classic libass failure: the file plays
      # fine and the words are simply not in the pixels. Zero subtitle streams is the
      # proof that they are.
      n="$(ffprobe -v error -select_streams s -show_entries stream=index -of csv=p=0 "$out" | wc -l | tr -d ' ')"
      [ "$n" = "0" ] || die "subtitles were SOFT-MUXED, not burned ($n subtitle stream(s)) — \
the words are not in the pixels. Check that \$FFMPEG_FULL has libass."
      log "captions: $out"
    done
  mark captions   # before the gate: gate() exits, so a mark after it never runs
    gate "check the captions" \
"Watch the subtitled cut. The lines must match what is SUNG, not what whisper heard —
make_subtitles prints its per-cue match score, and anything marked KEPT WHISPER is a
line it could not place. Re-run to approve."
  else
    log "captions: CAPTIONS=1 not set — skipping"
  fi
fi

# ---- 13d. polish (loudness, VERIFIED) ---------------------------------------
# This stage used to sit BEFORE bookends/captions and call rhyme-factory's
# youtube-polish.sh — which needs a master filename this lane never writes, died at a
# missing poster, and was swallowed by `|| warn`. Net effect: the stage list said
# "-14 LUFS" while NO rap master was ever loudness-normalised; the birthday film
# shipped at -16.6 LUFS. It now runs AFTER captions (its input is the finished film,
# which does not exist any earlier), uses rap_polish.py, and DIES on a miss — the
# whole point is that it measures the file it wrote.
if ! done_stage polish; then
  require_ffmpeg_full
  polished=0
  for film in "$P"/final/videos/film/"$SLUG"-*-FILM-SUBTITLED.mp4 \
              "$P"/final/videos/film/"$SLUG"-*-FILM.mp4; do
    [ -f "$film" ] || continue
    case "$film" in *-FILM-SUBTITLED.mp4) ;; *)
      # only fall back to the unsubtitled film when no subtitled twin exists
      [ -f "${film%.mp4}-SUBTITLED.mp4" ] && continue ;;
    esac
    python3 "$RAP_SCRIPTS/rap_polish.py" --film "$film" \
      --json-out "$P/build/polish-$(basename "${film%.mp4}").json" \
      || die "polish failed for $(basename "$film") — the output missed the loudness target"
    polished=$((polished + 1))
  done
  [ "$polished" -gt 0 ] || warn "polish: no finished film to normalise — captions/bookends
  have not produced a FILM yet, so deliverables will NOT be loudness-normalised"
  mark polish
fi

# ---- 14. preview -----------------------------------------------------------
if ! done_stage preview; then
  # all three delivery surfaces: review (operator HITL), preview (final showcase,
  # aspect-aware cards + soundtrack player + downloads + the QC menu item), run.
  node "$MAIN/dist/cli/vclaw.js" video portal --project "$SLUG" \
    --root "$VCLAW_WORKSPACE" || warn "portal generation failed (non-fatal)"
  python3 "$RAP_SCRIPTS/lane_nav.py" "$P"/*.html "$P"/build/*.html >/dev/null 2>&1 || true   # one menu on every page
  log "surfaces: $P/review.html · $P/preview.html · $P/run.html"
  log "storyboard (pre-spend contract): $P/build/storyboard.html"
  mark preview
fi

# ---- 15. deliver (free): the finished cut at delivery resolution ------------
# The skill had no hi-res path at all, so 1080p and 4K were built by hand at the end of
# a long session — and each hand-built step cost something. A partial upscale SILENTLY
# encodes a short film (ffmpeg's image reader stops at the first gap and writes a valid,
# wrong file); a killed run used to lose all its finished frames to an `rm -rf`; and an
# encode started with `nohup … &` was killed mid-write and produced `moov atom not
# found`. deliver.py makes all three impossible and then MEASURES the delivered file —
# dimensions, duration, frame count, an audio stream, and captions in the pixels rather
# than soft-muxed.
#
# DELIVER=1080p (default) | 4k | both | none. 4K is Real-ESRGAN at ~1.4s a frame, so a
# two-minute film is about an hour: it is daemonised and this stage does not block.
if ! done_stage deliver; then
  case "${DELIVER:-1080p}" in
    none) log "deliver: DELIVER=none — skipping" ;;
    *)
      # EVERY style, not styles[0]. `meta` signs off each master and the whole point of
      # the lane is two variants that read as different films; delivering one of them is
      # how the second quietly never ships.
      for sid in $(film_styles); do
        deliver_args=(--project "$P" --slug "$SLUG" --style "$sid" --mode "${DELIVER:-1080p}")
        # DELIVER THE FILM, NOT THE BODY. deliver.py defaults its input to
        # `master_version latest`, which is the body master — no title card, no outro.
        # The bookends gate calls that "a festival cut without the club ident"; the
        # thing anyone is actually shown is the FILM.
        #
        # And the captions are timed FOR the film: the caption stage passes
        # --offset-from-cards, so every cue is shifted by the intro. Burning that .ass
        # onto the body put every line ~6.5s early — the intro's length — which reads
        # as a caption-sync bug and is really a wrong-input bug.
        #
        # So prefer the already-subtitled film and burn nothing; then the plain film
        # with its own subs; and only then the body, which is what it always was.
        # `|| true` on each: under set -e + pipefail an absent file makes `ls` fail, the
        # assignment inherits the status and the runner exits SILENTLY — which is what
        # happened on the first CAPTIONS=0 film (no -FILM-SUBTITLED.mp4 exists then).
        # `sort -V`: the newest VERSION, not the last name. A plain `ls | tail -1` handed
        # v8-YT to the deliverable while v10-YT sat beside it ("v10" < "v8" as strings) —
        # the operator was shown the previous cut's ending (film #3, 2026-09-07 09:27).
        film_yt=$(ls "$P/final/videos/film/$SLUG-$sid"*-YT.mp4 2>/dev/null | sort -V | tail -1 || true)
        film_sub=$(ls "$P/final/videos/film/$SLUG-$sid"*-FILM-SUBTITLED.mp4 2>/dev/null | sort -V | tail -1 || true)
        film_raw=$(ls "$P/final/videos/film/$SLUG-$sid"*-FILM.mp4 2>/dev/null | sort -V | tail -1 || true)
        if [ -n "$film_yt" ]; then
          # the polish stage's output: captioned, bookended AND loudness-normalised —
          # deliverables built from it inherit the -14 LUFS the qc stage will demand.
          deliver_args+=(--input "$film_yt")
        elif [ -n "$film_sub" ]; then
          deliver_args+=(--input "$film_sub")
        elif [ -n "$film_raw" ]; then
          deliver_args+=(--input "$film_raw")
          [ -f "$P/build/captions.ass" ] && deliver_args+=(--subs "$P/build/captions.ass")
        else
          warn "deliver: no bookended film for '$sid' — delivering the body master,
  which has no title card. Frame 0 is the feed thumbnail."
          [ -f "$P/build/captions.ass" ] && deliver_args+=(--subs "$P/build/captions.ass")
        fi
        case "${DELIVER:-1080p}" in
          4k|both)
            # 4K is ~1.4s a frame, so a 2-minute film is about an hour PER STYLE. One
            # daemon per style, each with its own log and pidfile, each resumable.
            pid="$(python3 "$RAP_SCRIPTS/daemonize.py" --log "$P/build/deliver-$sid.out" \
              --pid "$P/build/deliver-$sid.pid" --cwd "$P" -- \
              python3 "$RAP_SCRIPTS/deliver.py" "${deliver_args[@]}")"
            log "deliver: 4K for '$sid' running detached as pid $pid — watch $P/build/deliver-$sid.out"
            log "  it is RESUMABLE: if it dies, re-run this stage and it continues." ;;
          *)
            python3 "$RAP_SCRIPTS/deliver.py" "${deliver_args[@]}" \
              || die "deliver failed for '$sid' — see $P/build/deliver.log" ;;
        esac
      done ;;
  esac
  mark deliver
fi

# ---- 16. qc: the checks nothing else runs, on the files a human receives ----
# `deliver` measures its own output against its own input; nothing before this compares
# the DELIVERED files to what the PACK asked for. Every check in final_qc caught a real
# defect on a shipped film (a landscape crop of a 9:16 film, -16.6 LUFS audio, a
# hallucinated caption) and the battery lived in a session scratchpad until now.
# Any FAIL kills the run: deliver is not the last word, this is.
if ! done_stage qc; then
  require_ffmpeg_full
  qc_args=(--project "$P" --slug "$SLUG" --resolution "${RESOLUTION:-720x1280}")
  [ -f "$P/references/lyrics.txt" ] && qc_args+=(--lyrics "$P/references/lyrics.txt")
  [ -f "$P/build/captions.ass" ] && qc_args+=(--captions "$P/build/captions.ass")
  python3 "$RAP_SCRIPTS/final_qc.py" "${qc_args[@]}" \
    || die "final_qc refused the delivered files — see build/qc-report.json"
  mark qc
fi

log "done: $SLUG — masters in $P/final/videos/, deliverables in $P/final/deliverables/"

# ---- publish (deliberately NOT a stage) --------------------------------------
# The prep (thumbnail + upload sheet) is free and idempotent; the PRINT of the exact
# upload command is wanted on every completed run; and the upload itself is an
# outward-facing act that must never ride the re-run-is-approval convention. So this
# block always runs after qc, and rap-publish.sh only calls the YouTube API when
# PUBLISH_GO=1 is in the environment — the explicit second key.
if [ -f "$P/build/qc-report.json" ]; then
  pub_film=$(ls -1 "$P"/final/videos/film/"$SLUG"-*-YT.mp4 2>/dev/null | tail -1)
  if [ -n "$pub_film" ]; then
    [ -f "$P/final/thumbnail.png" ] || \
      python3 "$RAP_SCRIPTS/rap_thumbnail.py" --film "$pub_film" \
        --out "$P/final/thumbnail.png" || warn "thumbnail generation failed"
    [ -f "$P/YOUTUBE-UPLOAD.md" ] || \
      python3 "$RAP_SCRIPTS/rap_metadata.py" --project "$P" --slug "$SLUG" \
        || warn "metadata generation failed"
    pub_rc=0
    bash "$RAP_SCRIPTS/rap-publish.sh" "$SLUG" "$PACK" || pub_rc=$?
    case "$pub_rc" in
      0) ;;                            # uploaded (PUBLISH_GO=1 was set) or dry printed
      3) ;;                            # the no-go print — the normal, expected path
      *) warn "rap-publish reported a problem (exit $pub_rc) — see above" ;;
    esac
  fi
fi
