CtrlK
BlogDocsLog inGet started
Tessl Logo
PluginPublic

gamussa/reels-producer-skill

Write talking-head scripts and produce Instagram reels and YouTube shorts

1.07x
Quality

96%

Does it follow best practices?

Impact

98%

1.07x

Average score across 8 eval scenarios

SecuritybySnyk

Low

Low-risk findings worth noting

Overview
Quality
Evals
Security
Files

pipeline.pyskills/reel-builder/scripts/

#!/usr/bin/env python3
"""Pipeline state machine for a reel project — status, next step, gate log.

Run from the project folder. Stage completion is detected from artifacts on
disk (never from memory), so status can't drift from reality; only things
disk can't know live in state.json: gate decisions, target duration, grade,
and the waiting-on-NLE flag.

Staleness comes from provenance (provenance.py), not timestamps: a render is
current only while every input its .render.json recorded — the plan's hash,
each clip, the VO, music, LUT — is unchanged. A gate decision is bound to the
fingerprint of the file the human reviewed; once that file is replaced the
decision no longer counts and the gate must be presented and approved again.
A gate also refuses until the QC the skill promises has PASSED on that exact
render (check_cuts for the preview; check_cuts + qa_render for the master;
verify_cut too for a talking-head reel whose audio comes from the segments).
Schema: references/state-schema.md.

Commands:
  pipeline.py init --target-duration 30   scaffold folders + project.md + state.json
  pipeline.py status                      full stage table, gates, warnings
  pipeline.py next                        the single next action (command or gate)
  pipeline.py gate 1 presented            log that plan+preview went to the human
  pipeline.py gate 1 approved             refuses if the preview is stale
  pipeline.py gate 1 nle-wait             pipeline paused: human editing in NLE —
                                          cut_plan.json must NOT be touched
  pipeline.py gate 1 reopen               back to pending (also: after nle import)
  pipeline.py gate 2 presented|approved|reopen
  pipeline.py gate 2 approved --accept-unverified "why"
                                          approve over a SKIPPED check, recorded
  pipeline.py config grade clean          the look check_master renders with

The agent ritual: `status` at session start (with project.md), `next` when
unsure, `gate` at every human decision. Creative judgment (what to reject,
hook picks, pacing feedback) is yours, not this script's.
"""

import argparse
import json
import shutil
import subprocess
import sys
import time
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
import plan_schema  # noqa: E402  — owner of cut_plan.json reads and writes
from provenance import file_fp, fp_matches, read_render_record, stale_inputs, qc_reports  # noqa: E402
from export_variants import deliverable_names  # noqa: E402
import brief as brief_mod  # noqa: E402
import selects as selects_mod  # noqa: E402
import hooks as hooks_mod  # noqa: E402

VIDEO_EXT = {".mp4", ".mov", ".m4v", ".mts", ".avi", ".mkv"}
IMAGE_EXT = {".jpg", ".jpeg", ".png", ".webp", ".heic"}  # stills -> Ken Burns
AUDIO_EXT = {".mp3", ".m4a", ".wav", ".aac", ".flac", ".ogg"}
STATE = Path("state.json")
SCHEMA_VERSION = 5  # v2 mode, v3 resolution, v4 aspect + captions,
# v5 gates bound to the reviewed artifact + grade
# older records default to music-video/1080/9:16

MODES = ("music-video", "talking-head")
DEFAULT_GRADE = {"music-video": "gritty", "talking-head": "clean"}
GRADE_CHOICES = ("gritty", "clean", "rapha", "cine", "punch", "none")
RESOLUTIONS = ("1080", "4k")
ASPECTS = ("9:16", "16:9", "1:1")


# ---------- state ----------


def load_state():
    if STATE.exists():
        st = json.loads(STATE.read_text())
        st.setdefault("mode", "music-video")  # v1 projects were all montages
        st.setdefault("resolution", "1080")  # v2 and earlier were 1080-only
        st.setdefault("aspect", "9:16")  # v3 and earlier were vertical-only
        st.setdefault("captions", None)  # None = not yet asked
        st.setdefault("grade", None)  # None = the mode's default
        # v4 and earlier approvals carry no artifact binding; they read as
        # unbound (gate_state -> pending) until presented again. Owner upgrade.
        st["schema_version"] = SCHEMA_VERSION
        return st
    return {
        "schema_version": SCHEMA_VERSION,
        "target_duration": 30,
        "mode": "music-video",
        "resolution": "1080",
        "aspect": "9:16",
        "captions": None,
        "grade": None,
        "gates": {},
    }


def save_state(st):
    tmp = STATE.with_suffix(".json.tmp")
    tmp.write_text(json.dumps(st, indent=2))
    tmp.rename(STATE)


# ---------- artifact probes ----------


def mtime(p):
    return p.stat().st_mtime


def newest(pattern):
    files = [p for p in Path().glob(pattern) if p.is_file()]
    return max(files, key=mtime) if files else None


def raw_clips():
    raw = Path("raw")
    if not raw.exists():
        return []
    return sorted(p for p in raw.rglob("*") if p.suffix.lower() in VIDEO_EXT | IMAGE_EXT)


