Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.
feat(video-frames): --spill removes key reflections the model painted into the subject
Soohong Kimbd28c87e1dfb
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c6f732e..af54d30 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,10 @@All notable public changes to `sprite-gen` are recorded here. Versions track the `version:` field in `SKILL.md` and `pyproject.toml`.+## Unreleased++- `video-frames --spill small|full|auto` and `video-set --spill` (default `auto`): remove the key colour a video model paints into the subject — a reflection across metal, a tint on a pale surface — which the chroma engine's trapped-spill pass leaves alone once the patch is larger than its small-cluster cap. `auto` keys the still the clip was made from and measures its own key-coloured material; none worth the name means every key tint in the clip is spill (`full`), otherwise the still-pipeline rule stays (`small`). Colour only — alpha is unchanged — and colours without key tint are untouched. `video-frames` defaults to `small`, byte-identical to before; the frames report records the decision under `spill`.+## v2.3.0 - Grok video modes: first-last, reference, extend, edit- `sprite-gen video` gains the other Grok Imagine generation modes: `--last-frame` pins the closing frame (alone or with `--image`), and `--reference` (repeatable, up to 7) guides the clip with reference images named `<IMAGE_0>`, `<IMAGE_1>`, … in the prompt. `--image` is no longer required on its own. The image-only request body is unchanged and pinned by a snapshot test; the video → loop pipeline (`video-canvas`, `video-frames`, `video-loop`, `video-set`) is untouched.diff --git a/docs/video-pipeline.md b/docs/video-pipeline.mdindex a97bf3c..7b4ad47 100644--- a/docs/video-pipeline.md+++ b/docs/video-pipeline.md@@ -126,6 +126,31 @@ touches the edge (a key-tinted blend pixel with low alpha), so a "framed too tigmessage with a small residual count is still a framing problem, not a key problem.`--allow-edge-contact` accepts the clipping on purpose.+## 3a. Spill — key colour the model painted into the subject++A video model does not only leave the key around the subject; it paints it *onto* the+subject — a green sheen across polished metal, a tint on a pale surface. Those pixels are+opaque, often many pixels in from the edge, and form patches far larger than the chroma+engine's trapped-spill cap (clusters up to 0.5 % of the subject). The engine leaves a large+key-tinted patch alone on purpose, because in a still it is usually the subject's own+key-coloured material. In a clip it usually is not.++The still the clip was made from settles it. `video-frames --spill` takes:++| Mode | What is corrected |+|---|---|+| `small` (default) | only small key-tinted clusters — the still pipeline's rule, byte-identical output |+| `full` | every key-tinted cluster, whatever its size (colour only: alpha is unchanged) |+| `auto` | keys `--reference` (the still) with the same matte and counts its strongly key-tinted pixels; a share ≤ 0.5 % means the still has no key-coloured material of its own → `full`, otherwise `small` |++`video-set` passes `--spill auto` with each item's `canvas.png` as the reference (override+with `--spill small|full`), so a green-free character loses the reflections while a+character that *is* green keeps its colour. The decision and its numbers are recorded in+the frames report under `spill`. The correction is the engine's own `despill_color` blend+model (observed = (1−k)·subject + k·key, solved for the subject), so colours without key+tint are untouched. Faint tints whose cluster never crosses the strong-tint bar are left+as they are.+## 3b. Canvas shape for raised limbs and wide costumes`video-set` picks the canvas from the state row alone. Two things that are not a jump ordiff --git a/sprite_gen/frames/cutout.py b/sprite_gen/frames/cutout.pyindex 898d813..452a372 100644--- a/sprite_gen/frames/cutout.py+++ b/sprite_gen/frames/cutout.py@@ -271,7 +271,7 @@ def _matte_route(}-def extract_route(image: Image.Image, kind: str) -> tuple[Image.Image, dict[str, Any]]:+def extract_route(image: Image.Image, kind: str, *, spill_max_fraction: float | None = None) -> tuple[Image.Image, dict[str, Any]]:"""Magenta/green key background → reuse the verified `extract` chroma engine (no drift).The engine keys from the background colour it detects on the borders@@ -285,8 +285,9 @@ def extract_route(image: Image.Image, kind: str) -> tuple[Image.Image, dict[str,target = KEY_TARGETS[kind]painted = detect_background_key_rgb(image, target)+ extra = {} if spill_max_fraction is None else {"spill_max_fraction": spill_max_fraction}result = remove_chroma_background(- image, target, _EXTRACT_KEY_THRESHOLD, _EXTRACT_FRINGE_THRESHOLD, _EXTRACT_FRINGE_DELTA+ image, target, _EXTRACT_KEY_THRESHOLD, _EXTRACT_FRINGE_THRESHOLD, _EXTRACT_FRINGE_DELTA, **extra)return result.convert("RGBA"), {"route": f"extract:{kind}",@@ -305,11 +306,13 @@ def cutout(erode: float = ERODE_DEFAULT,tolerance: int = CHROMA_TOLERANCE,white_check_dir: Path | None = None,+ spill_max_fraction: float | None = None,) -> dict[str, Any]:"""Cut a uniform-background imported image to a clean transparent RGBA PNG.`key`: "auto" (detect from corners) | "white" (matte) | "magenta" | "green"- (reuse the extract chroma engine). Returns a stats dict. Raises SystemExit if+ (reuse the extract chroma engine). `spill_max_fraction` overrides the chroma+ engine's trapped-spill cluster cap (None = the engine default). Returns a stats dict. Raises SystemExit ifthe key is unknown, the background cannot be located, or any transparent pixelkeeps non-zero RGB (No Silent Fallback)."""@@ -321,7 +324,7 @@ def cutout(route = _detect_key_kind(_corner_average(image)) if key == "auto" else keyif route in ("magenta", "green"):- result, route_stats = extract_route(image, route)+ result, route_stats = extract_route(image, route, spill_max_fraction=spill_max_fraction)else:result, route_stats = _matte_route(image, input_path, strength, band, erode, tolerance)diff --git a/sprite_gen/frames/extract.py b/sprite_gen/frames/extract.pyindex a5ad2e1..15de7d0 100644--- a/sprite_gen/frames/extract.py+++ b/sprite_gen/frames/extract.py@@ -364,6 +364,19 @@ _IN_BAND_UNMIX_KEY_DEPTH = 2_SPILL_MIN_TINT = 40.0+def key_material_pixels(image: Image.Image, chroma_key: tuple[int, int, int]) -> tuple[int, int]:+ """Opaque pixels that are strongly key-tinted (the trapped-spill bar, `_SPILL_MIN_TINT`),+ and all opaque pixels, of an already keyed RGBA image. A still that has almost none+ carries no key-coloured material of its own."""+ keyed_channels, unkeyed_channels = _key_channel_split(chroma_key)+ data = np.asarray(image.convert("RGBA")).astype(np.int32)+ opaque = data[..., 3] > 0+ if not keyed_channels:+ return 0, int(opaque.sum())+ tint = _key_tint_field(data[..., :3], keyed_channels, unkeyed_channels)+ return int((opaque & (tint > _SPILL_MIN_TINT)).sum()), int(opaque.sum())++def remove_chroma_background(image: Image.Image,chroma_key: tuple[int, int, int],diff --git a/sprite_gen/video/batch.py b/sprite_gen/video/batch.pyindex ed8e28c..c0f1808 100644--- a/sprite_gen/video/batch.py+++ b/sprite_gen/video/batch.py@@ -92,6 +92,7 @@ def run_item(video_runner: Callable[..., int] = run_video_cli,shape: str | None = None,anchor: str = "none",+ spill: str = "auto",) -> dict[str, Any]:item_dir = root / itemitem_dir.mkdir(parents=True, exist_ok=True)@@ -123,8 +124,9 @@ def run_item(if attempts[-1] != 0 or not clip.exists():raise SystemExit(f"clip generation failed after {len(attempts)} attempt(s); see {item_dir / 'clip.log'}")- fr = frames_mod.run_frames(clip, item_dir / "frames", key=key, allow_edge_contact=False, report_path=item_dir / "frames.report.json")+ fr = frames_mod.run_frames(clip, item_dir / "frames", key=key, allow_edge_contact=False, report_path=item_dir / "frames.report.json", spill=spill, reference=canvas_png)result["frames"] = {k: fr[k] for k in ("fps", "frames", "alpha_zero_pct_min", "alpha_zero_pct_max")}+ result["frames"]["spill"] = fr.get("spill", {}).get("mode")lp = loop_mod.run_loop(Path(fr["keyed_dir"]), item_dir / "loop", fps=float(fr["fps"]), state=state, min_len=None, max_len=None, n_out=None, seam_max=loop_mod.SEAM_RATIO_MAX, name=item, report_path=item_dir / "loop.report.json", anchor=anchor)result["loop"] = {"kind": lp["cycle"].get("kind", "periodic"), "cycle": lp["cycle"]["length"], "period": lp["cycle"]["period_global"], "cycle_ratio": round(lp["cycle"]["ratio"], 3), "seam_ratio": lp["resampled_seam_ratio"], "n_out": lp["n_out"], "drift_px": lp["strip"].get("drift_px", 0), "gif": lp["gif"]["file"], "webp": lp["webp"]["file"], "strip": lp["strip"]["path"]}result["ok"] = True@@ -162,6 +164,7 @@ def run_set(video_runner: Callable[..., int] = run_video_cli,shape: str | None = None,anchor: str = "none",+ spill: str = "auto",) -> dict[str, Any]:root = root.expanduser().resolve()root.mkdir(parents=True, exist_ok=True)@@ -171,7 +174,7 @@ def run_set(items = [(f"{d}-{s}", d, s) for d in bases for s in states]results: list[dict[str, Any]] = []with ThreadPoolExecutor(max_workers=max(1, concurrency)) as ex:- futures = {ex.submit(run_item, item=i, direction=d, state=s, base=bases[d], root=root, character=character, duration=duration, resolution=resolution, key=key, force=force, gap=gap, video_runner=video_runner, shape=shape, anchor=anchor): i for i, d, s in items}+ futures = {ex.submit(run_item, item=i, direction=d, state=s, base=bases[d], root=root, character=character, duration=duration, resolution=resolution, key=key, force=force, gap=gap, video_runner=video_runner, shape=shape, anchor=anchor, spill=spill): i for i, d, s in items}for fut in as_completed(futures):r = fut.result()results.append(r)@@ -208,6 +211,7 @@ def add_arguments(parser: argparse.ArgumentParser) -> None:parser.add_argument("--start-gap", type=float, default=START_GAP_SECONDS, help="seconds between clip request starts")parser.add_argument("--shape", choices=canvas_mod.SHAPES, help="force one canvas shape for every state (e.g. wide for a costume or arms that leave a 1:1 frame)")parser.add_argument("--anchor", choices=loop_mod.ANCHOR_MODES, default="none", help="feet: remove in-canvas drift so every cell stands on the mean foot line")+ parser.add_argument("--spill", choices=frames_mod.SPILL_MODES, default="auto", help="auto: judge key reflections from each item's canvas still (default); small / full: force")parser.add_argument("--force", action="store_true", help="regenerate clips that already exist")@@ -218,7 +222,7 @@ def run(**kwargs: object) -> int:root=Path(str(kwargs["out_dir"])), character=kwargs.get("character"), # type: ignore[arg-type]duration=int(kwargs.get("duration") or 6), resolution=str(kwargs.get("resolution") or "720p"), key=str(kwargs.get("key") or "auto"),concurrency=int(kwargs.get("concurrency") or 3), force=bool(kwargs.get("force")), gap=float(kwargs.get("start_gap") or START_GAP_SECONDS),- shape=(str(kwargs["shape"]) if kwargs.get("shape") else None), anchor=str(kwargs.get("anchor") or "none"),+ shape=(str(kwargs["shape"]) if kwargs.get("shape") else None), anchor=str(kwargs.get("anchor") or "none"), spill=str(kwargs.get("spill") or "auto"),)return 0 if not payload["failed"] else 1diff --git a/sprite_gen/video/frames.py b/sprite_gen/video/frames.pyindex 248e109..5d266f0 100644--- a/sprite_gen/video/frames.py+++ b/sprite_gen/video/frames.py@@ -36,6 +36,15 @@ from sprite_gen.frames.extract import is_border_key_candidatefrom sprite_gen.spec.runio import atomic_write_textEDGE_ROWS = 4 # rows/cols inspected at each edge+# Spill (key colour the video model painted INTO the subject — a reflection on+# metal, a tint on skin near the edge). The chroma engine treats a large key-tinted+# cluster as the subject's own key-coloured material and leaves it alone; a video+# model paints reflections that are exactly that large. The still the clip was made+# from is the evidence: if the still carries (almost) no key-coloured material, every+# key tint in the clip was painted by the model and is spill.+SPILL_MODES = ("auto", "small", "full")+SPILL_FULL_FRACTION = 1.0 # every tinted cluster is spill, whatever its size+SPILL_REFERENCE_MAX = 0.005 # the still's own key material ≤ the engine's small-cluster share → fullEDGE_MAX_PIXELS = 0 # any opaque pixel on the top/left/right edge band = contact@@ -115,19 +124,41 @@ def classify_edge_contact(raw: Image.Image, keyed: Image.Image, chroma_key: tuplreturn {"subject": subject, "residual": residual}+def decide_spill(reference: Path, key: str) -> dict[str, Any]:+ """`auto`: key the reference still with the same matte and measure its own+ key-coloured material. None worth the name → `full`; some → `small`."""+ from sprite_gen.frames.cutout import KEY_TARGETS, _corner_average, _detect_key_kind, extract_route+ from sprite_gen.frames.extract import key_material_pixels++ image = Image.open(reference).convert("RGBA")+ kind = _detect_key_kind(_corner_average(image)) if key == "auto" else key+ if kind not in ("green", "magenta"):+ return {"mode": "small", "reference": str(reference), "reason": f"key {kind!r} has no spill pass"}+ keyed, _ = extract_route(image, kind)+ material, subject = key_material_pixels(keyed, KEY_TARGETS[kind])+ share = material / subject if subject else 0.0+ mode = "full" if share <= SPILL_REFERENCE_MAX else "small"+ return {"mode": mode, "reference": str(reference), "key": kind, "key_material_px": material,+ "subject_px": subject, "key_material_share": round(share, 5), "share_max": SPILL_REFERENCE_MAX}++def key_frames(raw_files: list[Path],keyed_dir: Path,*,key: str = "auto",check_edges: bool = True,+ spill: str = "small",) -> dict[str, Any]:+ if spill not in ("small", "full"):+ raise SystemExit(f"video-frames: key_frames takes a resolved spill mode (small|full), got {spill!r}")+ spill_max = SPILL_FULL_FRACTION if spill == "full" else Nonekeyed_dir.mkdir(parents=True, exist_ok=True)rows: list[dict[str, Any]] = []contacts: list[dict[str, Any]] = []for src in raw_files:dst = keyed_dir / src.name- stats = cutout(src, dst, key=key)+ stats = cutout(src, dst, key=key, spill_max_fraction=spill_max)image = Image.open(dst).convert("RGBA")hist = image.getchannel("A").histogram()w, h = image.size@@ -180,7 +211,11 @@ def _edge_contact_message(contacts: list[dict[str, Any]]) -> str:return message-def run_frames(clip: Path, out_dir: Path, *, key: str, allow_edge_contact: bool, report_path: Path | None) -> dict[str, Any]:+def run_frames(clip: Path, out_dir: Path, *, key: str, allow_edge_contact: bool, report_path: Path | None, spill: str = "small", reference: Path | None = None) -> dict[str, Any]:+ if spill not in SPILL_MODES:+ raise SystemExit(f"video-frames: unknown --spill {spill!r}; expected one of {', '.join(SPILL_MODES)}")+ if spill == "auto" and reference is None:+ raise SystemExit("video-frames: --spill auto needs --reference (the still the clip was made from)")clip = clip.expanduser().resolve()if not clip.is_file():raise SystemExit(f"video-frames: clip not found: {clip}")@@ -188,9 +223,10 @@ def run_frames(clip: Path, out_dir: Path, *, key: str, allow_edge_contact: bool,meta = probe(clip)raw_dir = out_dir / "raw"keyed_dir = out_dir / "keyed"+ decision = decide_spill(Path(reference).expanduser().resolve(), key) if spill == "auto" else {"mode": spill, "reason": "explicit"}files = extract(clip, raw_dir)- report = key_frames(files, keyed_dir, key=key, check_edges=not allow_edge_contact)- payload = {"kind": "sprite-gen-video-frames-report", "clip": str(clip), "out_dir": str(out_dir), "raw_dir": str(raw_dir), "keyed_dir": str(keyed_dir), "key": key, **meta, **report}+ report = key_frames(files, keyed_dir, key=key, check_edges=not allow_edge_contact, spill=decision["mode"])+ payload = {"kind": "sprite-gen-video-frames-report", "clip": str(clip), "out_dir": str(out_dir), "raw_dir": str(raw_dir), "keyed_dir": str(keyed_dir), "key": key, "spill": decision, **meta, **report}target = (report_path or (out_dir / "frames.report.json")).expanduser().resolve()atomic_write_text(target, json.dumps(payload, ensure_ascii=False, indent=2) + "\n")payload["report"] = str(target)@@ -203,12 +239,15 @@ def add_arguments(parser: argparse.ArgumentParser) -> None:parser.add_argument("--key", choices=("auto", "green", "magenta", "white"), default="auto", help="background key (auto reads the corners)")parser.add_argument("--allow-edge-contact", action="store_true", help="accept frames whose subject touches the top/left/right edge")parser.add_argument("--report", type=Path, help="report JSON (default <out-dir>/frames.report.json)")+ parser.add_argument("--spill", choices=SPILL_MODES, default="small", help="small: correct only small key-tinted clusters (default); full: every key tint in the subject is spill; auto: decide from --reference")+ parser.add_argument("--reference", type=Path, help="the still the clip was made from (required by --spill auto)")def run(**kwargs: object) -> int:payload = run_frames(Path(str(kwargs["clip"])), Path(str(kwargs["out_dir"])), key=str(kwargs.get("key") or "auto"),- allow_edge_contact=bool(kwargs.get("allow_edge_contact")), report_path=kwargs.get("report")) # type: ignore[arg-type]- summary = {k: payload[k] for k in ("clip", "keyed_dir", "fps", "frames", "alpha_zero_pct_min", "alpha_zero_pct_max", "edge_contacts", "report")}+ allow_edge_contact=bool(kwargs.get("allow_edge_contact")), report_path=kwargs.get("report"), # type: ignore[arg-type]+ spill=str(kwargs.get("spill") or "small"), reference=kwargs.get("reference")) # type: ignore[arg-type]+ summary = {k: payload[k] for k in ("clip", "keyed_dir", "fps", "frames", "alpha_zero_pct_min", "alpha_zero_pct_max", "edge_contacts", "spill", "report")}print(json.dumps(summary, ensure_ascii=False, indent=2))return 0diff --git a/tests/video/test_gait_guard_anchor_wide.py b/tests/video/test_gait_guard_anchor_wide.pyindex ce8679f..b789792 100644--- a/tests/video/test_gait_guard_anchor_wide.py+++ b/tests/video/test_gait_guard_anchor_wide.py@@ -179,11 +179,12 @@ def test_video_set_passes_shape_and_anchor_through(tmp_path: Path, monkeypatch)Image.new("RGB", (32, 32), (0, 255, 0)).save(out)return {"shape": shape or "square", "canvas": [32, 32], "offset": [0, 0]}- def fake_frames(clip, out_dir, *, key, allow_edge_contact, report_path):+ def fake_frames(clip, out_dir, *, key, allow_edge_contact, report_path, spill, reference):+ seen["spill"] = (spill, Path(reference).name)keyed = Path(out_dir) / "keyed"keyed.mkdir(parents=True, exist_ok=True)_symmetric_walker(Path(out_dir), period=12, n=30)- return {"fps": 24.0, "frames": 30, "alpha_zero_pct_min": 0.0, "alpha_zero_pct_max": 0.0, "keyed_dir": str(keyed)}+ return {"fps": 24.0, "frames": 30, "alpha_zero_pct_min": 0.0, "alpha_zero_pct_max": 0.0, "keyed_dir": str(keyed), "spill": {"mode": "full"}}def fake_loop(frames_dir, out_dir, **kw):seen["anchor"] = kw.get("anchor")@@ -202,7 +203,8 @@ def test_video_set_passes_shape_and_anchor_through(tmp_path: Path, monkeypatch)Image.new("RGB", (32, 32), (0, 255, 0)).save(base)payload = batch_mod.run_set(bases={"side": base}, states=["cheer"], root=tmp_path / "set", character=None, duration=6, resolution="720p", key="green", concurrency=1, force=False, gap=0.0, video_runner=fake_video, shape="wide", anchor="feet")assert payload["ok"] == 1- assert seen == {"shape": "wide", "anchor": "feet"}+ # the frames step is told to judge spill from the item's own canvas still+ assert seen == {"shape": "wide", "anchor": "feet", "spill": ("auto", "canvas.png")}def test_cheer_motion_template_names_no_limbs() -> None:diff --git a/tests/video/test_video_spill.py b/tests/video/test_video_spill.pynew file mode 100644index 0000000..128c9d4--- /dev/null+++ b/tests/video/test_video_spill.py@@ -0,0 +1,91 @@+"""Synthetic regressions for key spill a video model paints into the subject.++A video model reflects the chroma key onto the subject — a green sheen across a+silver gauntlet — in patches far larger than the engine's trapped-spill cap, and+deeper than the fringe unmix reaches. `--spill full` treats every key tint as+spill; `auto` decides from the still the clip was made from.+"""+from __future__ import annotations++from pathlib import Path++import numpy as np+import pytest+from PIL import Image++from sprite_gen.video import frames as frames_mod++GREEN = (0, 255, 0)+SILVER = (205, 210, 215)+SHEEN = (150, 232, 160) # silver with the key reflected on it+LEAF = (40, 190, 60) # a subject that is green of its own+++def _frame(path: Path, *, patch: tuple[int, int, int] | None, size=(160, 160)) -> Path:+ """A silver block on the key; `patch` paints a large inner region (well past the+ fringe reach and far above the trapped-spill cluster cap)."""+ im = Image.new("RGB", size, GREEN)+ px = im.load()+ for y in range(30, 130):+ for x in range(40, 120):+ px[x, y] = SILVER+ if patch is not None:+ for y in range(50, 110):+ for x in range(55, 105):+ px[x, y] = patch+ im.save(path)+ return path+++def _green_excess(path: Path) -> int:+ a = np.asarray(Image.open(path).convert("RGBA")).astype(int)+ return int(((a[..., 3] > 0) & (a[..., 1] > np.maximum(a[..., 0], a[..., 2]) + 12)).sum())+++def test_small_keeps_a_large_reflection_and_full_removes_it(tmp_path: Path) -> None:+ raw = _frame(tmp_path / "raw.png", patch=SHEEN)+ small = frames_mod.key_frames([raw], tmp_path / "small", key="green", check_edges=False, spill="small")+ full = frames_mod.key_frames([raw], tmp_path / "full", key="green", check_edges=False, spill="full")+ assert small["frames"] == full["frames"] == 1+ kept = _green_excess(tmp_path / "small" / "raw.png")+ left = _green_excess(tmp_path / "full" / "raw.png")+ assert kept >= 2500 # the 50x60 sheen is a "large cluster" to the default pass+ assert left <= kept * 0.02+ # correction, not coverage: the reflected patch stays opaque+ a = np.asarray(Image.open(tmp_path / "full" / "raw.png").convert("RGBA"))+ assert (a[50:110, 55:105, 3] == 255).all()+++def test_full_does_not_touch_colours_without_key_tint(tmp_path: Path) -> None:+ raw = _frame(tmp_path / "raw.png", patch=(200, 60, 50)) # a red emblem+ frames_mod.key_frames([raw], tmp_path / "small", key="green", check_edges=False, spill="small")+ frames_mod.key_frames([raw], tmp_path / "full", key="green", check_edges=False, spill="full")+ a = np.asarray(Image.open(tmp_path / "small" / "raw.png"))+ b = np.asarray(Image.open(tmp_path / "full" / "raw.png"))+ assert (a == b).all()+++def test_auto_is_full_for_a_still_without_key_material(tmp_path: Path) -> None:+ still = _frame(tmp_path / "still.png", patch=None)+ decision = frames_mod.decide_spill(still, "auto")+ assert decision["mode"] == "full"+ assert decision["key"] == "green" and decision["key_material_px"] == 0+++def test_auto_is_small_for_a_still_that_is_green_of_its_own(tmp_path: Path) -> None:+ still = _frame(tmp_path / "still.png", patch=LEAF)+ decision = frames_mod.decide_spill(still, "auto")+ assert decision["mode"] == "small"+ assert decision["key_material_share"] > frames_mod.SPILL_REFERENCE_MAX+++def test_auto_without_a_reference_fails_loud(tmp_path: Path) -> None:+ with pytest.raises(SystemExit, match="--reference"):+ frames_mod.run_frames(tmp_path / "missing.mp4", tmp_path / "out", key="green", allow_edge_contact=True,+ report_path=None, spill="auto", reference=None)+++def test_key_frames_refuses_an_unresolved_mode(tmp_path: Path) -> None:+ raw = _frame(tmp_path / "raw.png", patch=None)+ with pytest.raises(SystemExit, match="resolved spill mode"):+ frames_mod.key_frames([raw], tmp_path / "k", key="green", check_edges=False, spill="auto")