Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.
fix: make facing observations record-only by default
Soohong Kim08151df82cc7
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a73fab4..db3090d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,12 +2,14 @@All notable public changes to `sprite-gen` are recorded here. Versions track the `version:` field in `SKILL.md` and `pyproject.toml`.-## v2.5.3 - Consistent reference and video facing--- Reference edits can opt into `gen --facing right|left` and `--facing-fix mirror|regen|none`. The default `preserve` leaves existing generation callers unchanged. Regeneration runs once, rechecks direction and mirrors a remaining opposite result.-- `video --direction side` and batch side inputs inspect the still before animation. Batch uses one shared check per side still and matches the corrected canvas with the motion prompt. Original inputs stay intact; cached canvases and prompts must match the requested facing.-- Direction reports include model-reported confidence and correction evidence. Failed or uncertain vision calls record `unknown` with a reason and continue without correction. Front-facing observations are unchanged; accessory handedness is not corrected.-- Synthetic tests cover direction parsing, exact mirrored pixels, regeneration rechecks, prompt/canvas agreement and existing callers.+## v2.5.3 - Reference and video facing controls++- Reference edits can opt into `gen --facing right|left` to request orientation in the generation prompt. The default `preserve` leaves existing generation callers unchanged.+- Facing inspection is **record-only by default**: `gen`, `video` and `video-set` use `--facing-fix none`. Explicit `mirror` corrects an observed opposite in the output copy; `gen --facing-fix regen` regenerates once, rechecks and mirrors a remaining observed opposite.+- `video --direction side` and batch side inputs inspect the still before animation. Batch uses one shared observation per side still; the requested facing drives canvas placement and motion prompts independently of the observation. Original inputs stay intact; cached canvases and prompts must match the requested policy.+- Direction reports include model, requested direction, model-reported confidence and correction evidence. `final_direction_source` distinguishes observations from values derived by mirroring; none is independent verification. Failed or uncertain calls record `unknown` with a reason and continue without correction.+- Known limitation: direction detectors can misclassify a correctly oriented still even at high confidence. Prompts request direction but cannot guarantee it; inspect the still before opting into correction. Front-facing observations are unchanged, and mirroring does not preserve accessory handedness.+- Synthetic regressions cover incorrect observations with byte-preserving defaults, explicit mirror pixel symmetry, regeneration rechecks, prompt/canvas agreement and existing callers.## v2.5.2 - Cleaner video spill correctiondiff --git a/README.ko.md b/README.ko.mdindex 4359a99..6a5d237 100644--- a/README.ko.md+++ b/README.ko.md@@ -26,7 +26,7 @@`sprite-gen` 은 그 간극을 메우는 Codex/Claude 스킬이자 Python CLI 다. **기본 이미지 한 장**을 주면 행 단위로 생성을 이끌고, 캐릭터의 아이덴티티를 고정하고, 크로마 배경을 벗겨 진짜 알파로 만들고, 각 포즈를 깨끗한 투명 프레임으로 추출한 뒤, **기계가 읽을 수 있는 `manifest.json.frame_layout`** 과 함께 런타임 아틀라스를 굽는다. 또는 같은 정지 이미지를 비디오 모델에 넘겨 모션 상태별로 이음매 없는 투명 루프를 받을 수도 있다. 생성이 끝내 해결하지 못하는 마지막 10% 를 위해, **큐레이션 웹뷰**가 굽기 전에 비교·거부·미세 조정하고 루프를 실시간으로 확인하게 해준다.-측면 스프라이트는 `video-set`이 기본으로 방향을 검사하고 반대 방향이면 사본을 좌우 반전해 캔버스와 클립 프롬프트의 `--facing right|left`를 맞춘다. 참고 이미지 편집부터 맞추려면 `gen --ref image.png --facing right --facing-fix mirror`를 쓴다. `gen`의 기본값은 방향 보존이다. [방향 옵션](SKILL.md#side-view-facing).+측면 스프라이트는 `video-set`의 `--facing right|left`를 캔버스 배치와 클립 프롬프트에 일관되게 사용한다. 방향 판정기는 **기본적으로 기록만 남기며**(`--facing-fix none`), 높은 신뢰도에서도 틀릴 수 있다. `gen --ref image.png --facing right`는 생성 문장으로 방향을 요구한다. `gen`의 방향 기본값은 보존이며, 문장만으로 결과를 보장할 수는 없다. 보정은 `--facing-fix mirror` 또는 `gen --facing-fix regen`을 명시해야 하므로 먼저 스틸을 확인한다. [방향 옵션](SKILL.md#side-view-facing).## 요청으로 시작하기diff --git a/README.md b/README.mdindex 4fc5a1a..6ad9c73 100644--- a/README.md+++ b/README.md@@ -26,7 +26,7 @@ Ask an image model for a "sprite sheet" and you know what you get: a character w`sprite-gen` is a Codex/Claude skill and a Python CLI that closes that gap. Give it **one base image** — it drives generation row by row, locks the character's identity, strips the chroma background to real alpha, extracts each pose as a clean transparent frame, and bakes a runtime atlas **with a machine-readable `manifest.json.frame_layout`**. Or hand the same still to a video model and get back a seamless, transparent loop per motion state. For the last 10% that generation never gets right, a **curation webview** lets you compare, reject, nudge and watch the loop live before you bake.-For side sprites, `video-set` checks and mirrors opposite-facing inputs by default, keeping `--facing right|left` consistent across canvas and clip prompts. Use `gen --ref image.png --facing right --facing-fix mirror` to normalize a reference edit; `gen` otherwise preserves orientation. See [facing options](SKILL.md#side-view-facing).+For side sprites, `video-set` uses `--facing right|left` consistently across canvas placement and clip prompts. Its direction detector is **record-only by default** (`--facing-fix none`) and can be wrong even at high confidence. Use `gen --ref image.png --facing right` to request orientation in the generation prompt; `gen` otherwise preserves orientation. Prompts request direction but cannot guarantee the result. Correction is opt-in: `--facing-fix mirror`, or `gen --facing-fix regen`; review the still before using either. See [facing options](SKILL.md#side-view-facing).## Start with a requestdiff --git a/SKILL.md b/SKILL.mdindex 5272155..f6fa234 100644--- a/SKILL.md+++ b/SKILL.md@@ -62,19 +62,23 @@ Pass choices already stated in the request. The guide checks access, combines ex## Side-view facingKeep the side still, canvas placement and motion prompt facing the same direction.-`video-set` checks each side input once before canvas placement, mirrors an opposite-facing copy,-and uses `--facing` for both the canvas and clip prompt. The source image stays intact.+`video-set` observes each side input once before canvas placement and uses the requested+`--facing` for both the canvas and clip prompt. Observation is record-only by default;+it never changes the requested direction. Image correction requires explicit opt-in.| Command option | Values and default | Behavior ||---|---|---|| `gen --facing` | `preserve` (default), `right`, `left` | With `--ref`, an explicit direction adds a prompt requirement and checks the generated still. |-| `gen --facing-fix` | `mirror` (default), `regen`, `none` | Mirror an opposite result, regenerate once and recheck, or record without correction. A still-opposite regeneration is mirrored. |+| `gen --facing-fix` | `none` (default), `mirror`, `regen` | Record without correction; opt into mirroring an observed opposite or regenerating once and rechecking. A still-opposite regeneration is mirrored. || `video --direction` | `side`, `front`, `back`; unset by default | `side` opts into facing inspection and a matching prompt requirement; front/back skip it. || `video --facing`, `video-set --facing` | `right` (default), `left` | Required side direction. |-| `video --facing-fix`, `video-set --facing-fix` | `mirror` (default), `none` | Correct an opposite side input or only record the observation. Batch side inspection is enabled by default. |+| `video --facing-fix`, `video-set --facing-fix` | `none` (default), `mirror` | Record the observation; opt into mirroring an observed opposite in a copy. Batch side inspection is enabled by default. |-Generation reports record direction, model-reported confidence and correction under `extra.facing`;-video reports and batch items use `facing`.+Direction is requested through the generation and motion prompts, which cannot guarantee model compliance.+The detector can be wrong even at high confidence: review the still before choosing `mirror` or `regen`.+Generation reports record direction, model, requested direction, model-reported confidence and correction+under `extra.facing`; video reports and batch items use `facing`. `final_direction` is an observation+or a value derived from it, not independent verification; `final_direction_source` identifies which.An uncertain or failed inspection records `unknown` and its reason and continues without correction;front-facing observations also remain unchanged. Mirroring does not preserve left/right accessory handedness.diff --git a/sprite_gen/gen/__init__.py b/sprite_gen/gen/__init__.pyindex a9eed92..7780b1a 100644--- a/sprite_gen/gen/__init__.py+++ b/sprite_gen/gen/__init__.py@@ -245,7 +245,7 @@ def generate_image(*,refs: list[Path] | None = None,facing: str | None = None,- facing_fix: str = "mirror",+ facing_fix: str = "none",model: str | None = None,aspect_ratio: str | None = None,quality: str | None = None,@@ -513,7 +513,7 @@ def add_arguments(parser: argparse.ArgumentParser) -> None:)parser.add_argument("--chroma-key", choices=sorted(chroma_mod.KEYS), default="magenta")parser.add_argument("--facing", choices=(*facing_mod.FACINGS, "preserve"), default="preserve", help="with --ref: required direction; preserve (default) leaves prompt and pixels unchanged")- parser.add_argument("--facing-fix", choices=facing_mod.FIXES, default="mirror", help="with --ref: correct an opposite-facing result by mirror (default), one regen, or none")+ parser.add_argument("--facing-fix", choices=facing_mod.FIXES, default="none", help="with --ref and --facing: record only (none, default), or opt into mirror / one regen")parser.add_argument("--trim-alpha", action="store_true", help="with --transparent: crop the published PNG to its opaque bbox so the bottom edge is the foot line (margins reported)")parser.add_argument("--white-check", type=Path, help="write a white-composite check image")parser.add_argument("--keep-session", action="store_true", help="codex: do not delete the rollout jsonl")diff --git a/sprite_gen/gen/facing.py b/sprite_gen/gen/facing.pyindex 51e9696..1a66041 100644--- a/sprite_gen/gen/facing.py+++ b/sprite_gen/gen/facing.py@@ -1,5 +1,5 @@# SPDX-License-Identifier: Apache-2.0-"""Reference-facing policy: observe, correct once, and recheck regeneration.+"""Reference-facing policy: observe by default; opt into correction and recheck.Confidence is the model's self-report, not a calibrated probability. A one-wordanswer has no confidence measurement and is recorded with confidence=None.@@ -37,7 +37,7 @@ INSPECTION_PROMPT = ()-def validate(facing: str, fix: str = "mirror") -> None:+def validate(facing: str, fix: str = "none") -> None:if facing not in FACINGS:raise SystemExit(f"facing: expected right or left, got {facing!r}")if fix not in FIXES:@@ -94,6 +94,7 @@ def inspect(backend, path: Path, workdir: Path) -> dict:# Provider bodies may echo a key or input. Report the failure class only.observation = {"direction": "unknown", "confidence": None,"reason": f"vision-call-failed:{type(exc).__name__}"}+ observation.setdefault("model", None)if observation["direction"] == "unknown":observation.setdefault("reason", "vision-uncertain")print(f"[gen] facing unknown: {observation['reason']}; no correction", file=sys.stderr)@@ -108,7 +109,7 @@ def prepare_correction(backend, request, run, workdir: Path, *, facing: str, fix"""observation = inspect(backend, request.raw, workdir)report = {**observation, "requested": facing, "fix": fix, "action": "none",- "final_direction": observation["direction"]}+ "final_direction": observation["direction"], "final_direction_source": "observation"}opposite = "left" if facing == "right" else "right"if observation["direction"] != opposite:report.setdefault("reason", "already-matched" if observation["direction"] == facing else "not-lateral")@@ -127,14 +128,13 @@ def prepare_correction(backend, request, run, workdir: Path, *, facing: str, fix# original generation, so existing consumers don't see a different shape.recheck = inspect(backend, regenerated, workdir)report.update(action="regen", final_direction=recheck["direction"],+ final_direction_source="regeneration-recheck",regeneration={"model": retry_run.model, "elapsed_seconds": retry_run.elapsed_seconds,"prompt": retry_request.prompt, "extra": retry_run.extra, "recheck": recheck})if recheck["direction"] == opposite:report.update(fallback="mirror", final_direction=facing,final_direction_source="mirror-of-recheck")- elif recheck["direction"] == facing:- report["final_direction_source"] = "regeneration-recheck"- else:+ elif recheck["direction"] != facing:report["reason"] = "regeneration-facing-unresolved:" + recheck.get("reason", "not-lateral")request = retry_requestrun = replace(run, elapsed_seconds=run.elapsed_seconds + retry_run.elapsed_seconds)diff --git a/sprite_gen/gen/facing_vision.py b/sprite_gen/gen/facing_vision.pyindex 9f95d25..7b6eed6 100644--- a/sprite_gen/gen/facing_vision.py+++ b/sprite_gen/gen/facing_vision.py@@ -15,7 +15,7 @@ from pathlib import Pathfrom .base import GEN_TIMEOUT_SECONDS, provider_binary, provider_subprocess_envfrom .facing import INSPECTION_PROMPT-OPENAI_MODEL = "gpt-4.1"+OPENAI_MODEL = "gpt-4.1-mini"GROK_MODEL = "grok-4.6"diff --git a/sprite_gen/gen/video.py b/sprite_gen/gen/video.pyindex a4ece15..94812da 100644--- a/sprite_gen/gen/video.py+++ b/sprite_gen/gen/video.py@@ -197,7 +197,7 @@ class VideoRequest:reference_images: list[Path] = field(default_factory=list)direction: str | None = Nonefacing: str = "right"- facing_fix: str = "mirror"+ facing_fix: str = "none"@propertydef mode(self) -> str:@@ -678,7 +678,7 @@ def _add_prompt_and_report(parser: argparse.ArgumentParser) -> None:def add_arguments(parser: argparse.ArgumentParser) -> None:parser.add_argument("--direction", choices=("side", "front", "back"), help="sprite view; side opts into facing inspection before video generation")parser.add_argument("--facing", choices=FACINGS, default="right", help="with --direction side: required direction (default right)")- parser.add_argument("--facing-fix", choices=facing_mod.FIXES, default="mirror", help="with --direction side: mirror an opposite-facing still, or none to only record")+ parser.add_argument("--facing-fix", choices=facing_mod.FIXES, default="none", help="with --direction side: record only (none, default), or opt into mirror")parser.add_argument("--image", type=Path, help="the still to animate / the first frame (PNG/JPEG/WebP)")parser.add_argument("--last-frame", type=Path, help=f"pin the closing frame ({DEFAULT_MODEL} only); alone or with --image")parser.add_argument(diff --git a/sprite_gen/video/batch.py b/sprite_gen/video/batch.pyindex 30c636c..bcde93c 100644--- a/sprite_gen/video/batch.py+++ b/sprite_gen/video/batch.py@@ -102,7 +102,7 @@ def run_item(anchor: str = "none",spill: str = "auto",facing: str = "right",- facing_fix: str = "mirror",+ facing_fix: str = "none",prepare_side: Callable[[Path], tuple[Path, dict]] | None = None,) -> dict[str, Any]:validate_facing(facing, facing_fix)@@ -222,7 +222,7 @@ def run_set(anchor: str = "none",spill: str = "auto",facing: str = "right",- facing_fix: str = "mirror",+ facing_fix: str = "none",) -> dict[str, Any]:validate_facing(facing, facing_fix)if facing_fix not in facing_mod.FIXES:@@ -276,7 +276,7 @@ def _parse_bases(values: list[str]) -> dict[str, Path]:def add_arguments(parser: argparse.ArgumentParser) -> None:parser.add_argument("--base", action="append", default=[], help="direction=still.png (repeatable: side=..., front=..., back=...)")parser.add_argument("--facing", choices=FACINGS, default="right", help="side-view facing for both prompt and canvas (default right); ignored for front/back")- parser.add_argument("--facing-fix", choices=facing_mod.FIXES, default="mirror", help="side inputs: mirror an opposite-facing still (default) or only record the observation")+ parser.add_argument("--facing-fix", choices=facing_mod.FIXES, default="none", help="side inputs: record only (none, default), or opt into mirror")parser.add_argument("--states", default="idle,walk,run,jump,attack", help="comma list of motion states")parser.add_argument("--out-dir", required=True, type=Path, help="batch root; one folder per direction-state")parser.add_argument("--character", help="short subject phrase used in the prompts (e.g. 'The armored knight')")@@ -298,7 +298,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 DEFAULT_DURATION_SECONDS), 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),- facing=str(kwargs.get("facing") or "right"), facing_fix=str(kwargs.get("facing_fix") or "mirror"),+ facing=str(kwargs.get("facing") or "right"), facing_fix=str(kwargs.get("facing_fix") 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/facing.py b/sprite_gen/video/facing.pyindex 731b82a..e383876 100644--- a/sprite_gen/video/facing.py+++ b/sprite_gen/video/facing.py@@ -1,5 +1,5 @@# SPDX-License-Identifier: Apache-2.0-"""Normalize a side-view video input before canvas placement; never edit its source."""+"""Observe a side-view input; correction requires opt-in and never edits its source."""from __future__ import annotationsimport hashlib@@ -27,9 +27,9 @@ class _Vision:return vision.grok_inspect(path, credential=self.credential, call=self.call)-def prepare_still(source: Path, out: Path, *, facing: str = "right", fix: str = "mirror",+def prepare_still(source: Path, out: Path, *, facing: str = "right", fix: str = "none",credential: Credential | None = None, call: HttpCall | None = None) -> dict:- """Inspect exactly once on the video provider; publish a corrected PNG copy."""+ """Inspect once on the video provider; copy unchanged unless correction is opted in."""policy.validate(facing, fix)if fix not in FIXES:raise SystemExit("video facing: expected mirror or none")@@ -40,7 +40,7 @@ def prepare_still(source: Path, out: Path, *, facing: str = "right", fix: str =observed = policy.inspect(_Vision(credential, call), out, out.parent)report = {**observed, "requested": facing, "fix": fix, "action": "none","source": str(source), "source_sha256": digest(source), "out": str(out),- "final_direction": observed["direction"]}+ "final_direction": observed["direction"], "final_direction_source": "observation"}opposite = "left" if facing == "right" else "right"if observed["direction"] == opposite and fix == "mirror":policy.mirror(out)diff --git a/tests/gen/test_facing.py b/tests/gen/test_facing.pyindex 2afebea..72650b6 100644--- a/tests/gen/test_facing.py+++ b/tests/gen/test_facing.py@@ -19,14 +19,15 @@ class Backend:name = "openai"transparency = "native"- def __init__(self, direction="left", failure=None, regenerated_direction="right"):+ def __init__(self, direction="left", failure=None, regenerated_direction="right", image_direction=None):+ self.image_direction = image_direction or directionself.regenerated_direction = regenerated_directionself.direction, self.failure = direction, failureself.generations, self.inspections = [], []def generate(self, request, workdir):self.generations.append(request)- source = self.regenerated_direction if len(self.generations) > 1 else self.direction+ source = self.regenerated_direction if len(self.generations) > 1 else self.image_directionif source == "unknown":source = "front"shutil.copyfile(FIXTURES / f"{source}.png", request.raw)@@ -37,7 +38,7 @@ class Backend:if self.failure:raise self.failuredirection = self.regenerated_direction if len(self.generations) > 1 else self.direction- return json.dumps({"direction": direction, "confidence": 0.95}), {"usage": {"input_tokens": 4}}+ return json.dumps({"direction": direction, "confidence": 0.95}), {"model": "test-vision", "usage": {"input_tokens": 4}}def generate(tmp_path, monkeypatch, backend, **kwargs):@@ -49,7 +50,7 @@ def generate(tmp_path, monkeypatch, backend, **kwargs):@pytest.mark.parametrize("direction", ["left", "right", "front"])def test_three_fixture_directions_only_opposite_is_mirrored(tmp_path, monkeypatch, direction):backend = Backend(direction)- result = generate(tmp_path, monkeypatch, backend)+ result = generate(tmp_path, monkeypatch, backend, facing_fix="mirror")original = Image.open(FIXTURES / f"{direction}.png")expected = ImageOps.mirror(original) if direction == "left" else originalassert Image.open(result.out).tobytes() == expected.tobytes()@@ -62,7 +63,7 @@ def test_three_fixture_directions_only_opposite_is_mirrored(tmp_path, monkeypatcdef test_left_request_mirrors_right_and_preserves_alpha_and_preview(tmp_path, monkeypatch):- result = generate(tmp_path, monkeypatch, Backend("right"), facing="left",+ result = generate(tmp_path, monkeypatch, Backend("right"), facing="left", facing_fix="mirror",transparent=True, alpha_mode="native", white_check=tmp_path / "white.png")original = Image.open(FIXTURES / "right.png")assert Image.open(result.out).tobytes() == ImageOps.mirror(original).tobytes()@@ -72,10 +73,19 @@ def test_left_request_mirrors_right_and_preserves_alpha_and_preview(tmp_path, moassert result.extra["facing"]["final_direction"] == "left"-def test_none_is_byte_identical_and_records_mismatch(tmp_path, monkeypatch):- result = generate(tmp_path, monkeypatch, Backend(), facing_fix="none")- assert result.out.read_bytes() == (FIXTURES / "left.png").read_bytes()- assert result.extra["facing"]["reason"] == "correction-disabled"[email protected]("options", [{}, {"facing_fix": "none"}])+def test_default_and_none_preserve_bytes_despite_wrong_observation(tmp_path, monkeypatch, options):+ backend = Backend("left", image_direction="right")+ result = generate(tmp_path, monkeypatch, backend, **options)+ assert result.out.read_bytes() == result.raw.read_bytes() == (FIXTURES / "right.png").read_bytes()+ report = result.extra["facing"]+ assert report["fix"] == "none" and report["action"] == "none"+ assert report["reason"] == "correction-disabled"+ assert report["direction"] == report["final_direction"] == "left"+ assert report["final_direction_source"] == "observation"+ assert report["requested"] == "right" and report["model"] == "test-vision"+ assert len(backend.generations) == len(backend.inspections) == 1+ assert "facing right" in result.prompt@pytest.mark.parametrize("failure", [RuntimeError("private"), SystemExit("private")])@@ -106,6 +116,7 @@ def test_regen_rechecks_once_and_mirrors_only_a_known_opposite(tmp_path, monkeypassert report["regeneration"]["recheck"]["usage"] == {"input_tokens": 4}assert report.get("fallback") == ("mirror" if rechecked == "left" else None)assert report["final_direction"] == ("right" if rechecked in ("left", "right") else rechecked)+ assert report["final_direction_source"] == ("mirror-of-recheck" if rechecked == "left" else "regeneration-recheck")if rechecked in ("unknown", "front"):assert report["reason"].startswith("regeneration-facing-unresolved:")@@ -220,15 +231,18 @@ def test_codex_vision_reads_new_answer_and_scrubs_identity(monkeypatch, tmp_pathassert not list(tmp_path.iterdir())-def test_cli_options_reach_report(tmp_path, monkeypatch):[email protected]("options", [[], ["--facing-fix", "none"]])+def test_cli_options_reach_report(tmp_path, monkeypatch, options):backend = Backend("right")monkeypatch.setattr(gen, "_make_provider", lambda *a, **kw: backend)report = tmp_path / "report.json"assert gen.main(["--provider", "openai", "--prompt", "robot", "--ref", str(FIXTURES / "right.png"),"--out", str(tmp_path / "out.png"), "--report", str(report),- "--facing", "left", "--facing-fix", "none"]) == 0+ "--facing", "left", *options]) == 0facing_report = json.loads(report.read_text())["extra"]["facing"]assert facing_report["requested"] == "left" and facing_report["action"] == "none"+ assert facing_report["fix"] == "none"+ assert (tmp_path / "out.png").read_bytes() == (FIXTURES / "right.png").read_bytes()def test_regeneration_recheck_failure_preserves_regenerated_image(tmp_path, monkeypatch):diff --git a/tests/gen/test_video_facing.py b/tests/gen/test_video_facing.pyindex 7274dd0..3a9344e 100644--- a/tests/gen/test_video_facing.py+++ b/tests/gen/test_video_facing.py@@ -84,13 +84,31 @@ def test_side_multi_input_refused_before_vision_or_video(tmp_path):assert not api.calls-def test_video_cli_passes_side_policy(tmp_path, monkeypatch):[email protected]("options", [[], ["--facing-fix", "none"]])+def test_video_cli_passes_side_policy(tmp_path, monkeypatch, options):api = Api()monkeypatch.setattr(video, "resolve_credential", lambda: video.Credential("synthetic", "grok-login"))monkeypatch.setattr(video, "http_json", api.call)monkeypatch.setattr(video, "http_download", lambda *a: MP4)report = tmp_path / "report.json"assert video.main(["--image", str(FIXTURE), "--prompt", "idle", "--out", str(tmp_path / "out.mp4"),- "--direction", "side", "--facing", "left", "--facing-fix", "none", "--report", str(report)]) == 0+ "--direction", "side", "--facing", "right", *options, "--report", str(report)]) == 0data = json.loads(report.read_text())- assert data["facing"]["requested"] == "left" and "facing left" in data["prompt"]+ assert data["facing"]["requested"] == "right" and "facing right" in data["prompt"]+ assert data["facing"]["fix"] == "none" and data["facing"]["action"] == "none"+ uploaded = base64.b64decode(api.calls[1][3]["image"]["url"].split(",", 1)[1])+ assert uploaded == FIXTURE.read_bytes()+++def test_default_video_preserves_bytes_despite_wrong_observation(tmp_path):+ source = FIXTURE.with_name("right.png")+ api = Api("left")+ result = video.generate_video(video.VideoRequest(source, "idle", tmp_path / "out.mp4", direction="side"),+ credential=video.Credential("synthetic", "grok-login"), call=api.call, download=lambda *a: MP4)+ assert result.image.read_bytes() == source.read_bytes()+ uploaded = base64.b64decode(api.calls[1][3]["image"]["url"].split(",", 1)[1])+ assert uploaded == source.read_bytes()+ assert result.facing["fix"] == "none" and result.facing["action"] == "none"+ assert result.facing["final_direction"] == "left"+ assert result.facing["final_direction_source"] == "observation"+ assert result.facing["requested"] == "right" and "facing right" in result.promptdiff --git a/tests/video/test_batch_facing.py b/tests/video/test_batch_facing.pyindex 44e5371..b6bb3d5 100644--- a/tests/video/test_batch_facing.py+++ b/tests/video/test_batch_facing.py@@ -23,9 +23,10 @@ def offline(monkeypatch):monkeypatch.setattr(batch, "_staggered_start", lambda gap: None)[email protected]("options", [{}, {"facing_fix": "mirror"}])@pytest.mark.parametrize("facing", ["left", "right"])@pytest.mark.parametrize("direction", ["side", "front", "back"])-def test_set_facing_reaches_both_real_canvas_and_prompt(tmp_path, offline, facing, direction):+def test_set_facing_reaches_both_real_canvas_and_prompt(tmp_path, offline, facing, direction, options):prompts = []source_bytes = FIXTURE.read_bytes()def video(image, prompt, out, report, **kw):@@ -35,13 +36,16 @@ def test_set_facing_reaches_both_real_canvas_and_prompt(tmp_path, offline, facinreturn 0result = batch.run_set(bases={direction: FIXTURE}, states=["attack"], root=tmp_path,character=None, duration=3, resolution="720p", key="green",- concurrency=1, force=False, gap=0, facing=facing, video_runner=video)+ concurrency=1, force=False, gap=0, facing=facing, video_runner=video, **options)assert result["ok"] == 1 and result["facing"] == facingassert FIXTURE.read_bytes() == source_bytescanvas = json.loads((tmp_path / f"{direction}-attack" / "canvas.report.json").read_text())if direction == "side":assert f"facing {facing}" in prompts[0]- assert result["items"][0]["facing"]["action"] == ("mirror" if facing == "right" else "none")+ assert result["items"][0]["facing"]["action"] == ("mirror" if facing == "right" and options else "none")+ if not options:+ assert (tmp_path / "side.facing.png").read_bytes() == source_bytes+ assert result["items"][0]["facing"]["final_direction_source"] == "observation"assert (canvas["offset"][0] > 0) == (facing == "left")else:assert "facing" not in result["items"][0]@@ -71,7 +75,7 @@ def test_changed_facing_cannot_reuse_an_opposite_prompt_clip(tmp_path, offline,assert (item / "canvas.png").read_bytes() == previous_canvasresult = batch.run_item(**options)assert result["ok"] and result["clip"]["reused"] and len(calls) == 1- result = batch.run_item(**options, facing_fix="none")+ result = batch.run_item(**options, facing_fix="mirror")assert not result["ok"] and "--force" in result["error"]@@ -83,7 +87,7 @@ def test_cli_threads_facing_into_set(monkeypatch, tmp_path):monkeypatch.setattr(batch, "run_set", run_set)assert batch.main(["--base", f"side={FIXTURE}", "--states", "attack", "--out-dir", str(tmp_path),"--facing", "left"]) == 0- assert seen[0]["facing"] == "left"+ assert seen[0]["facing"] == "left" and seen[0]["facing_fix"] == "none"def test_parallel_states_share_one_inspection_of_the_side_still(tmp_path, offline, monkeypatch):@@ -96,8 +100,23 @@ def test_parallel_states_share_one_inspection_of_the_side_still(tmp_path, offlinout.write_bytes(b"test-video")report.write_text(json.dumps({"prompt": prompt}))return 0- result = batch.run_set(bases={"side": FIXTURE}, states=["idle", "attack", "walk"], root=tmp_path,+ source = FIXTURE.with_name("right.png")+ result = batch.run_set(bases={"side": source}, states=["idle", "attack", "walk"], root=tmp_path,character=None, duration=3, resolution="720p", key="green",concurrency=3, force=False, gap=0, video_runner=video)assert result["ok"] == 3 and len(calls) == 1assert len({item["facing"]["out"] for item in result["items"]}) == 1+ assert (tmp_path / "side.facing.png").read_bytes() == source.read_bytes()+ assert all(item["facing"]["action"] == "none" and item["facing"]["requested"] == "right"+ for item in result["items"])+ assert result["facing_fix"] == "none"+++def test_tool_defaults_to_record_only(monkeypatch, tmp_path):+ seen = []+ def run_set(**kwargs):+ seen.append(kwargs)+ return {"failed": []}+ monkeypatch.setattr(batch, "run_set", run_set)+ assert batch.run(base=[f"side={FIXTURE}"], out_dir=tmp_path) == 0+ assert seen[0]["facing_fix"] == "none"