def probed_clips():
    cj = Path("work/clips.json")
    if not cj.exists():
        return None
    try:
        clips = json.loads(cj.read_text())["clips"]
    except (json.JSONDecodeError, KeyError):
        return None
    return [c for c in clips if "error" not in c]


def music_file():
    m = Path("music")
    if not m.exists():
        return None
    files = sorted(p for p in m.iterdir() if p.suffix.lower() in AUDIO_EXT)
    return files[0] if files else None


# ---------- stages ----------
# each check returns (status, detail, action)
# status: "done" | "stale" | "ready" | "blocked"


def res_flag(st):
    """Emit --resolution/--aspect only when they differ from script defaults."""
    out = ""
    if st.get("resolution", "1080") != "1080":
        out += f" --resolution {st['resolution']}"
    if st.get("aspect", "9:16") != "9:16":
        out += f" --aspect {st['aspect']}"
    return out


def check_deps(st):
    """Preflight gate. Everything downstream shells out to these."""
    mode = st.get("mode", "music-video")
    cmd = f"python3 scripts/check_deps.py --mode {mode}"
    r = subprocess.run(
        [sys.executable, str(Path(__file__).with_name("check_deps.py")), "--mode", mode, "--json"],
        capture_output=True,
        text=True,
    )
    try:
        data = json.loads(r.stdout)
    except json.JSONDecodeError:
        return ("ready", "run the dependency preflight", cmd)
    missing = data.get("missing_required", [])
    if missing:
        return (
            "blocked",
            f"MISSING REQUIRED: {', '.join(missing)} — install before anything else",
            cmd,
        )
    opt = data.get("missing_optional", [])
    d = "all required tools present"
    if opt:
        d += (
            f"; {len(opt)} optional absent ({', '.join(opt)}) — "
            f"say what each costs before substituting"
        )
    return ("done", d, None)


def check_brief(st):
    """The creative brief comes before any technical choice."""
    path = Path("plan/brief.json")
    init = (
        "python3 scripts/brief.py init --out plan/brief.json "
        "[--from ../<last reel>/plan/brief.json], then fill it WITH the user "
        "(references/creative-brief.md)"
    )
    if not path.exists():
        if Path("plan/cut_plan.json").exists():
            # a project planned before briefs existed: do not send it backwards
            return (
                "done",
                "no brief — this project was planned without one; write one for the next reel",
                None,
            )
        return (
            "ready",
            "write the creative brief with the user — viewer, need, "
            "promise, evidence, response, platform, structure, duration",
            init,
        )
    try:
        data = json.loads(path.read_text())
    except json.JSONDecodeError:
        return ("ready", "plan/brief.json is not valid JSON", "fix plan/brief.json")
    missing, errors = brief_mod.validate(data)
    if missing or errors:
        parts = ([f"ask the user: {', '.join(missing)}"] if missing else []) + errors
        return (
            "ready",
            "brief incomplete — " + "; ".join(parts),
            "python3 scripts/brief.py check plan/brief.json",
        )
    d = f"{data['structure']} for {data['viewer']}: {data['promise']}"
    target = data["duration"]["target"]
    if abs(target - st["target_duration"]) > 0.25 * target:
        d += f" (brief says ~{target:g}s, project target {st['target_duration']:g}s — reconcile)"
    return ("done", d[:140], None)


def check_selects(st):
    """Which moments earn a place, and why — before anything meets a beat grid."""
    clips = probed_clips()
    path = Path("plan/selects.json")
    cmd = (
        "write plan/selects.json from the contact sheets (references/selects.md), "
        "then: python3 scripts/selects.py check plan/selects.json --clips work/clips.json"
    )
    if not clips:
        return ("blocked", "needs probe", None)
    if not path.exists():
        if Path("plan/cut_plan.json").exists():
            return (
                "done",
                "no selects — the plan predates them; record selects before re-planning",
                None,
            )
        return (
            "ready",
            "record the selects: each moment's range, what happens, its "
            "purpose and value, in story order",
            cmd,
        )
    try:
        doc = json.loads(path.read_text())
    except json.JSONDecodeError:
        return ("ready", "plan/selects.json is not valid JSON", cmd)
    errors, warns, chosen = selects_mod.validate(doc, clips)
    if errors:
        return (
            "ready",
            f"selects invalid — {errors[0]}"
            + (f" (+{len(errors) - 1} more)" if len(errors) > 1 else ""),
            cmd,
        )
    d = f"{len(chosen)} selects, {sum(s['out'] - s['in'] for s in chosen):.1f}s of material"
    if warns:
        d += f"; {len(warns)} note(s): {warns[0]}"
    return ("done", d, None)


