#!/usr/bin/env python3 """Merge MiniMax H3 scene-agent fragments into the final plan JSON for plan_json_input. Stage 3 of the agent workflow (outline -> one scene per turn -> assembly). Deterministic and byte-exact: fragment prompt strings are copied, never rewritten. Every fragment and the merged plan are validated with the same rules the node uses (replicated in verify_plan_rules.py) before anything is written. Usage: python build_plan.py outline.json scene_01.json scene_02.json scene_03.json -o plan.json python build_plan.py scene_01.json scene_02.json -o plan.json [--duration 10] [--steps 20] python build_plan.py --check plan.json # validate an existing plan file The outline file (from the scene agent's PROMPT A) is optional; it is auto-detected by its "scenes" key. When present, fragment ids, durations, and dialogue are checked against it in order. Fenced markdown JSON (```json ... ```) also parses. """ import argparse import json import os import sys sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import verify_plan_rules as vpr # noqa: E402 def load_json_file(path): try: with open(path, encoding="utf-8-sig") as fh: return vpr.load_json_text(fh.read(), path) except (OSError, ValueError) as exc: raise SystemExit(f"{path}: cannot read JSON ({exc})") def looks_like_outline(obj): return (isinstance(obj, dict) and isinstance(obj.get("scenes"), list) and bool(obj["scenes"]) and all(isinstance(row, dict) and "id" in row for row in obj["scenes"])) def extract_shots(obj, label): """Return the list of shot objects held in a fragment file.""" if isinstance(obj, list): return obj if isinstance(obj, dict): if isinstance(obj.get("shots"), list): return obj["shots"] if "prompt" in obj or "_handoff" in obj: return [obj] raise SystemExit(f"{label}: not a fragment file (need a shot object, a list of " f"shots, or an object with a 'shots' array)") def main(): ap = argparse.ArgumentParser( description="Merge H3 scene-agent fragments into a validated plan JSON.") ap.add_argument("files", nargs="*", help="outline JSON (optional, auto-detected) then fragment " "files in story order") ap.add_argument("-o", "--out", default=None, help="write the merged plan here (default: print to stdout)") ap.add_argument("--duration", type=float, default=10.0, help="defaults.duration_seconds when no outline is given") ap.add_argument("--steps", type=int, default=20, help="defaults.steps when no outline is given") ap.add_argument("--check", metavar="PLAN", default=None, help="validate an existing plan JSON and exit") args = ap.parse_args() if args.check: plan = load_json_file(args.check) print(f"Checking plan: {args.check}") vpr.validate_plan(plan) vpr.check_h3_sections(plan) print("PLAN OK") return if not args.files: ap.error("give fragment files (optionally an outline first), or --check PLAN") outline = None shots_in = [] for path in args.files: obj = load_json_file(path) if outline is None and looks_like_outline(obj): outline = obj print(f"outline: {path} ({len(obj['scenes'])} scenes)") continue shots_in.extend((path, shot) for shot in extract_shots(obj, path)) n = len(shots_in) if n == 0: raise SystemExit("no fragments found") if n > vpr.MAX_SHOTS: raise SystemExit(f"{n} fragments exceed MAX_SHOTS={vpr.MAX_SHOTS}") if outline and len(outline["scenes"]) != n: raise SystemExit(f"outline has {len(outline['scenes'])} scenes but {n} " f"fragments were given") defaults = {"duration_seconds": args.duration, "steps": args.steps} if outline and isinstance(outline.get("defaults"), dict): d = outline["defaults"] defaults = {"duration_seconds": d.get("duration_seconds", args.duration), "steps": int(d.get("steps", args.steps))} prev = None final_shots = [] for i, (path, shot) in enumerate(shots_in, 1): expect = None if outline: row = outline["scenes"][i - 1] expect = {"id": row.get("id"), "duration_seconds": row.get("duration_seconds"), "dialogue": row.get("dialogue") or []} print(f"\nfragment {i}/{n} from {path}:") prev = vpr.validate_fragment(shot, index=i, total=n, prev_handoff=prev, expect=expect) merged = {k: shot[k] for k in ("id", "prompt", "duration_seconds") if k in shot} for extra in ("steps", "seed"): if extra in shot: merged[extra] = shot[extra] final_shots.append(merged) # _handoff stripped by construction plan = {"prompt_prefix": [""], "defaults": defaults, "shots": final_shots} print("\nMerged plan:") vpr.validate_plan(plan) vpr.check_h3_sections(plan) out_text = json.dumps(plan, indent=2, ensure_ascii=False) + "\n" if args.out: with open(args.out, "w", encoding="utf-8") as fh: fh.write(out_text) print(f"\nwrote {args.out} - paste its full contents into plan_json_input") else: print("\n" + out_text) if __name__ == "__main__": main()