"""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"] # Ref2VA (full-reference) mode: the six native H3 reference sections in canonical # order, mirroring web/h3_prompt_schema_core.mjs H3_REFERENCE_SECTIONS. The skill # emits this format; t2va (3-line) stays as an auto-detected legacy path. REF2VA_SECTIONS = ["subject_definitions", "summary", "retention_analysis", "detailed_description", "overall_soundscape", "non_diegetic_music"] REF2VA_TASK_DIRECTIVE = "[reference generation]" REF2VA_RETENTION_MARKERS = {"fully_preserved", "partially_preserved", "attribute_transfer", "weak_reference"} # subject_definitions is a lean identity anchor (who the label is, tied to its # reference image) - never the full head-to-toe look and never a nude/bare skin # state; both are woven into the [Shot 1] body according to what the scene shows. REF2VA_DEF_MAX_WORDS = 25 REF2VA_DEF_SKINSTATE_RE = re.compile( r"\b(?:nude|naked|unclothed|undressed|bare|barefoot|topless)\b", re.I) 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) # The gate is a composition gate, not a word counter: there is no target band and # no upper limit. The floor only trips on lazy output that could not possibly carry # the elements of a scene composition (subject, wardrobe, style, continuity, # blocking, camera, performance, texture, sound, exit state). THIN_FLOOR_SHORT = 100 # description words, scenes under 10 s THIN_FLOOR_LONG = 120 # description words, scenes of 10 s or longer 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 detect_prompt_mode(prompt_text): """t2va (3-line) vs ref2va (six-section) - mirrors detectH3Mode().""" if re.search(r"^(?:subject_definitions|summary|retention_analysis|" r"detailed_description):", prompt_text, re.M): return "ref2va" return "t2va" def _split_ref2va_sections(lines, where): """Group ref2va prompt lines into [(section, [content lines])] in file order. A line whose stripped form starts with '
:' opens that section (its content is the rest of that line plus following lines until the next header) - the same rule parseH3Sections() applies.""" records = [] for line in lines: stripped = line.strip() hit = None for sec in REF2VA_SECTIONS: if stripped.startswith(sec + ":"): hit = sec break if hit is not None: rest = stripped[len(hit) + 1:].strip() records.append((hit, [rest] if rest else [])) elif records: records[-1][1].append(stripped) else: raise ValueError(f"{where}: ref2va prompt must open with " f"'subject_definitions:', got {stripped[:60]!r}") return records def check_ref2va_prompt(lines, dur, where, prev_handoff=None): """Structural + craft checks for one ref2va prompt array. Returns (shot_body, soundscape_text, dialogue_spans, defined_labels, wc) so the fragment chain (handoff mirror, outline match) can reuse them; wc is the detailed_description word count the thin-scene floor was applied to. """ if (not isinstance(lines, list) or len(lines) < 6 or not all(isinstance(line, str) and line.strip() for line in lines)): raise ValueError(f"{where}: ref2va prompt must be an array of non-empty " f"strings (headers on their own line, content on the " f"following lines)") records = _split_ref2va_sections(lines, where) names = [name for name, _ in records] if sorted(names) != sorted(REF2VA_SECTIONS): missing = [s for s in REF2VA_SECTIONS if s not in names] raise ValueError(f"{where}: ref2va sections missing {missing} - all six of " f"{REF2VA_SECTIONS} are required, each exactly once") if names != REF2VA_SECTIONS: raise ValueError(f"{where}: ref2va sections must be in canonical order " f"{REF2VA_SECTIONS}, got {names}") by_name = dict(records) summary = " ".join(by_name["summary"]).strip() if summary != REF2VA_TASK_DIRECTIVE: raise ValueError(f"{where}: summary must be exactly {REF2VA_TASK_DIRECTIVE!r} " f"(every scene is built from the wired subject references), " f"got {summary[:60]!r}") defs = by_name["subject_definitions"] if not defs: raise ValueError(f"{where}: subject_definitions is empty") defined = [] for line in defs: m = re.match(r"^(<(?:Subject|Picture|Video|Audio)\s+\d+>)\s+\S", line) if not m: raise ValueError(f"{where}: subject_definitions lines must start with a " f" label and name the subject (lean identity " f"anchor): {line[:60]!r}") if m.group(1) in defined: raise ValueError(f"{where}: {m.group(1)} is defined more than once") anchor = line[m.end(1):].strip() if REF2VA_DEF_SKINSTATE_RE.search(anchor): raise ValueError(f"{where}: {m.group(1)} definition carries a nude/bare " f"skin state - subject_definitions is a lean identity " f"anchor only; weave the skin state into the [Shot 1] body " f"where the scene exposes it: {line[:60]!r}") words = len(anchor.split()) if words > REF2VA_DEF_MAX_WORDS: raise ValueError(f"{where}: {m.group(1)} definition is {words} words - " f"subject_definitions is a lean identity anchor (who the " f"label is, tied to its reference image), not the full " f"head-to-toe look; weave the look into the [Shot 1] body " f"according to what the scene shows") defined.append(m.group(1)) if "" not in defined: raise ValueError(f"{where}: must be defined in subject_definitions") retained = {} for line in by_name["retention_analysis"]: m = re.match(r"^(<(?:Subject|Picture|Video|Audio)\s+\d+>)\s*:\s*(\S+)\s*$", line) if not m or m.group(2) not in REF2VA_RETENTION_MARKERS: raise ValueError(f"{where}: retention_analysis lines must be " f"': fully_preserved' (or partially_preserved / " f"attribute_transfer / weak_reference): {line[:60]!r}") retained[m.group(1)] = m.group(2) for label in defined: if label not in retained: raise ValueError(f"{where}: {label} has no retention_analysis entry") dd = "\n".join(by_name["detailed_description"]).strip() if "[Shot 1]" not in dd: raise ValueError(f"{where}: detailed_description must contain '[Shot 1]'") style_part, _, body = dd.partition("[Shot 1]") body = body.strip() if not style_part.strip(): raise ValueError(f"{where}: detailed_description needs 1-2 style sentences " f"before [Shot 1] (medium, lighting quality, palette)") wc = len((style_part + " " + body).split()) floor = THIN_FLOOR_LONG if dur >= 10 else THIN_FLOOR_SHORT if wc < floor: raise ValueError(f"{where}: detailed_description is only {wc} words - too thin " f"to carry the elements of a scene composition (subject, " f"wardrobe, style, continuity, blocking, camera, performance, " f"texture, sound, exit state)") if "" not in body: raise ValueError(f"{where}: the [Shot 1] body must re-state and " f"carry the head-to-toe look woven into the action (lean " f"definitions do not render)") if " is now " in dd.lower(): raise ValueError(f"{where}: change stated as bare outcome instead of shown progression") if re.search(r"\bbare\b", dd, re.I): print(f" note: {where} description says 'bare' - call uncovered body parts " f"'nude' (e.g. 'nude arms')") ssc_text = "\n".join(by_name["overall_soundscape"]).strip() if not ssc_text: raise ValueError(f"{where}: overall_soundscape is empty") ndm_text = "\n".join(by_name["non_diegetic_music"]).strip() if ndm_text.upper() != "N/A": print(f" note: {where} non_diegetic_music is {ndm_text[:40]!r} - N/A unless " f"the user asked for a score") spans = [MARKER_RE.sub("", span, count=1).strip() for span in DIALOGUE_SPAN_RE.findall(dd)] if spans and not re.search(r"silently with mouth", dd): raise ValueError(f"{where}: dialogue span lacks a 'silently with mouth' cue") if prev_handoff is not None: prev_ssc = "" if isinstance(prev_handoff, dict): prev_ssc = str(prev_handoff.get("soundscape", "")) if prev_ssc and not CONTINUITY_RE.search(ssc_text): raise ValueError(f"{where}: soundscape does not continue the previous audio " f"bed (say 'the same ... continues')") if prev_ssc and not CONTINUITY_RE.search(body): raise ValueError(f"{where}: description does not open inside the previous " f"end_state (use a continuity cue: 'Continue the same ...', " f"'without resetting the motion')") return body, ssc_text, spans, defined, wc 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 per shot, mode-detected: t2va (the 3 native sections) or ref2va (the six native reference sections). Mirrors web/h3_prompt_schema_core.mjs H3_BASE_SECTIONS / H3_REFERENCE_SECTIONS.""" assert plan["prompt_prefix"] == [""], \ "prompt_prefix must be exactly [''] (empirical: better H3 results, no prose preamble)" counts = [] modes = [] for idx, shot in enumerate(plan["shots"], 1): raw_prompt = shot["prompt"] dur = float(shot.get("duration_seconds", plan.get("defaults", {}).get("duration_seconds", 15))) if not isinstance(raw_prompt, list): continue # string prompt: validate_plan already ensured it is non-empty mode = detect_prompt_mode("\n".join(raw_prompt)) modes.append(mode) if mode == "ref2va": body, _ssc, _spans, _defs, wc = check_ref2va_prompt( raw_prompt, dur, f"shot {idx}") else: lines = raw_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)" if re.search(r"\bbare\b", lines[0], re.I): print(f" note: shot {idx} description says 'bare' - call uncovered body " f"parts 'nude' (e.g. 'nude arms')") 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" counts.append(f"{wc}w @ {dur:g}s") if modes and len(set(modes)) == 1 and modes[0] == "ref2va": print(" H3 section structure: all shots are ref2va - the six reference " "sections in canonical order, summary [reference generation]") elif modes and len(set(modes)) == 1: print(" H3 section structure: all shots have the 3 sections in canonical order") else: print(" H3 section structure: mixed t2va/ref2va shots (each shot auto-detected)") print(" description lengths:", counts, "| composition elements are the gate - no word band") 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 not prompt or not all(isinstance(line, str) and line.strip() for line in prompt)): raise ValueError(f"{where}: prompt must be an array of non-empty strings") mode = detect_prompt_mode("\n".join(prompt)) spans = [] if mode == "ref2va": desc, ssc, spans, _defs, wc = check_ref2va_prompt( prompt, dur, where, prev_handoff=prev_handoff) else: if len(prompt) != 3: raise ValueError(f"{where}: t2va prompt must be an array of exactly 3 " f"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()) floor = THIN_FLOOR_LONG if dur >= 10 else THIN_FLOOR_SHORT if wc < floor: raise ValueError(f"{where}: description is only {wc} words - too thin to carry " f"the elements of a scene composition (subject, wardrobe, " f"style, continuity, blocking, camera, performance, texture, " f"sound, exit state)") if "" not in desc: raise ValueError(f"{where}: description must re-state (prefix is empty)") if re.search(r"\bbare\b", desc, re.I): print(f" note: {where} description says 'bare' - call uncovered body parts " f"'nude' (e.g. 'nude arms')") 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 mode == "t2va" and 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 prev_line and not CONTINUITY_RE.search(desc): raise ValueError(f"{where}: description does not open inside the previous " f"end_state (use a continuity cue: 'Continue the same ...', " f"'without resetting the motion')") 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} 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": [], }, } # Ref2VA fragment: the six native H3 reference sections, one line per element, # headers on their own line. handoff.soundscape copies the soundscape CONTENT # line (the element after the overall_soundscape: header), not the header. REF2VA_NURSE = { "id": "corridor_walk", "duration_seconds": 8, "prompt": [ "subject_definitions:", " the night nurse, matching her subject reference image.", "summary:", "[reference generation]", "retention_analysis:", ": fully_preserved", "detailed_description:", "Photorealistic cool fluorescent lighting, soft clinical palette, stable " "over-the-shoulder tracking shots.", "[Shot 1] Continue the same walk along the corridor without resetting the " "motion. , the same night nurse from her reference image with a " "slim build and dark brown hair pulled back in a low bun, 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. Her pale green scrub top and " "matching scrub trousers hang smooth as she leans into the push, her nude " "hands below the scrub cuffs wrapped around the cold handle, and her white " "sneakers land heel first and roll to the toe, her nude lower legs showing " "above the sneaker collars with each stride. 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. The cup's surface trembles with each push, and " "the hem of her scrub top sways in counterpoint to the trolley's roll. Her " "jaw stays set, her calm grey 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": "the same low fluorescent hum and distant trolley squeak " "continue, a soft draught breathing under the far door.", "dialogue_used": [], }, } REF2VA_DOOR = { "id": "door_stop", "duration_seconds": 8, "prompt": [ "subject_definitions:", REF2VA_NURSE["prompt"][1], "summary:", "[reference generation]", "retention_analysis:", ": fully_preserved", "detailed_description:", REF2VA_NURSE["prompt"][7], "[Shot 1] Continue the same corridor walk without resetting the motion, the " "trolley still rolling at her pace. , the same night nurse from " "her reference image with her dark brown hair still in its low bun, eases " "the steel trolley to a stop beside the blue door, both hands relaxing on " "the handle one after the other, its last wheel squeak dying on the " "linoleum. Her pale green scrubs settle as her shoulders drop, the white " "sneakers planting at hip width, the nude hands below the scrub cuffs " "opening off the handle while her nude lower legs stay above the sneaker " "collars. The camera holds its over-the-shoulder framing while her " "shoulders settle and the paper cup's surface stills on the trolley top; " "the fluorescent panels keep their even rhythm overhead, the corridor walls " "stay in soft focus, and her scrub-top hem sways once and hangs. Her right " "hand leaves the handle, opens, and closes on the door's cold push bar " "while the clipped chart keeps swaying on its clip.", "overall_soundscape:", "the same low fluorescent hum continues, the trolley wheels fall silent, a " "soft draught breathing under the far door.", "non_diegetic_music:", "N/A", ], "_handoff": { "end_state": "Her right hand is closing on the cold push bar, trolley at her " "hip, cup stilled, camera at her shoulder.", "soundscape": "the same low fluorescent hum continues, the trolley wheels " "fall silent, 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 _ref2va_short(**over): base = json.loads(json.dumps(REF2VA_NURSE)) # 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("\nRef2VA fragments (six-section format) that must PASS:") rh = validate_fragment(json.loads(json.dumps(REF2VA_NURSE)), index=1, total=2) validate_fragment(json.loads(json.dumps(REF2VA_DOOR)), index=2, total=2, prev_handoff=rh) print(" all ref2va PASS cases ok") print("\nRef2VA edge cases that must FAIL:") no_ret = _ref2va_short() no_ret["prompt"] = [l for l in no_ret["prompt"] if not l.startswith(": ")] wrong_summary = _ref2va_short() idx_sum = wrong_summary["prompt"].index("[reference generation]") wrong_summary["prompt"][idx_sum] = "[video continuation]" no_style = _ref2va_short() no_style["prompt"].remove( "Photorealistic cool fluorescent lighting, soft clinical palette, stable " "over-the-shoulder tracking shots.") out_of_order = _ref2va_short() p = out_of_order["prompt"] i_sum, i_def = p.index("summary:"), p.index("subject_definitions:") p[i_sum], p[i_def] = p[i_def], p[i_sum] nude_defs = _ref2va_short() nude_defs["prompt"][1] = (" is a night nurse with nude hands below " "the scrub cuffs.") dump_defs = _ref2va_short() dump_defs["prompt"][1] = (" is a night nurse in her thirties with a " "slim build, dark brown hair pulled back in a low bun, " "and calm grey eyes, wearing a pale green scrub top and " "matching scrub trousers, white sneakers, and a lanyard " "ID badge at her chest.") r2_cases = [ ("missing retention_analysis entry", no_ret, {}), ("summary directive not [reference generation]", wrong_summary, {}), ("no style sentences before [Shot 1]", no_style, {}), ("sections out of canonical order", out_of_order, {}), ("nude/bare state in subject_definitions", nude_defs, {}), ("head-to-toe look dump in subject_definitions", dump_defs, {}), ] for i, (label, obj, kwargs) in enumerate(r2_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}") 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 too thin to compose the scene", _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("Legacy t2va worked example (mode auto-detected):") validate_plan(plan) check_h3_sections(plan) print("\nRef2VA plan (six-section reference format):") ref2va_plan = { "prompt_prefix": [""], "defaults": {"duration_seconds": 8, "steps": 20}, "shots": [ {"id": "corridor_walk", "prompt": list(REF2VA_NURSE["prompt"]), "duration_seconds": 8}, {"id": "door_stop", "prompt": list(REF2VA_DOOR["prompt"]), "duration_seconds": 8}, ], } validate_plan(ref2va_plan) check_h3_sections(ref2va_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()