def check_hooks(st):
    """Three openings, rendered and compared, with the user's pick recorded — optional."""
    path = Path("plan/hooks.json")
    if not path.exists():
        return ("done", "no hook variants (optional — hooks.py compares three openings)", None)
    try:
        doc = json.loads(path.read_text())
    except json.JSONDecodeError:
        return ("ready", "plan/hooks.json is not valid JSON", "fix plan/hooks.json")
    errors = hooks_mod.validate(doc)
    if errors:
        return ("ready", f"hook variants invalid — {errors[0]}", "python3 scripts/hooks.py check")
    pv = doc.get("previews") or {}
    if len(pv) != 3 or not all(fp_matches(x) for x in pv.values()):
        return (
            "ready",
            "render the three openings for comparison",
            "python3 scripts/hooks.py preview --seconds 3",
        )
    chosen = doc.get("chosen")
    if not chosen:
        return (
            "ready",
            "show work/hooks/compare.mp4 to the user and record THEIR pick",
            'python3 scripts/hooks.py choose <id> --why "<their reason>"',
        )
    return ("done", f"opening {chosen['id']}: {chosen['why']}"[:120], None)


def check_probe(st):
    raws = raw_clips()
    cj = Path("work/clips.json")
    cmd = (
        f"python3 scripts/probe_clips.py raw/ --target-duration "
        f"{st['target_duration']:g} --out work/clips.json"
    )
    if not raws:
        return (
            "blocked",
            "no clips in raw/ — get footage from the user (or symlink: ln -s /Volumes/… raw)",
            None,
        )
    if not cj.exists() or probed_clips() is None:
        return ("ready", f"{len(raws)} raw clips await probing", cmd)
    if max(mtime(p) for p in raws) > mtime(cj):
        return ("stale", "raw/ changed after last probe — re-probe", cmd)
    clips = probed_clips() or []
    warn = sum(1 for c in clips if "warning" in c)
    d = f"{len(clips)} usable clips"
    if warn:
        d += f", {warn} duration outlier(s) — extract segments before normalizing"
    return ("done", d, None)


def check_inspect(st):
    clips = probed_clips()
    cmd = "python3 scripts/contact_sheet.py work/clips.json --outdir work/sheets"
    if not clips:
        return ("blocked", "needs probe", None)
    missing = [
        c for c in clips if not Path(f"work/sheets/{Path(c['file']).stem}_sheet.png").exists()
    ]
    if missing:
        return (
            "ready",
            f"{len(missing)}/{len(clips)} sheets missing — "
            "generate, then VIEW every sheet before planning",
            cmd,
        )
    return ("done", f"{len(clips)}/{len(clips)} sheets (did you look at them?)", None)


LAYOUT_SPEC = Path("plan/layout.json")


def check_layout(st):
    """Talk-layout projects (references/long-form.md "Talk layout"): the layout
    clip replaces the mezzanine, so this stage stands in for normalize. Whether
    the clip is current is talk_layout.py's call (layout_status: inputs record,
    spec hash, input fingerprints, frame size), never a guess from mtimes here."""
    import talk_layout

    res = st.get("resolution", "1080")
    py = "uv run --no-project --python '>=3.11' scripts/talk_layout.py"
    build = (
        f"{py} check plan/layout.json && either {py} hyperframes plan/layout.json "
        f"--project work/motion/talk, npm ci, then render_hyperframes.py work/motion/talk "
        f"--resolution {res} --out <spec out>; or {py} build plan/layout.json --resolution {res}"
    )
    if st.get("aspect", "9:16") != "9:16":
        return (
            "blocked",
            f"the talk layout is 9:16 and this project is {st.get('aspect')} — "
            "set it with pipeline.py config aspect 9:16 (before rendering), or remove "
            "plan/layout.json",
            None,
        )
    state, detail = talk_layout.layout_status(LAYOUT_SPEC, res)
    return (state, detail, None if state == "done" else build)


def check_normalize(st):
    clips = probed_clips()
    cmd = "python3 scripts/normalize_clips.py work/clips.json --outdir work/mezz" + res_flag(st)
    if not clips:
        return ("blocked", "needs probe", None)
    missing, stale = [], []
    for c in clips:
        mz = Path(f"work/mezz/{Path(c['file']).stem}.mp4")
        if not mz.exists():
            missing.append(c)
        elif Path(c["file"]).exists() and mtime(Path(c["file"])) > mtime(mz):
            stale.append(c)
    if missing:
        return (
            "ready",
            f"{len(missing)}/{len(clips)} mezzanine files to render "
            "(wait for process exit, not files)",
            cmd,
        )
    if stale:
        return ("stale", f"{len(stale)} source clip(s) newer than mezzanine", cmd)
    return ("done", f"{len(clips)} mezzanine files", None)


def check_beats(st):
    m = music_file()
    bj = Path("work/beats.json")
    if not m:
        return (
            "blocked",
            "no music in music/ — ASK THE USER: drop a file, "
            "YouTube via scripts/fetch_music.py, or --bpm fixed grid",
            None,
        )
    cmd = f"python3 scripts/detect_beats.py '{m}' --out work/beats.json"
    if not bj.exists():
        return ("ready", f"track: {m.name}", cmd)
    if mtime(m) > mtime(bj):
        return ("stale", "music changed after beat detection", cmd)
    return ("done", f"{m.name}", None)


