Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.
gen-set: every state row of a prepared run, N at a time, as a command
Soohong Kimca20efb99d44
diff --git a/SKILL.md b/SKILL.mdindex 2fa5729..2bd6f5a 100644--- a/SKILL.md+++ b/SKILL.md@@ -16,6 +16,7 @@ depends_on:required_scripts:- scripts/prepare_sprite_run.py- scripts/generate_sprite_image.py+ - scripts/gen_set.py- scripts/generate_sprite_video.py- scripts/video_canvas.py- scripts/video_frames.py@@ -111,6 +112,7 @@ One job each, all under `scripts/` (wrappers) ↔ `sprite_gen/<domain>/` (impl).|---|---|---|| `prepare_sprite_run.py` | request → `sprite-request.json`, layout guides, prompts, empty `raw/`+`frames/` | run-contract §2 || `generate_sprite_image.py` (`gen`) | one still via codex `image_gen` / grok Imagine → verified PNG (+ transparent strategy) | [`docs/gen.md`](docs/gen.md) |+| `gen_set.py` (`gen-set`) | every state row of a prepared run, N at a time — identity ref from the run (base or accepted anchor), one report per row, `table.md`, non-zero exit on any failure | [`docs/gen.md`](docs/gen.md) || `generate_sprite_video.py` (`video`) | one still → verified mp4 via Grok Imagine, user's own login / `XAI_API_KEY` | [`docs/video.md`](docs/video.md) || `video_canvas.py` · `video_frames.py` · `video_loop.py` · `video_set.py` | state canvas (jump tall / attack wide / else square) · ffmpeg + keying · true-period cycle → strip/GIF/WebP · directions × states batch | [`docs/video-pipeline.md`](docs/video-pipeline.md) || `extract_sprite_row_frames.py` (`extract`) | `raw/<state>.png` → chroma removal → components → transparent cells + `frames/frames-manifest.json` | run-contract · [`docs/pixel-unfake.md`](docs/pixel-unfake.md) |@@ -143,7 +145,7 @@ $SPRITE_GEN_ROOT/.venv/bin/python $SPRITE_GEN_ROOT/scripts/prepare_sprite_run.pyHatch-pet-style locomotion adds the cell gate (`--cell-width 192 --cell-height 208`). Directional characters declare the direction contract (`--directions down,side,up --mirror left=side`); files then follow the taxonomy `raw/<dir>/<pose>.png`, `frames/<dir>/<pose>/` (path resolver SSoT `sprite_gen/layout.py`, frame paths SSoT = frames-manifest `row.files`) and `prepare` records the generation chain in `references/generation-plan.json` — [`docs/directional-anchor-workflow.md`](docs/directional-anchor-workflow.md). Writes `sprite-request.json`, `base-source.<ext>`, `references/layout-guides/<state>.png`, `prompts/<state>.txt`, `raw/`, `frames/`.-2. Generate one row per state (the one AI step; the `image-gen` skill is a thin shuttle over this):+2. Generate the rows (the one AI step; the `image-gen` skill is a thin shuttle over this). The batch form is the default — `$SPRITE_GEN_ROOT/.venv/bin/sprite-gen gen-set --run-dir <run>` generates every non-mirrored state 4 at a time with the run's own identity ref and writes `reports/gen-set/table.md`; one row by hand:```bash$SPRITE_GEN_ROOT/.venv/bin/python $SPRITE_GEN_ROOT/scripts/generate_sprite_image.py \@@ -153,7 +155,7 @@ $SPRITE_GEN_ROOT/.venv/bin/python $SPRITE_GEN_ROOT/scripts/generate_sprite_image- `--provider` is optional: default codex (`SPRITE_GEN_DEFAULT_PROVIDER` overrides; observable grok fallback only if codex is unavailable). Rows keep the request chroma key and are generated **without** `--transparent`; standalone stills use `--transparent` (codex native alpha first, grok chroma) — [`docs/gen.md`](docs/gen.md).- References: default states attach exactly two — `base-source.<ext>` + the state layout guide. Direction-anchor mode attaches the accepted anchor instead of the base: **never pick the anchor crop by hand**, ask `$SPRITE_GEN_ROOT/.venv/bin/python -m sprite_gen.cli anchor --run-dir <run> --for-state <state>` right before each generation (derived cache, re-run every time; the human pins which frame). Extra motion references only when recorded in `qa-notes.md`.-- **Concurrency (maintainer 2026-07-19)**: multi-row batches run **4 at a time** (`ThreadPoolExecutor(max_workers=4)`); serial one-by-one is an anti-pattern. `runio.py` locks make parallel `raw/<state>.png` writes safe. Providers are engine backends, not agents — no worker surface is spawned ([`docs/gen.md`](docs/gen.md#provider-topology)).+- **Concurrency (maintainer 2026-07-19)**: multi-row batches run **4 at a time** — that is `gen-set`'s default `--concurrency`; serial one-by-one is an anti-pattern. `runio.py` locks make parallel `raw/<state>.png` writes safe. Providers are engine backends, not agents — no worker surface is spawned ([`docs/gen.md`](docs/gen.md#provider-topology)).3. Extract frames — chroma removal, connected components, one transparent request-sized cell per pose, `frames/<state>/frame-N.png` + `frames/frames-manifest.json`:diff --git a/docs/gen.md b/docs/gen.mdindex 0c6bef0..cf0b18a 100644--- a/docs/gen.md+++ b/docs/gen.md@@ -162,8 +162,20 @@ exactly that, rather than falling back on its own.## Sprite-row usage-In the component-row pipeline (SKILL.md §2) generate each state row with-`--provider codex` (or `grok`) using `prompts/<state>.txt`, writing `raw/<state>.png`.+In the atlas pipeline (SKILL.md §2) the rows of a prepared run are generated by+`sprite-gen gen-set --run-dir <run>`: every non-mirrored state, `--concurrency` 4 at a+time, each row with the identity ref the run declares (`base-source.*`, or the accepted+direction anchor for a direction-contract action row — `sprite_gen.curate.anchor` owns+that choice) plus its layout guide, into `raw/<state>.png`. Each row gets+`reports/gen-set/<state>.json`, the batch writes `reports/gen-set/table.md` and+`set.report.json`, existing rows are reused unless `--force`, a direction run generates+its anchors before its rows and stops when an anchor failed, and the exit code is+non-zero when any row failed. `--provider` is honoured verbatim; unspecified, it+resolves exactly as `gen` does (above), and any codex→grok availability failover is+recorded per row.++One row by hand is the same call `gen-set` makes: `--provider codex` (or `grok`) with+`prompts/<state>.txt`, writing `raw/<state>.png`.The row prompts still carry the request chroma key on the background and frameextraction removes it downstream — rows are generated **without** `--transparent`, sothe native strategy does not apply to them yet (moving rows to native alpha is adiff --git a/scripts/gen_set.py b/scripts/gen_set.pynew file mode 100644index 0000000..ae980b9--- /dev/null+++ b/scripts/gen_set.py@@ -0,0 +1,15 @@+# SPDX-License-Identifier: Apache-2.0+"""Backward-compatible wrapper for sprite_gen.gen.gen_set (`sprite-gen gen-set`)."""++import sys+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++import sprite_gen.gen.gen_set as _impl++globals().update({name: value for name, value in vars(_impl).items() if name not in {"__name__", "__package__", "__loader__", "__spec__"}})+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/sprite_gen/_modules.py b/sprite_gen/_modules.pyindex a8bed60..b35792f 100644--- a/sprite_gen/_modules.py+++ b/sprite_gen/_modules.py@@ -12,6 +12,7 @@ MODULE_DOMAIN = {'migrate_breathe': 'spec','generate_image': 'gen','video': 'gen',+ 'gen_set': 'gen','canvas': 'video','frames': 'video','loop': 'video',diff --git a/sprite_gen/cli.py b/sprite_gen/cli.pyindex f3cd8d4..039bdfc 100644--- a/sprite_gen/cli.py+++ b/sprite_gen/cli.py@@ -12,7 +12,7 @@ from sprite_gen.curate import anchorfrom sprite_gen.compose import compose_atlas, compose_cycle, compose_gif, compose_layers, export_aseprite, export_pngsfrom sprite_gen.qa import correction_loop, inspect, preview, scorefrom sprite_gen.frames import cutout, extract, slice_sheet, unpack_atlas-from sprite_gen.gen import prepare, video+from sprite_gen.gen import gen_set, prepare, videofrom sprite_gen.video import batch as video_batchfrom sprite_gen.video import canvas as video_canvasfrom sprite_gen.video import frames as video_frames@@ -293,6 +293,11 @@ COMMANDS: dict[str, tuple[str, Callable[[argparse.ArgumentParser], None], Callab_add_cutout,cutout.run,),+ "gen-set": (+ "Generate every state row of a prepared run, N at a time — one report per row, table.md, non-zero exit on any failure.",+ gen_set.add_arguments,+ gen_set.run,+ ),"video": ("Animate one still into a verified mp4 via Grok Imagine (your own grok login or XAI_API_KEY).",_add_video,diff --git a/sprite_gen/gen/gen_set.py b/sprite_gen/gen/gen_set.pynew file mode 100644index 0000000..13b0df6--- /dev/null+++ b/sprite_gen/gen/gen_set.py@@ -0,0 +1,226 @@+# SPDX-License-Identifier: Apache-2.0+"""`sprite-gen gen-set` — generate every state row of a prepared run, N at a time.++The atlas pipeline's one AI step, as a command instead of prose. `prepare` already+wrote the numeric request, one prompt per state and one layout guide per state; this+runs `gen` for each state with the identity ref the run declares (`base-source.*`, or+the accepted direction anchor for a direction-contract action row — `sprite_gen.curate.anchor`+owns that choice) and writes `raw/<state>.png` where `extract` expects it.++Same contract as `video-set`: items are idempotent (an existing row is reused unless+`--force`), every item gets its own report, `table.md` names failures by stage, and the+exit code is non-zero when any item failed. There is no fallback provider: `--provider`+is honoured verbatim and the unspecified case resolves exactly like `gen` does+(`SPRITE_GEN_DEFAULT_PROVIDER` > codex, with the same observable codex→grok+availability failover recorded per item).++Direction-contract runs follow the run's own `references/generation-plan.json`: stage 1+(direction anchors, base-referenced) must be generated, extracted and an anchor frame+accepted before stage 2 rows can attach it, so a stage-2 row whose anchor is not+resolvable fails by name instead of quietly re-attaching the base.+"""++from __future__ import annotations++import argparse+import json+import sys+import time+from concurrent.futures import ThreadPoolExecutor, as_completed+from pathlib import Path+from typing import Any, Callable++from sprite_gen import gen as gen_mod+from sprite_gen.curate import anchor as anchor_mod+from sprite_gen.spec import layout+from sprite_gen.spec.runio import atomic_write_text++DEFAULT_CONCURRENCY = 4 # maintainer 2026-07-19: multi-row batches run 4 at a time; serial is the anti-pattern+REPORT_DIR = "reports" # <run>/reports/gen-set/<state>.json — outside raw/ and frames/, the run contract's derived areas+++def _row_states(request: dict[str, Any], wanted: list[str] | None) -> list[str]:+ """States to generate, in generation-plan order (anchors before rows), minus mirrored directions."""+ states = list(request.get("states") or {})+ if not states:+ raise SystemExit("gen-set: the request declares no states")+ directions = request.get("directions")+ mirrored = set((directions or {}).get("mirror") or {})+ ordered: list[str] = []+ if directions:+ anchors = [anchor_mod.anchor_state(request, d) for d in anchor_mod.directions(request)]+ ordered = [s for s in anchors if s in states] + [s for s in states if s not in anchors]+ else:+ ordered = states+ ordered = [s for s in ordered if not any(s.startswith(m + "_") for m in mirrored)]+ if wanted:+ unknown = [s for s in wanted if s not in states]+ if unknown:+ raise SystemExit(f"gen-set: state(s) not in the request: {', '.join(unknown)} (have: {', '.join(states)})")+ ordered = [s for s in ordered if s in wanted]+ return ordered+++def _stages(request: dict[str, Any], states: list[str]) -> list[list[str]]:+ """Direction runs: anchors first (parallel), then rows. Flat runs: one stage."""+ directions = request.get("directions")+ if not directions:+ return [states]+ anchors = {anchor_mod.anchor_state(request, d) for d in anchor_mod.directions(request)}+ first = [s for s in states if s in anchors]+ second = [s for s in states if s not in anchors]+ return [stage for stage in (first, second) if stage]+++def run_gen_cli(prompt_file: Path, out: Path, refs: list[Path], report: Path, *, provider: str | None, model: str | None, log: Path) -> int:+ import subprocess++ cmd = [sys.executable, "-m", "sprite_gen.gen", "--prompt-file", str(prompt_file), "--out", str(out), "--report", str(report)]+ for ref in refs:+ cmd += ["--ref", str(ref)]+ if provider:+ cmd += ["--provider", provider]+ if model:+ cmd += ["--model", model]+ with log.open("w", encoding="utf-8") as fh:+ return subprocess.run(cmd, stdout=fh, stderr=subprocess.STDOUT, text=True).returncode+++def run_item(+ *,+ run_dir: Path,+ request: dict[str, Any],+ state: str,+ provider: str | None,+ model: str | None,+ force: bool,+ gen_runner: Callable[..., int] | None = None,+) -> dict[str, Any]:+ gen_runner = gen_runner or run_gen_cli # late-bound so a test can stand in for the provider call+ out = run_dir / layout.raw_rel(request, state)+ prompt_file = run_dir / layout.prompt_rel(request, state)+ guide = run_dir / layout.guide_rel(request, state)+ report_dir = run_dir / REPORT_DIR / "gen-set"+ report_dir.mkdir(parents=True, exist_ok=True)+ report = report_dir / f"{state.replace('/', '_')}.json"+ log = report_dir / f"{state.replace('/', '_')}.log"+ result: dict[str, Any] = {"state": state, "out": str(out), "report": str(report)}+ started = time.monotonic()+ try:+ if not prompt_file.is_file():+ raise SystemExit(f"prompt missing: {prompt_file} — run `sprite-gen prepare` first")+ if not guide.is_file():+ raise SystemExit(f"layout guide missing: {guide} — run `sprite-gen prepare` first")+ if out.is_file() and report.is_file() and not force:+ result["reused"] = True+ result["ok"] = True+ return result+ identity = anchor_mod.identity_ref(run_dir, state, request, quiet=True)+ refs = [identity, guide]+ result["refs"] = [str(r) for r in refs]+ out.parent.mkdir(parents=True, exist_ok=True)+ rc = gen_runner(prompt_file, out, refs, report, provider=provider, model=model, log=log)+ if rc != 0 or not out.is_file():+ tail = log.read_text(encoding="utf-8", errors="replace").strip().splitlines()[-3:] if log.exists() else []+ raise SystemExit(f"gen exited {rc}; " + (" | ".join(tail) if tail else f"see {log}"))+ gen_report = json.loads(report.read_text(encoding="utf-8")) if report.is_file() else {}+ result["provider"] = gen_report.get("provider")+ result["provider_resolved_from"] = gen_report.get("provider_resolved_from")+ if gen_report.get("provider_fallback"):+ result["provider_fallback"] = gen_report["provider_fallback"]+ result["elapsed_seconds"] = round(time.monotonic() - started, 1)+ result["ok"] = True+ except SystemExit as exc:+ result["ok"] = False+ result["error"] = str(exc)+ result["elapsed_seconds"] = round(time.monotonic() - started, 1)+ return result+++def write_table(results: list[dict[str, Any]], path: Path) -> str:+ lines = ["| state | provider | resolved from | seconds | status |", "|---|---|---|---|---|"]+ for r in results:+ if r.get("ok") and r.get("reused"):+ lines.append(f"| {r['state']} | - | - | - | reused |")+ elif r.get("ok"):+ lines.append(f"| {r['state']} | {r.get('provider') or '-'} | {r.get('provider_resolved_from') or '-'} | {r.get('elapsed_seconds', '-')} | OK |")+ else:+ lines.append(f"| {r['state']} | - | - | {r.get('elapsed_seconds', '-')} | FAIL: {r.get('error', '')[:100]} |")+ text = "\n".join(lines) + "\n"+ atomic_write_text(path, text)+ return text+++def run_set(+ *,+ run_dir: Path,+ states: list[str] | None,+ provider: str | None,+ model: str | None,+ concurrency: int,+ force: bool,+ gen_runner: Callable[..., int] | None = None,+) -> dict[str, Any]:+ gen_runner = gen_runner or run_gen_cli+ run_dir = run_dir.expanduser().resolve()+ if not (run_dir / "sprite-request.json").is_file():+ raise SystemExit(f"gen-set: {run_dir} is not a prepared run (no sprite-request.json) — run `sprite-gen prepare` first")+ request = anchor_mod.load_request(run_dir)+ ordered = _row_states(request, states)+ results: list[dict[str, Any]] = []+ for stage in _stages(request, ordered):+ with ThreadPoolExecutor(max_workers=max(1, concurrency)) as ex:+ futures = {ex.submit(run_item, run_dir=run_dir, request=request, state=s, provider=provider, model=model, force=force, gen_runner=gen_runner): s for s in stage}+ for fut in as_completed(futures):+ r = fut.result()+ results.append(r)+ print(json.dumps({k: r[k] for k in ("state", "ok") if k in r} | ({"error": r["error"]} if not r.get("ok") else {}), ensure_ascii=False), flush=True)+ if any(not r.get("ok") for r in results if r["state"] in stage) and len(_stages(request, ordered)) > 1:+ # a failed anchor stage cannot feed stage 2 — stop here and say so, do not attach the base instead+ break+ results.sort(key=lambda r: ordered.index(r["state"]))+ report_dir = run_dir / REPORT_DIR / "gen-set"+ report_dir.mkdir(parents=True, exist_ok=True)+ table = write_table(results, report_dir / "table.md")+ skipped = [s for s in ordered if s not in {r["state"] for r in results}]+ payload = {+ "kind": "sprite-gen-gen-set-report",+ "run_dir": str(run_dir),+ "states": ordered,+ "ok": sum(1 for r in results if r.get("ok")),+ "failed": [r["state"] for r in results if not r.get("ok")],+ "not_started": skipped,+ "items": results,+ }+ atomic_write_text(report_dir / "set.report.json", json.dumps(payload, ensure_ascii=False, indent=2) + "\n")+ print(table)+ return payload+++def add_arguments(parser: argparse.ArgumentParser) -> None:+ parser.add_argument("--run-dir", required=True, type=Path, help="a prepared run (sprite-request.json, prompts/, references/layout-guides/)")+ parser.add_argument("--states", help="comma list; default = every non-mirrored state in the request")+ parser.add_argument("--provider", choices=("codex", "grok"), help="honoured verbatim; default resolves like `gen` (env > codex, observable failover)")+ parser.add_argument("--model")+ parser.add_argument("--concurrency", type=int, default=DEFAULT_CONCURRENCY, help=f"rows generated at once (default {DEFAULT_CONCURRENCY})")+ parser.add_argument("--force", action="store_true", help="regenerate rows that already exist")+++def run(**kwargs: object) -> int:+ states = [s.strip() for s in str(kwargs.get("states") or "").split(",") if s.strip()] or None+ payload = run_set(+ run_dir=Path(str(kwargs["run_dir"])), states=states,+ provider=kwargs.get("provider"), model=kwargs.get("model"), # type: ignore[arg-type]+ concurrency=int(kwargs.get("concurrency") or DEFAULT_CONCURRENCY), force=bool(kwargs.get("force")),+ )+ return 0 if not payload["failed"] and not payload["not_started"] else 1+++def main(argv: list[str] | None = None) -> int:+ parser = argparse.ArgumentParser(prog="sprite-gen gen-set", description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ add_arguments(parser)+ return run(**vars(parser.parse_args(argv)))+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/tests/gen/test_gen_set.py b/tests/gen/test_gen_set.pynew file mode 100644index 0000000..1084f58--- /dev/null+++ b/tests/gen/test_gen_set.py@@ -0,0 +1,121 @@+# SPDX-License-Identifier: Apache-2.0+"""`sprite-gen gen-set` — the atlas pipeline's row generation as a batch command.++Contract pinned here: rows come from the prepared run (prompt + guide + identity ref),+run N at a time, every row gets a report, `table.md` names failures by stage, existing+rows are reused unless --force, a direction run generates anchors before rows and stops+when an anchor failed, and the exit code is non-zero on any failure. No provider is+called — a fake runner stands in for `sprite-gen gen`.+"""++from __future__ import annotations++import json+import threading+from pathlib import Path++import pytest+from PIL import Image++from conftest import run_script+from sprite_gen.gen import gen_set+++FLAT_STATES = {+ "idle": {"frames": 4, "fps": 6, "loop": True, "action": "standing"},+ "walk": {"frames": 6, "fps": 8, "loop": True, "action": "walking"},+ "jump": {"frames": 5, "fps": 8, "loop": False, "action": "jumping"},+}+DIRECTION_STATES = {+ "down_walk": {"frames": 6, "fps": 8, "loop": True, "action": "walking toward the viewer"},+ "side_walk": {"frames": 6, "fps": 8, "loop": True, "action": "walking in side view"},+}+++def _prepare(tmp_path: Path, *extra: str, states: dict | None = None) -> Path:+ out_dir = tmp_path / "run"+ result = run_script(+ "prepare_sprite_run.py",+ "--out-dir", str(out_dir), "--character-id", "setbot",+ "--request-json", json.dumps({"states": states or FLAT_STATES}),+ *extra,+ )+ assert result.returncode == 0, result.stdout + result.stderr+ Image.new("RGB", (64, 64), (255, 0, 255)).save(out_dir / "base-source.png")+ return out_dir+++def _fake_runner(fail_states: set[str] = frozenset(), record: list | None = None):+ lock = threading.Lock()++ def runner(prompt_file: Path, out: Path, refs: list[Path], report: Path, *, provider, model, log) -> int:+ with lock:+ if record is not None:+ record.append((out.name, [r.name for r in refs], provider))+ log.write_text("fake gen\n", encoding="utf-8")+ state = out.stem+ if state in fail_states:+ log.write_text("gen: provider refused\n", encoding="utf-8")+ return 3+ Image.new("RGB", (256, 64), (255, 0, 255)).save(out)+ report.write_text(json.dumps({"provider": provider or "codex", "provider_resolved_from": "explicit" if provider else "hard-default"}), encoding="utf-8")+ return 0++ return runner+++def test_gen_set_generates_every_row_with_run_refs_and_reports(tmp_path: Path) -> None:+ run_dir = _prepare(tmp_path)+ seen: list = []+ payload = gen_set.run_set(run_dir=run_dir, states=None, provider="codex", model=None, concurrency=3, force=False, gen_runner=_fake_runner(record=seen))+ assert payload["failed"] == [] and payload["not_started"] == [] and payload["ok"] == 3+ assert sorted(n for n, _, _ in seen) == ["idle.png", "jump.png", "walk.png"]+ for _name, refs, provider in seen:+ assert refs[0] == "base-source.png" and refs[1].endswith(".png") and provider == "codex"+ for state in ("idle", "walk", "jump"):+ assert (run_dir / "raw" / f"{state}.png").is_file()+ assert (run_dir / "reports" / "gen-set" / f"{state}.json").is_file()+ table = (run_dir / "reports" / "gen-set" / "table.md").read_text(encoding="utf-8")+ assert "| walk | codex | explicit |" in table and "| status |" in table+ assert json.loads((run_dir / "reports" / "gen-set" / "set.report.json").read_text())["kind"] == "sprite-gen-gen-set-report"+++def test_gen_set_reuses_existing_rows_and_force_regenerates(tmp_path: Path) -> None:+ run_dir = _prepare(tmp_path)+ gen_set.run_set(run_dir=run_dir, states=["idle"], provider=None, model=None, concurrency=1, force=False, gen_runner=_fake_runner())+ seen: list = []+ again = gen_set.run_set(run_dir=run_dir, states=["idle"], provider=None, model=None, concurrency=1, force=False, gen_runner=_fake_runner(record=seen))+ assert seen == [] and again["items"][0]["reused"] is True+ assert "| idle | - | - | - | reused |" in (run_dir / "reports" / "gen-set" / "table.md").read_text()+ forced = gen_set.run_set(run_dir=run_dir, states=["idle"], provider=None, model=None, concurrency=1, force=True, gen_runner=_fake_runner(record=seen))+ assert len(seen) == 1 and forced["items"][0].get("reused") is None+++def test_gen_set_names_failures_and_exits_non_zero(tmp_path: Path, monkeypatch, capsys) -> None:+ run_dir = _prepare(tmp_path)+ monkeypatch.setattr(gen_set, "run_gen_cli", _fake_runner(fail_states={"walk"}))+ rc = gen_set.run(run_dir=run_dir, states=None, provider="grok", model=None, concurrency=2, force=False)+ assert rc == 1+ table = (run_dir / "reports" / "gen-set" / "table.md").read_text()+ assert "| walk | - | - |" in table and "FAIL: gen exited 3" in table+ assert not (run_dir / "raw" / "walk.png").exists() and (run_dir / "raw" / "idle.png").is_file()+++def test_gen_set_refuses_unknown_state_and_unprepared_dir(tmp_path: Path) -> None:+ run_dir = _prepare(tmp_path)+ with pytest.raises(SystemExit, match="not in the request"):+ gen_set.run_set(run_dir=run_dir, states=["fly"], provider=None, model=None, concurrency=1, force=False, gen_runner=_fake_runner())+ with pytest.raises(SystemExit, match="not a prepared run"):+ gen_set.run_set(run_dir=tmp_path / "nowhere", states=None, provider=None, model=None, concurrency=1, force=False, gen_runner=_fake_runner())+++def test_gen_set_direction_run_generates_anchors_first_and_stops_on_anchor_failure(tmp_path: Path) -> None:+ run_dir = _prepare(tmp_path, "--directions", "down,side", "--mirror", "left=side", states=DIRECTION_STATES)+ order: list = []+ payload = gen_set.run_set(run_dir=run_dir, states=None, provider="codex", model=None, concurrency=4, force=False, gen_runner=_fake_runner(fail_states={"idle"}, record=order))+ # stage 1 = the two direction anchors (down_idle, side_idle -> raw/<dir>/idle.png); both fail here+ assert sorted(n for n, _, _ in order) == ["idle.png", "idle.png"]+ assert sorted(payload["failed"]) == ["down_idle", "side_idle"]+ # stage 2 rows were not started — the base is never re-attached in place of a missing anchor+ assert payload["not_started"] and all("_idle" not in s for s in payload["not_started"])+ assert not any(s.startswith("left_") for s in payload["states"]), "mirrored directions are skipped by contract"diff --git a/tests/packaging/test_package_surface.py b/tests/packaging/test_package_surface.pyindex 984bff2..f208c8e 100644--- a/tests/packaging/test_package_surface.py+++ b/tests/packaging/test_package_surface.py@@ -29,6 +29,7 @@ PACKAGE_RUN_MODULES = ["export_pngs","extract","gen",+ "gen_set","generate_image","inspect","prepare",