"""Standalone replica of the plan_json validation rules from chain_nodes.py
(_h3_frame_length, _validate_h3_length, _safe_name, _prompt_text) used to
verify the system-prompt worked example and edge cases.
Task 10 additions: a scene-agent FRAGMENT validator (one scene per turn of the
agent workflow) plus a CLI:
python verify_plan_rules.py # embedded test suite
python verify_plan_rules.py plan FILE # validate a final plan JSON
python verify_plan_rules.py fragment FILE # validate one scene fragment
[--index N] [--total N] [--prev PREV_FILE] # --prev chains the handoff
"""
import json
import math
import re
FPS = 24
MAX_SHOTS = 128
MAX_SEED = 0xFFFFFFFFFFFFFFFF
MAX_H3_FRAMES = 3592
H3_SECTIONS = ["integrated_multimodal_description", "overall_soundscape",
"non_diegetic_music"]
FENCE_RE = re.compile(r"^\s*```[a-zA-Z0-9_-]*\s*\n(.*?)\n?\s*```\s*$", re.S)
DIALOGUE_SPAN_RE = re.compile(r"(.*?)")
MARKER_RE = re.compile(r"^\[[^\]]+\]\s*")
CONTINUITY_RE = re.compile(r"\b(same\b|continu|still\b)", re.I)
def load_json_text(text, label=""):
"""json.loads tolerant of a surrounding markdown fence (LLM output)."""
text = (text or "").strip().lstrip("\ufeff")
m = FENCE_RE.match(text)
if m:
text = m.group(1).strip()
return json.loads(text)
def _safe_name(value, fallback="chain"):
text = re.sub(r"[^A-Za-z0-9._-]+", "_", str(value or "").strip())
text = text.strip("._-")
return (text or fallback)[:96]
def _prompt_text(value, label=""):
if isinstance(value, list):
if not all(isinstance(line, str) for line in value):
raise ValueError(f"{label} line arrays may contain only strings.")
return "\n".join(value).strip()
return str(value or "").strip()
def _h3_frame_length(seconds):
seconds = float(seconds)
if not math.isfinite(seconds) or seconds <= 0:
raise ValueError("duration must be finite positive")
requested = max(5, int(math.ceil(seconds * FPS - 1e-9)))
length = requested + (5 - requested % 17) % 17
if length > MAX_H3_FRAMES:
raise ValueError("too long")
return length
def validate_plan(raw, default_duration=15.0, default_steps=20):
if isinstance(raw, list):
raw = {"shots": raw}
if not isinstance(raw, dict):
raise ValueError("must be object or list")
shots_raw = raw.get("shots")
if not isinstance(shots_raw, list) or not shots_raw:
raise ValueError("requires non-empty shots")
if len(shots_raw) > MAX_SHOTS:
raise ValueError("too many shots")
defaults = raw.get("defaults") if isinstance(raw.get("defaults"), dict) else {}
dd = float(defaults.get("duration_seconds", default_duration))
ds = int(defaults.get("steps", default_steps))
if not math.isfinite(dd) or dd <= 0:
raise ValueError("default duration must be positive")
if ds < 1:
raise ValueError("default steps >= 1")
prompt_prefix = _prompt_text(raw.get("prompt_prefix", raw.get("global_prompt", "")))
seen = set()
delivered_total = 0
for offset, item in enumerate(shots_raw):
idx = offset + 1
if isinstance(item, str):
item = {"prompt": item}
if not isinstance(item, dict):
raise ValueError(f"shot {idx} not object/string")
shot_id = _safe_name(item.get("id", "clip_%04d" % idx), "clip_%04d" % idx)
if shot_id in seen:
raise ValueError(f"duplicate id {shot_id}")
seen.add(shot_id)
scene_prompt = _prompt_text(item.get("prompt", ""))
if not scene_prompt and not prompt_prefix:
raise ValueError(f"shot {idx} needs a prompt")
explicit = item.get("length", item.get("frames"))
if explicit is None:
dur = float(item.get("duration_seconds", dd))
if not math.isfinite(dur) or dur <= 0:
raise ValueError(f"shot {idx} bad duration")
raw_frames = _h3_frame_length(dur)
else:
n = int(explicit)
if n < 5 or n > MAX_H3_FRAMES or n % 17 != 5:
raise ValueError(f"shot {idx} bad length {n}")
raw_frames = n
steps = int(item.get("steps", ds))
if steps < 1 or steps > 10000:
raise ValueError(f"shot {idx} steps")
seed = item.get("seed")
if seed is not None:
s = int(seed)
if s < 0 or s > MAX_SEED:
raise ValueError(f"shot {idx} seed out of range")
context = 22 # default node context
delivered = raw_frames if idx == 1 else raw_frames - context
if idx > 1 and raw_frames <= context:
raise ValueError(f"shot {idx} shorter than context")
if idx > 1 and delivered_total < context:
raise ValueError(f"shot {idx-1} delivered too few for shot {idx} context")
delivered_total += delivered
print(f" shot {idx} id={shot_id!r} raw={raw_frames} delivered={delivered} "
f"steps={steps}")
print(f" total delivered: {delivered_total} frames = {delivered_total/FPS:.2f}s")
return True
WORKED_EXAMPLE = r"""
{
"prompt_prefix": [""],
"defaults": { "duration_seconds": 15, "steps": 20 },
"shots": [
{
"id": "greenhouse_arrival",
"prompt": [
"integrated_multimodal_description: [Shot 1] Opening scene. , the adult bicycle courier, steps off his silver bicycle at the wet gravel path outside the glass greenhouse and walks it slowly through the entrance, right hand on the handlebar, left thumb hooked under the strap of the olive messenger bag as the kraft paper parcel presses against his hip. The camera is a stable landscape tracking shot at eye level, gliding sideways at his exact walking pace, keeping his face, the parcel, and the fogged glass wall behind him in frame; the camera height and the direction of travel never change. Photorealistic overcast rainy daylight filters through the fogged panes and lays soft grey light across his mustard-yellow waterproof jacket; rain beads and long streaks run down the glass, and the wet paving glistens under the bicycle wheels. Droplets dot his charcoal helmet, his dark teal trousers darken at the shins, and each footstep squeezes a small splash between the gravel stones. He breathes steadily with a relaxed jaw, eyes flicking up to the aisle numbers as he passes benches of potted ferns and clay pots, and the kraft paper shifts faintly against the bag strap with every step. End while he is crossing the interior threshold, front wheel still rolling over the concrete sill, coat sleeve mid-swing, motion clearly still in progress.",
"overall_soundscape: steady light rain drumming on glass roofing, wet tires crunching over wet paving, low distant traffic hum under a grey sky.",
"non_diegetic_music: N/A"
],
"duration_seconds": 15
},
{
"id": "greenhouse_delivery",
"prompt": [
"integrated_multimodal_description: [Shot 1] Continue the same forward stride and the same sideways camera move through the already-crossed threshold without resetting the motion, wet gravel giving way to polished concrete underfoot. , the same adult bicycle courier in his mustard-yellow waterproof jacket, dark teal trousers, and charcoal helmet, rolls the silver bicycle to the wooden potting table at the end of the aisle, wedges the front wheel against the table leg with his left hand, unbuckles the olive messenger flap, lifts the kraft paper parcel with both hands, and sets it down on the table with a soft, deliberate press. The camera glides to a stop at a calm medium-wide angle as he straightens to his full height and turns his shoulders toward the lens. He stands silently with mouth closed, then speaks. [English] Package for the greenhouse, right on time. He falls silently with mouth closed and lets a brief smile lift the corners of his mouth before it fades. Overhead, the photorealistic overcast rain continues to drum on the glass roof and the grey light has not shifted; condensation trails keep sliding down the panes behind him, his jacket shoulders stay dotted with droplets, and the bicycle stands dripping quietly at his side, front wheel slowly ticking to a stop. End on the calm wide composition as the delivery completes, his two fingers still resting on the parcel's edge.",
"overall_soundscape: the same rain on glass and wet paving continues, tires creak to a stop, the kraft paper parcel thuds softly on the wooden potting table.",
"non_diegetic_music: N/A"
],
"duration_seconds": 15
}
]
}
"""
def check_h3_sections(plan):
"""Structural check: every shot prompt is exactly the three native H3
sections in canonical order; dialogue lives only in the description line.
Mirrors web/h3_prompt_schema_core.mjs H3_BASE_SECTIONS ordering."""
assert plan["prompt_prefix"] == [""], \
"prompt_prefix must be exactly [''] (empirical: better H3 results, no prose preamble)"
for idx, shot in enumerate(plan["shots"], 1):
lines = shot["prompt"]
assert len(lines) == 3, f"shot {idx}: expected 3 prompt lines, got {len(lines)}"
positions = []
for sec in H3_SECTIONS:
m = re.search(rf"^{sec}:", lines[len(positions)], re.M)
assert m, f"shot {idx}: line {len(positions)+1} does not start with {sec}:"
positions.append(sec)
assert positions == H3_SECTIONS, f"shot {idx}: sections out of order"
assert lines[0].lstrip().startswith(
"integrated_multimodal_description: [Shot 1]"), f"shot {idx}: missing [Shot 1]"
wc = len(lines[0].split())
assert "" in lines[0], \
f"shot {idx}: description line must re-state (prefix is empty)"
dur = float(shot.get("duration_seconds",
plan.get("defaults", {}).get("duration_seconds", 15)))
lo, hi = (200, 300) if dur >= 10 else (150, 200)
assert lo <= wc <= hi, \
f"shot {idx}: {wc} words outside {lo}-{hi} budget for a {dur:g}s scene"
assert " is now " not in lines[0].lower(), \
f"shot {idx}: change stated as bare outcome instead of shown progression"
assert "" not in lines[1] and "" not in lines[1], \
f"shot {idx}: dialogue must not appear in the soundscape line"
if "" in lines[0]:
assert re.search(r"silently with mouth", lines[0]), \
f"shot {idx}: dialogue span lacks a mouth-state cue"
print(" H3 section structure: all shots have the 3 sections in canonical order")
print(" description word budget:",
[(f"{len(s['prompt'][0].split())}w @ "
f"{s.get('duration_seconds', plan.get('defaults', {}).get('duration_seconds', 15))}s")
for s in plan["shots"]], "| <10s: 150-200, >=10s: 200-300")
return True
# ---------------------------------------------------------------------------
# Scene-agent fragment validation (agent workflow, Task 10)
# ---------------------------------------------------------------------------
def validate_fragment(obj, index=1, total=None, prev_handoff=None, expect=None):
"""Validate one scene-agent fragment (the future shot of a plan).
obj -- parsed fragment: {id, duration_seconds, prompt, _handoff}
index/total -- position in the story (1-based) for messages
prev_handoff -- previous fragment's _handoff dict, or None for scene 1
expect -- optional outline row {id, duration_seconds, dialogue}
Returns the fragment's _handoff so callers can chain turns.
"""
where = f"fragment {index}" + (f"/{total}" if total else "")
if not isinstance(obj, dict):
raise ValueError(f"{where}: must be a JSON object")
allowed = {"id", "prompt", "duration_seconds", "_handoff", "steps", "seed"}
required = {"id", "prompt", "duration_seconds", "_handoff"}
unknown = set(obj) - allowed
if unknown:
raise ValueError(f"{where}: unknown keys {sorted(unknown)} (allowed: {sorted(allowed)})")
missing = required - set(obj)
if missing:
raise ValueError(f"{where}: missing keys {sorted(missing)}")
shot_id = obj["id"]
if not isinstance(shot_id, str) or not shot_id.strip():
raise ValueError(f"{where}: id must be a non-empty string")
if _safe_name(shot_id) != shot_id:
raise ValueError(f"{where}: id {shot_id!r} does not survive node sanitization")
if not re.fullmatch(r"[a-z0-9_]+", shot_id):
print(f" note: id {shot_id!r} is not lowercase snake_case (node would allow it)")
dur = obj["duration_seconds"]
if isinstance(dur, bool) or not isinstance(dur, (int, float)) or not math.isfinite(dur):
raise ValueError(f"{where}: duration_seconds must be a finite number")
if not 2 <= dur <= 15:
raise ValueError(f"{where}: duration_seconds {dur} outside the 2-15 window")
raw_frames = _h3_frame_length(dur)
prompt = obj["prompt"]
if (not isinstance(prompt, list) or len(prompt) != 3
or not all(isinstance(line, str) and line.strip() for line in prompt)):
raise ValueError(f"{where}: prompt must be an array of exactly 3 non-empty strings")
desc, ssc, ndm = prompt
if not desc.lstrip().startswith("integrated_multimodal_description: [Shot 1]"):
raise ValueError(f"{where}: line 1 must start with "
f"'integrated_multimodal_description: [Shot 1]'")
if not ssc.lstrip().startswith("overall_soundscape:"):
raise ValueError(f"{where}: line 2 must start with 'overall_soundscape:'")
if not ndm.lstrip().startswith("non_diegetic_music:"):
raise ValueError(f"{where}: line 3 must start with 'non_diegetic_music:'")
wc = len(desc.split())
lo, hi = (200, 300) if dur >= 10 else (150, 200)
if not lo <= wc <= hi:
raise ValueError(f"{where}: description is {wc} words, outside {lo}-{hi} "
f"for a {dur:g}s scene")
if "" not in desc:
raise ValueError(f"{where}: description must re-state (prefix is empty)")
if " is now " in desc.lower():
raise ValueError(f"{where}: change stated as bare outcome instead of shown progression")
if "" in ssc or "" in ssc:
raise ValueError(f"{where}: dialogue must not appear in the soundscape line")
spans = [MARKER_RE.sub("", span, count=1).strip()
for span in DIALOGUE_SPAN_RE.findall(desc)]
if spans and not re.search(r"silently with mouth", desc):
raise ValueError(f"{where}: dialogue span lacks a 'silently with mouth' cue")
handoff = obj["_handoff"]
if not isinstance(handoff, dict):
raise ValueError(f"{where}: _handoff must be an object")
for key in ("end_state", "soundscape", "dialogue_used"):
if key not in handoff:
raise ValueError(f"{where}: _handoff missing {key!r}")
end_state = handoff["end_state"]
if not isinstance(end_state, str) or len(end_state.split()) < 5:
raise ValueError(f"{where}: _handoff.end_state must describe the final frame "
f"(>= 5 words)")
if handoff["soundscape"] != ssc:
raise ValueError(f"{where}: _handoff.soundscape must copy the overall_soundscape "
f"line character for character")
used = handoff["dialogue_used"]
if not isinstance(used, list) or not all(isinstance(x, str) for x in used):
raise ValueError(f"{where}: _handoff.dialogue_used must be a list of strings")
if sorted(used) != sorted(spans):
raise ValueError(f"{where}: _handoff.dialogue_used {used} does not mirror the "
f" spans {spans}")
if prev_handoff is not None:
prev_line = ""
if isinstance(prev_handoff, dict):
prev_line = str(prev_handoff.get("soundscape", ""))
if prev_line and not CONTINUITY_RE.search(ssc):
raise ValueError(f"{where}: soundscape does not continue the previous audio "
f"bed (say 'the same ... continues')")
if expect is not None:
if expect.get("id") not in (None, shot_id):
raise ValueError(f"{where}: outline says id {expect.get('id')!r}, "
f"fragment says {shot_id!r}")
exp_dur = expect.get("duration_seconds")
if exp_dur is not None and float(exp_dur) != float(dur):
raise ValueError(f"{where}: outline says duration {exp_dur}, fragment says {dur}")
exp_dialogue = list(expect.get("dialogue") or [])
if exp_dialogue != list(used):
raise ValueError(f"{where}: outline dialogue {exp_dialogue} != "
f"dialogue_used {used}")
if "steps" in obj and not 1 <= int(obj["steps"]) <= 10000:
raise ValueError(f"{where}: steps out of range")
if "seed" in obj:
s = int(obj["seed"])
if s < 0 or s > MAX_SEED:
raise ValueError(f"{where}: seed out of range")
print(f" {where} id={shot_id!r} dur={dur:g}s raw={raw_frames} frames "
f"words={wc} (band {lo}-{hi}) handoff ok"
+ (f" dialogue={len(spans)}" if spans else ""))
return handoff
NURSE_OK = {
"id": "corridor_walk",
"duration_seconds": 8,
"prompt": [
"integrated_multimodal_description: [Shot 1] Continue the same walk along the "
"corridor without resetting the motion. , the same night nurse in "
"pale green scrubs and white sneakers, pushes the steel trolley forward with "
"both hands, its wheels squeaking softly on the linoleum, a paper cup and a "
"clipped chart riding on top. The camera keeps a steady over-the-shoulder "
"framing at her shoulder height, gliding at her pace, fluorescent panels "
"passing overhead in even rhythm, the corridor walls sliding past in soft "
"focus. Her sneakers land heel first and roll to the toe, the cup's surface "
"trembling with each push, and the hem of her scrub top sways in counterpoint "
"to the trolley's roll. Her jaw stays set, eyes forward, one loose strand of "
"hair lifting with each step; the trolley's shadow stretches and compresses "
"under each ceiling panel. Reaching the blue door at the corridor's end, she "
"slows the trolley to a stop and her right hand leaves the handle, closing on "
"the door's cold push bar.",
"overall_soundscape: the same low fluorescent hum and distant trolley squeak "
"continue, a soft draught breathing under the far door.",
"non_diegetic_music: N/A",
],
"_handoff": {
"end_state": "She is stopped at the blue door at the corridor's end, right "
"hand closing on the cold push bar, trolley at her hip, camera "
"still at her shoulder.",
"soundscape": "overall_soundscape: the same low fluorescent hum and distant "
"trolley squeak continue, a soft draught breathing under the far "
"door.",
"dialogue_used": [],
},
}
def _short_fragment(**over):
base = json.loads(json.dumps(NURSE_OK)) # deep copy
base.update(over)
return base
def run_fragment_suite():
print("Fragment edge cases that must PASS:")
handoff = validate_fragment(dict(NURSE_OK), index=1, total=2)
validate_fragment(_short_fragment(id="door_stop"), index=2, total=2,
prev_handoff=handoff)
spoken = _short_fragment(
id="door_words",
prompt=[
"integrated_multimodal_description: [Shot 1] Continue the same corridor "
"motion without resetting it as , the same night nurse in pale "
"green scrubs and white sneakers, halts the steel trolley at the blue "
"door, its wheels settling with a last squeak on the linoleum. She stands "
"silently with mouth closed, then speaks. [English] Room four, your "
"tea is ready. She falls silently with mouth closed and turns the "
"chart toward the door. The camera holds its over-the-shoulder framing "
"while her shoulders settle, the paper cup's surface stilling on the "
"trolley top, and the fluorescent panels hum their even rhythm above; "
"one loose strand of hair drifts as she exhales, the hem of her scrub "
"top sways once and hangs, and the corridor walls keep their soft focus "
"behind the steel frame. Her right hand stays flat on the trolley "
"handle, knuckles easing, while the door's cold push bar waits an inch "
"from her left palm and the draught under the door lifts the corner of "
"the clipped chart.",
NURSE_OK["prompt"][1],
"non_diegetic_music: N/A",
],
_handoff={
"end_state": "She stands at the blue door with the trolley at her hip.",
"soundscape": NURSE_OK["prompt"][1],
"dialogue_used": ["Room four, your tea is ready."],
})
validate_fragment(spoken, index=1, total=1)
print(" all fragment PASS cases ok")
print("\nFragment edge cases that must FAIL:")
prev = dict(NURSE_OK["_handoff"])
no_continuity = _short_fragment(
prompt=[NURSE_OK["prompt"][0],
"overall_soundscape: seagulls cry over fresh surf and a busker's "
"guitar plinks somewhere on the promenade.",
"non_diegetic_music: N/A"])
no_continuity["_handoff"] = dict(no_continuity["_handoff"],
soundscape=no_continuity["prompt"][1])
bad_spans = _short_fragment()
bad_spans["_handoff"] = dict(bad_spans["_handoff"],
dialogue_used=["A line nobody said."])
bad_ssc_copy = _short_fragment()
bad_ssc_copy["_handoff"] = dict(bad_ssc_copy["_handoff"],
soundscape="overall_soundscape: different text.")
cases = [
("missing _handoff", {k: v for k, v in NURSE_OK.items() if k != "_handoff"}, {}),
("duration outside 2-15", _short_fragment(duration_seconds=20), {}),
("description far under word budget",
_short_fragment(prompt=["integrated_multimodal_description: [Shot 1] "
" walks on. End mid-stride.",
NURSE_OK["prompt"][1], "non_diegetic_music: N/A"]), {}),
("bare 'is now' outcome",
_short_fragment(prompt=[NURSE_OK["prompt"][0].replace(
"Her jaw stays set", "Her face is now old"), NURSE_OK["prompt"][1],
"non_diegetic_music: N/A"]), {}),
("handoff.soundscape not the soundscape line", bad_ssc_copy, {}),
("dialogue_used does not mirror spans", bad_spans, {}),
("soundscape ignores previous audio bed", no_continuity,
{"prev_handoff": prev}),
("id disagrees with outline row", _short_fragment(id="hallway_walk"),
{"expect": {"id": "door_stop", "duration_seconds": 8, "dialogue": []}}),
("steps out of range", _short_fragment(steps=0), {}),
]
for i, (label, obj, kwargs) in enumerate(cases, 1):
try:
validate_fragment(obj, index=1, total=1, **kwargs)
print(f" case {i} ({label}) UNEXPECTEDLY PASSED <-- BUG")
except (ValueError, AssertionError) as exc:
print(f" case {i} ({label}) rejected: {exc}")
# The 90-second, 6-scene example user message -> plausible LLM output
SIX_SCENE = {
"prompt_prefix": [" is the same retired boxer...",
"Warm film look, one continuous take."],
"defaults": {"duration_seconds": 15, "steps": 20},
"shots": [{"id": f"kitchen_dance_{i:02d}", "prompt": ["Continue..."],
"duration_seconds": 15} for i in range(1, 7)],
}
# Edge cases that must PASS
edge_ok = [
{"shots": ["Opening scene.", "Continue through the doorway."]}, # bare strings
{"prompt_prefix": "Shared style.", "shots": [{"id": "a", "length": 362},
{"id": "b", "frames": 124}]}, # exact frames
{"prompt_prefix": "p", "shots": [{"id": "a", "prompt": ["x"], "duration_seconds": 7.5},
{"id": "b", "prompt": ["y"], "context_length": 0},
{"id": "c", "prompt": ["z"], "context_length": 0}]},
]
# Edge cases that must FAIL
edge_bad = [
{"prompt_prefix": "p", "shots": [{"id": "a", "length": 360}]}, # invalid grid
{"prompt_prefix": "p", "shots": [{"id": "a", "prompt": "x", "duration_seconds": 200}]},
{"shots": [{"id": "a", "prompt": "x"}, {"id": "a", "prompt": "y"}]}, # dup id
{"shots": []}, # empty shots
{"shots": [{"id": "a"}]}, # no prompt anywhere
]
def run_embedded_suite():
plan = json.loads(WORKED_EXAMPLE)
print("Worked example from system prompt:")
validate_plan(plan)
check_h3_sections(plan)
print("\nRepo I2V Studio example (with length/frames + string seeds):")
repo = {
"defaults": {"steps": 20},
"shots": [
{"id": "greenhouse_arrival", "prompt": "p", "length": 362,
"steps": 20, "seed": "6101"},
{"id": "greenhouse_delivery", "prompt": "p", "length": 362,
"steps": 20, "seed": "6102"},
],
}
validate_plan(repo)
print("\n6-scene 90s story example:")
validate_plan(SIX_SCENE)
print("\nEdge cases that must PASS:")
for i, case in enumerate(edge_ok):
validate_plan(case)
print(f" case {i} OK")
print("\nEdge cases that must FAIL:")
for i, case in enumerate(edge_bad):
try:
validate_plan(case)
print(f" case {i} UNEXPECTEDLY PASSED <-- BUG")
except ValueError as exc:
print(f" case {i} rejected: {exc}")
print()
run_fragment_suite()
# delivered-duration math check used in the TIMING section
print("\nTiming table (raw frames from duration):")
for s in (0.2, 1, 2, 5, 10, 15, 30, 149.666, 149.667):
try:
print(f" {s}s -> {_h3_frame_length(s)} raw frames")
except ValueError as exc:
print(f" {s}s -> rejected ({exc})")
def main():
import argparse
parser = argparse.ArgumentParser(
description="Validate H3 plan JSONs and scene-agent fragments "
"(replica of chain_nodes.py rules).")
sub = parser.add_subparsers(dest="cmd")
p_plan = sub.add_parser("plan", help="validate a final plan JSON")
p_plan.add_argument("file")
p_frag = sub.add_parser("fragment", help="validate one scene-agent fragment")
p_frag.add_argument("file")
p_frag.add_argument("--index", type=int, default=1)
p_frag.add_argument("--total", type=int, default=None)
p_frag.add_argument("--prev", default=None,
help="previous fragment file; chains the soundscape handoff")
args = parser.parse_args()
if args.cmd is None:
run_embedded_suite()
return
with open(args.file, encoding="utf-8-sig") as fh:
raw = load_json_text(fh.read(), args.file)
if args.cmd == "plan":
validate_plan(raw)
check_h3_sections(raw)
else:
prev = None
if args.prev:
with open(args.prev, encoding="utf-8-sig") as fh:
pf = load_json_text(fh.read(), args.prev)
if isinstance(pf, dict) and isinstance(pf.get("shots"), list) and pf["shots"]:
pf = pf["shots"][-1]
prev = pf.get("_handoff") if isinstance(pf, dict) else None
validate_fragment(raw, index=args.index, total=args.total, prev_handoff=prev)
print("OK")
if __name__ == "__main__":
main()