def check_plan(st):
    plan = Path("plan/cut_plan.json")
    if st.get("mode") == "talking-head":
        cmd = (
            "author plan/cut_plan.json by hand: VO segments keep their TRUE "
            "source in-points (lip-sync dies otherwise), b-roll covers the "
            'middle, no "music" key unless you want a bed. '
            "Recipe: references/talking-head.md"
        )
        if not Path("work/clips.json").exists():
            return ("blocked", "needs probe", None)
        if not plan.exists() and not Path("plan/selects.json").exists():
            return (
                "blocked",
                "needs selects — the take's beats and the b-roll moments that prove them",
                None,
            )
        if not plan.exists():
            return ("ready", "write the VO spine + b-roll plan from the selects", cmd)
        problem = speech_contract_problem(plan)
        if problem:
            return ("blocked", problem, None)
        return ("done", "plan/cut_plan.json (human-editable)", None)
    cmd = (
        f"python3 scripts/build_cut_plan.py work/clips.json work/beats.json "
        f"--selects plan/selects.json --target-duration {st['target_duration']:g} "
        f"--out plan/cut_plan.json"
    )
    deps = [Path("work/clips.json"), Path("work/beats.json")]
    if not all(d.exists() for d in deps):
        return ("blocked", "needs probe + beats", None)
    if not plan.exists():
        if not Path("plan/selects.json").exists():
            return ("blocked", "needs selects", None)
        return ("ready", "arrange the selects on the beat grid", cmd)
    if Path("plan/selects.json").exists() and mtime(Path("plan/selects.json")) > mtime(plan):
        return (
            "stale",
            "selects changed after the plan was built — rebuild, or "
            "carry the change into the plan by hand",
            cmd,
        )
    return ("done", "plan/cut_plan.json (human-editable)", None)


def read_plan(plan):
    try:
        return plan_schema.load(plan)
    except plan_schema.PlanError:
        return None


def speech_contract_problem(plan):
    """A talking-head plan must say where its speech comes from.

    Segments are concatenated with their own audio, so a segment from another
    clip (b-roll) replaces its slice of speech — a word, a "not" — unless the
    plan lays a continuous voice ("vo") or declares that cutting the speech
    with the picture is the intended audio edit ("audio": "segments").
    """
    data = read_plan(plan)
    if data is None:
        return f"{plan} is not valid JSON — fix it before rendering"
    if data.get("vo") or data.get("audio") == "segments":
        return None
    clips = {s.get("clip") for s in data.get("segments", [])}
    if len(clips) > 1:
        return (
            'b-roll would replace its slice of speech: add "vo": {"file": <take>, '
            '"start": 0, "words": <words.json>} to the plan, or "audio": "segments" '
            "if cutting the speech with the picture is intended "
            "(references/talking-head.md)"
        )
    return None


def render_status(path):
    """("current"|"stale"|"untracked"|"missing", why) for a rendered file."""
    if not path or not Path(path).exists():
        return "missing", "not rendered"
    rec = read_render_record(path)
    if rec is None:
        return "untracked", (
            f"{Path(path).name} has no render record — re-render so its inputs are tracked"
        )
    changed = stale_inputs(rec)
    if changed:
        return "stale", f"{', '.join(changed)} changed since {Path(path).name} was rendered"
    return "current", ""


QC_KINDS = {
    # kind: (report glob, field that identifies the report shape, how to run it)
    "cuts": (
        "work/qc*.json",
        "cuts",
        "python3 scripts/check_cuts.py plan/cut_plan.json {v} --out work/qc_{stem}",
    ),
    "frames": (
        "work/qa*.json",
        "segments",
        "python3 scripts/qa_render.py {v} --plan plan/cut_plan.json --out work/qa_{stem}",
    ),
    "speech": (
        "work/verify*.json",
        "status",
        "python3 scripts/verify_cut.py {v} --words <take.words.json> "
        "--cuts <cuts.json> --out work/verify_{stem}.json",
    ),
}


def qc_status(video, kind):
    """("pass"|"fail"|"skipped"|"missing", detail) for one check on this exact file."""
    pattern, key, _ = QC_KINDS[kind]
    reps = [(pth, r) for pth, r in qc_reports(pattern, video) if key in r]
    if not reps:
        return "missing", f"{kind} QC has not run on this render"
    pth, rep = max(reps, key=lambda x: mtime(x[0]))
    if kind == "speech":
        status = {"PASS": "pass", "FAIL": "fail", "SKIPPED": "skipped"}.get(
            rep.get("status"), "fail"
        )
        return status, f"{pth.name}: {rep.get('status')}"
    if rep.get("defects"):
        return "fail", f"{pth.name}: {len(rep['defects'])} defect(s)"
    review = len(rep.get("review") or [])
    return "pass", f"{pth.name}: pass" + (f", {review} to review" if review else "")


def required_qc(st, which):
    kinds = ["cuts"] if which == "preview" else ["cuts", "frames"]
    if which == "master" and st.get("mode") == "talking-head":
        data = read_plan(Path("plan/cut_plan.json")) or {}
        if not data.get("vo"):
            kinds.append("speech")  # speech comes from the cut itself: prove no word was lost
    return kinds


def qc_summary(st, video, which):
    """[(kind, status, detail, command)] for every check this render owes."""
    out = []
    for kind in required_qc(st, which):
        status, detail = qc_status(video, kind)
        cmd = QC_KINDS[kind][2].format(v=video, stem=Path(video).stem)
        out.append((kind, status, detail, cmd))
    return out


def qc_blocker(summary, accept_unverified=False):
    """First check that keeps the render from being presented, or None."""
    for kind, status, detail, cmd in summary:
        if status == "pass" or (status == "skipped" and accept_unverified):
            continue
        return kind, status, detail, cmd
    return None


def check_preview(st):
    plan = Path("plan/cut_plan.json")
    pv = newest("preview/draft_v*.mp4")
    n = int(pv.stem.split("_v")[-1]) + 1 if pv else 1
    cmd = (
        f"python3 scripts/render_reel.py plan/cut_plan.json --preview "
        f"--out preview/draft_v{n}.mp4 && python3 scripts/check_cuts.py "
        f"plan/cut_plan.json preview/draft_v{n}.mp4 --out work/qc_v{n}"
    )
    if not plan.exists():
        return ("blocked", "needs cut plan", None)
    if not pv:
        return ("ready", "render draft + QC before showing the human", cmd)
    rs, why = render_status(pv)
    if rs != "current":
        return ("stale", f"{why} — re-render + QC", cmd)
    qc = qc_summary(st, pv, "preview")
    bad = qc_blocker(qc)
    if bad:
        kind, status, detail, qcmd = bad
        verb = "FAILED" if status == "fail" else status.upper()
        return (
            "ready",
            f"{pv.name}: {kind} QC {verb} ({detail}) — fix/run before showing the human",
            qcmd,
        )
    return ("done", f"{pv.name}, " + "; ".join(d for _, _, d, _ in qc), None)


def check_master(st):
    mst = Path("work/master.mp4")
    cmd = (
        f"python3 scripts/render_reel.py plan/cut_plan.json --grade {grade_for(st)}"
        f"{res_flag(st)} --out work/master.mp4 && python3 "
        f"scripts/check_cuts.py plan/cut_plan.json work/master.mp4 "
        f"--out work/qc_master && python3 scripts/qa_render.py work/master.mp4 "
        f"--plan plan/cut_plan.json --out work/qa_master"
    )
    if gate_state(st, 1) != "approved":
        return ("blocked", "needs Gate 1 approval", None)
    if not mst.exists():
        return ("ready", "final render with grade + QC", cmd)
    rs, why = render_status(mst)
    if rs != "current":
        return ("stale", f"{why} — re-render + QC", cmd)
    qc = qc_summary(st, mst, "master")
    bad = qc_blocker(qc, accept_unverified=True)
    if bad:
        kind, status, detail, qcmd = bad
        return ("ready", f"master: {kind} QC {status.upper()} ({detail})", qcmd)
    return ("done", "work/master.mp4, " + "; ".join(d for _, _, d, _ in qc), None)


def check_export(st):
    mst = Path("work/master.mp4")
    cmd = "python3 scripts/export_variants.py work/master.mp4 --outdir exports/ --thumb-at 1.5" + (
        " --captioned work/master_captioned.mp4 --srt work/captions.srt"
        if st.get("captions")
        else ""
    )
    if gate_state(st, 2) != "approved":
        return ("blocked", "needs Gate 2 approval", None)
    return exports_status(st, mst, cmd)


def exports_status(st, mst, cmd):
    """Are this project's deliverables written from the current master?"""
    names = deliverable_names(st.get("aspect", "9:16"))
    if st.get("captions"):
        # captions on: the clean and the captioned cut both ship, plus a sidecar
        names = names + [f"{n}_captioned" for n in names]
    outs = [Path(f"exports/{n}.mp4") for n in names]
    if not all(p.exists() for p in outs):
        return ("ready", f"export {' / '.join(names)}", cmd)
    try:
        man = json.loads(Path("exports/manifest.json").read_text())
    except (OSError, json.JSONDecodeError):
        return ("stale", "exports have no manifest — re-export to bind them to the master", cmd)
    if not fp_matches(man.get("master")) or Path(man["master"]["path"]).resolve() != mst.resolve():
        return ("stale", "master changed since the exports were made", cmd)
    if not all(fp_matches(o) for o in man.get("outputs", [])):
        return ("stale", "an export file changed after it was written", cmd)
    if st.get("captions"):
        cap = Path("work/master_captioned.mp4")
        if (
            not man.get("captioned")
            or not fp_matches(man["captioned"])
            or Path(man["captioned"]["path"]).resolve() != cap.resolve()
        ):
            return ("stale", "captioned master changed since the exports were made", cmd)
        if not man.get("sidecar") or not fp_matches(man["sidecar"]):
            return ("ready", "export the caption sidecar too (--srt work/captions.srt)", cmd)
    styled = len(list(Path("exports").glob("thumbnail-*.jpg")))
    d = " / ".join(names) + " + thumbnail"
    if styled:
        d += f" (+{styled} styled — human picks the cover)"
    return ("done", d, None)


STAGES = [
    ("deps", check_deps),
    ("brief", check_brief),
    ("probe", check_probe),
    ("inspect", check_inspect),
    ("selects", check_selects),
    ("hooks", check_hooks),
    ("normalize", check_normalize),
    ("beats", check_beats),
    ("plan", check_plan),
    ("preview", check_preview),
    ("master", check_master),
    ("export", check_export),
]


def stages_for(st):
    """Talking-head reels cut to speech, not to a grid — no beat stage. A
    talk-layout project builds its layout clip where others normalize."""
    stages = STAGES
    if st.get("mode") == "talking-head":
        stages = [(n, c) for n, c in stages if n != "beats"]
    if LAYOUT_SPEC.exists():
        stages = [("layout", check_layout) if n == "normalize" else (n, c) for n, c in stages]
    return stages


# ---------- gates ----------


def grade_for(st):
    return st.get("grade") or DEFAULT_GRADE.get(st.get("mode", "music-video"), "gritty")


def reviewed_artifact(n):
    """The file a gate decision is about: the newest preview, or the master."""
    return newest("preview/draft_v*.mp4") if n == 1 else Path("work/master.mp4")


def raw_gate_state(st, n):
    return st.get("gates", {}).get(str(n), {}).get("state", "pending")


def binding_problem(st, n):
    """Why a recorded presented/approved decision no longer applies, or None."""
    g = st.get("gates", {}).get(str(n), {})
    if g.get("state") not in ("presented", "approved"):
        return None
    art, cur = g.get("artifact"), reviewed_artifact(n)
    if not art:
        return (
            f"Gate {n} was {g['state']} before decisions were bound to a file — "
            "present the current render and record the decision again"
        )
    if not cur or not fp_matches(art) or Path(art["path"]).resolve() != Path(cur).resolve():
        return (
            f"Gate {n} was {g['state']} for {Path(art['path']).name} as it was then; "
            "that render has been replaced — present the new one and decide again"
        )
    rs, why = render_status(cur)
    if rs != "current":
        return (
            f"Gate {n} was {g['state']} for {Path(cur).name}, but {why} — "
            "re-render, then present and decide again"
        )
    return None


def gate_state(st, n):
    """Effective state: a decision about a file that has since changed is void."""
    raw = raw_gate_state(st, n)
    return "pending" if binding_problem(st, n) else raw


def gate_ready(st, n, accept_unverified=False):
    """(ok, why) — is the reviewed render current and has its QC passed?"""
    which = "preview" if n == 1 else "master"
    s, detail, _ = (check_preview if n == 1 else check_master)(st)
    art = reviewed_artifact(n)
    if s != "done" or art is None:
        return False, f"{which}: {detail}"
    bad = qc_blocker(qc_summary(st, art, which), accept_unverified)
    if bad:
        kind, status, detail, qcmd = bad
        hint = ' (or approve with --accept-unverified "<why>")' if status == "skipped" else ""
        return False, f"{kind} QC is {status.upper()} on {art.name}: {detail} — {qcmd}{hint}"
    return True, ""


def cmd_gate(st, n, action, accept_unverified=None):
    gates = st.setdefault("gates", {})
    g = gates.setdefault(str(n), {})
    cur = g.get("state", "pending")
    if action in ("presented", "approved"):
        ok, why = gate_ready(st, n, bool(accept_unverified))
        if not ok:
            sys.exit(f"Refusing gate {n} '{action}': {why}")
        art = reviewed_artifact(n)
        g["artifact"] = file_fp(art)
        g["qc"] = {k: s for k, s, _, _ in qc_summary(st, art, "preview" if n == 1 else "master")}
        if accept_unverified:
            g["accepted_unverified"] = accept_unverified
        else:
            g.pop("accepted_unverified", None)
    if action == "nle-wait":
        if n != 1:
            sys.exit("NLE round trip is a Gate 1 flow")
        plan = Path("plan/cut_plan.json")
        g["plan_mtime_at_wait"] = mtime(plan) if plan.exists() else 0
    if action == "reopen":
        action = "pending"
        g.pop("artifact", None)
    g["state"] = action if action != "presented" else "presented"
    g["at"] = time.strftime("%Y-%m-%d %H:%M:%S")
    save_state(st)
    print(f"Gate {n}: {cur} -> {g['state']}")
    if g["state"] == "nle-wait":
        print(
            "PIPELINE PAUSED. Do not render, re-plan, or touch "
            "plan/cut_plan.json until the edited fcpxml returns "
            "(then: import_timeline.py + `gate 1 reopen`)."
        )
    if g["state"] == "approved" and n == 1:
        print("Gate 1 approved — next: final render (see `pipeline.py next`).")
    if g["state"] == "approved" and n == 2:
        print("Gate 2 approved — next: export variants.")


# ---------- commands ----------


def warnings(st):
    w = []
    g1 = st.get("gates", {}).get("1", {})
    if g1.get("state") == "nle-wait":
        plan = Path("plan/cut_plan.json")
        if plan.exists() and mtime(plan) > g1.get("plan_mtime_at_wait", 0) + 1:
            w.append(
                "cut_plan.json CHANGED while waiting on the NLE edit — "
                "the human's edit may be clobbered on import. Reconcile "
                "before proceeding."
            )
        else:
            w.append(
                "waiting on NLE edit — hands off plan/cut_plan.json "
                "(import_timeline.py when the fcpxml comes back, "
                "then `gate 1 reopen`)"
            )
    for n in (1, 2):
        problem = binding_problem(st, n)
        if problem:
            w.append(problem)
        elif gate_state(st, n) == "approved":
            ok, why = gate_ready(
                st, n, bool(st.get("gates", {}).get(str(n), {}).get("accepted_unverified"))
            )
            if not ok:
                w.append(f"Gate {n} was approved but its render is no longer current — {why}")
    return w


def next_action(st):
    if st.get("gates", {}).get("1", {}).get("state") == "nle-wait":
        return (
            "WAITING on the human's NLE edit. When the fcpxml returns: "
            "python3 scripts/import_timeline.py <edited.fcpxml> --out "
            "plan/cut_plan.json --base-plan plan/cut_plan.json, "
            "then `pipeline.py gate 1 reopen`"
        )
    for name, check in stages_for(st):
        s, detail, cmd = check(st)
        if s in ("ready", "stale"):
            return f"[{name}] {detail}\n  {cmd}" if cmd else f"[{name}] {detail}"
        if s == "blocked" and name in ("deps", "probe", "beats", "layout", "plan"):
            return f"[{name}] {detail}"  # human-input blockers surface immediately
        if name == "preview" and s == "done":
            gs = gate_state(st, 1)
            if gs == "pending":
                return (
                    "GATE 1: present plan + preview together to the human "
                    "(then `pipeline.py gate 1 presented`)"
                )
            if gs == "presented":
                return (
                    "GATE 1: awaiting the human — approve / edits / NLE "
                    "(`gate 1 approved` | edit plan | `gate 1 nle-wait`)"
                )
        if name == "master" and s == "done" and gate_state(st, 2) in ("pending", "presented"):
            gs = gate_state(st, 2)
            return (
                "GATE 2: show the master to the human (`pipeline.py gate 2 presented`)"
                if gs == "pending"
                else "GATE 2: awaiting the human (`gate 2 approved` or loop back)"
            )
    return "All stages done — deliver exports/ to the user and update project.md."


MARK = {"done": ".", "ready": ">", "stale": "!", "blocked": "x"}


def cmd_status(st):
    print(
        f"Reel pipeline — {Path.cwd().name}  "
        f"[{st.get('mode', 'music-video')} · {st.get('aspect', '9:16')} · "
        f"{st.get('resolution', '1080')} · grade {grade_for(st)}"
        f"{'' if st.get('captions') is None else (' · captions' if st['captions'] else ' · no captions')}]  "
        f"(target {st['target_duration']:g}s)\n"
    )
    for name, check in stages_for(st):
        s, detail, _ = check(st)
        print(f"  {MARK[s]} {name:<10} {s:<8} {detail}")
    print(f"\n  Gate 1 (plan+preview): {gate_state(st, 1)}    Gate 2 (master): {gate_state(st, 2)}")
    for w in warnings(st):
        print(f"\n  WARNING: {w}")
    print(f"\nNext: {next_action(st)}")


def cmd_init(args):
    if STATE.exists():
        sys.exit(
            "state.json already exists — this is already a reel project (use `pipeline.py status`)"
        )
    for d in ("raw", "music", "work", "plan", "preview", "exports"):
        Path(d).mkdir(exist_ok=True)
    # `python3 scripts/<tool>.py` is how every emitted command reads, so the
    # project gets a link to the installed skill's scripts.
    if not Path("scripts").exists():
        Path("scripts").symlink_to(Path(__file__).resolve().parent, target_is_directory=True)
    tmpl = Path(__file__).resolve().parent.parent / "assets/project_template.md"
    if not Path("project.md").exists() and tmpl.exists():
        shutil.copy(tmpl, "project.md")
    save_state(
        {
            "schema_version": SCHEMA_VERSION,
            "target_duration": args.target_duration,
            "mode": args.mode,
            "resolution": args.resolution,
            "aspect": args.aspect,
            "captions": (None if args.captions is None else args.captions == "yes"),
            "grade": None,
            "gates": {},
            "created": time.strftime("%Y-%m-%d %H:%M:%S"),
        }
    )
    caps = {None: "captions: unset", True: "captions: yes", False: "captions: no"}[
        None if args.captions is None else args.captions == "yes"
    ]
    print(
        f"Project scaffolded — {args.mode}, {args.aspect}, "
        f"{args.resolution}, {caps}, target {args.target_duration:g}s."
    )
    if args.mode == "talking-head":
        print(
            "Fill project.md, drop the VO take + b-roll in raw/ (or symlink). "
            "Music is an optional bed, not the spine."
        )
    else:
        print("Fill project.md, drop footage in raw/ (or symlink), music in music/.")


def cmd_mode(st, new):
    cur = st.get("mode", "music-video")
    if new is None:
        print(cur)
        return
    if new == cur:
        print(f"Already {cur}.")
        return
    st["mode"] = new
    save_state(st)
    print(f"Mode: {cur} -> {new}")
    print("Re-check the plan — the two modes cut to different spines (`pipeline.py next`).")


SETTINGS = {
    "grade": GRADE_CHOICES,
    "captions": ("yes", "no"),
    "aspect": ("9:16", "16:9", "1:1"),
    "resolution": ("1080", "4k"),
}
# A render made at one frame size cannot be reused at another.
FRAME_SETTINGS = ("aspect", "resolution")


def rendered_anything():
    """Any mezzanine, draft, master or layout clip already on disk (the layout
    clip wherever plan/layout.json puts it)."""
    if any(
        any(Path(".").glob(pat))
        for pat in ("work/mezz/*.mp4", "preview/*.mp4", "work/master*.mp4", "work/layout/*.mp4")
    ):
        return True
    try:
        out = json.loads(LAYOUT_SPEC.read_text()).get("out")
    except (OSError, json.JSONDecodeError, AttributeError):
        return False
    return isinstance(out, str) and Path(out).exists()


def cmd_config(st, key, value):
    """Record a Step 1 answer in an existing project (one `init` could not take,
    for example a project `shortlist.py promote` created)."""
    if key not in SETTINGS:
        sys.exit(f"Unknown setting {key!r} — settable: {', '.join(SETTINGS)}")
    if value is None:
        current = {
            "grade": grade_for(st),
            "captions": {True: "yes", False: "no", None: "unset"}[st.get("captions")],
        }
        print(current.get(key, st.get(key)))
        return
    if key != "grade" and value not in SETTINGS[key]:
        sys.exit(f"{key} must be one of {', '.join(SETTINGS[key])}")
    if key in FRAME_SETTINGS and value != st.get(key) and rendered_anything():
        sys.exit(
            f"{key} cannot change after rendering: renders exist at {st.get(key)}. "
            f"Start a new project (pipeline.py init --{key} {value}) for the other size."
        )
    if key == "captions":
        st["captions"] = value == "yes"
        save_state(st)
        print(f"captions: {value}")
        return
    if key in FRAME_SETTINGS:
        st[key] = value
        save_state(st)
        print(f"{key}: {value}")
        return
    if value not in GRADE_CHOICES:
        sys.exit(
            f"grade must be one of {', '.join(GRADE_CHOICES)} (or pass --lut to "
            "render_reel.py for a custom look)"
        )
    st["grade"] = value
    save_state(st)
    print(f"grade: {value} — check_master renders with it")


def main():
    ap = argparse.ArgumentParser()
    sub = ap.add_subparsers(dest="cmd", required=True)
    p_init = sub.add_parser("init")
    p_init.add_argument("--target-duration", type=float, default=30)
    p_init.add_argument(
        "--aspect",
        choices=ASPECTS,
        default="9:16",
        help="Frame aspect. 9:16 for reels/shorts, 16:9 for a landscape YouTube cut.",
    )
    p_init.add_argument(
        "--captions",
        choices=("yes", "no"),
        default=None,
        help="Burn in captions. Ask the user; talking-head reels are watched muted.",
    )
    p_init.add_argument(
        "--resolution",
        choices=RESOLUTIONS,
        default="1080",
        help="Mezzanine/master size. 4k = 2160x3840 archival "
        "master; platforms downscale on delivery.",
    )
    p_init.add_argument(
        "--mode",
        choices=MODES,
        default="music-video",
        help="music-video: beat-synced montage. talking-head: VO spine + b-roll.",
    )
    sub.add_parser("status")
    sub.add_parser("next")
    p_mode = sub.add_parser("mode")
    p_mode.add_argument("value", nargs="?", choices=MODES, help="omit to print the current mode")
    p_gate = sub.add_parser("gate")
    p_gate.add_argument("n", type=int, choices=(1, 2))
    p_gate.add_argument("action", choices=("presented", "approved", "nle-wait", "reopen"))
    p_gate.add_argument(
        "--accept-unverified",
        metavar="WHY",
        help="approve although a check SKIPPED (no backend); the "
        "reason is recorded with the decision",
    )
    p_cfg = sub.add_parser("config")
    p_cfg.add_argument("key", choices=tuple(SETTINGS))
    p_cfg.add_argument("value", nargs="?")
    args = ap.parse_args()

    if args.cmd == "init":
        return cmd_init(args)
    st = load_state()
    if args.cmd == "status":
        cmd_status(st)
    elif args.cmd == "next":
        print(next_action(st))
    elif args.cmd == "mode":
        cmd_mode(st, args.value)
    elif args.cmd == "gate":
        cmd_gate(st, args.n, args.action, args.accept_unverified)
    elif args.cmd == "config":
        cmd_config(st, args.key, args.value)


if __name__ == "__main__":
    main()

skills

tile.json