Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.
gen: auto strategy keys instead of native alpha when refs are attached
Soohong Kim3d351025c8c3
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a1ab641..85bb765 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,7 +5,7 @@ All notable public changes to `sprite-gen` are recorded here. Versions track the## v1.60.0 - Native Alpha- `sprite-gen gen --transparent` now follows a per-provider transparency strategy declared once on each adapter (`Provider.transparency`). `codex` asks `image_gen` for a genuinely transparent background and publishes the measured alpha (`native`, first choice); `grok` keeps deterministic chroma keying because Grok Imagine returns JPEG only.-- Added `--alpha-mode auto|native|chroma`. `auto` reads the provider's strategy, `chroma` forces keying on codex for prompts that already carry a key background, and `native` on a chroma-only provider fails before any model call.+- Added `--alpha-mode auto|native|chroma`. `auto` reads the provider's strategy, `chroma` forces keying on codex for prompts that already carry a key background, and `native` on a chroma-only provider fails before any model call. With `--ref` attached, `auto` keys instead of asking codex for native alpha (measured 1/6 real alpha with references vs 6/6 chroma); the report records why under `alpha.strategy_source`.- Native output is verified before publishing: no alpha channel or 0% transparent pixels refuses the run (a drawn checkerboard is never keyed silently), RGB under alpha 0 is scrubbed, and partial alpha is reported untouched.- Reports carry an `alpha` block (`strategy` plus stats) next to the existing `chroma` stats, and codex's own `transparentBackground` claim under `extra.transparent_background_reported`.- Sprite-row generation is unchanged: rows still carry the request chroma key and are keyed at extraction.diff --git a/docs/gen.md b/docs/gen.mdindex 7a00fcc..0c6bef0 100644--- a/docs/gen.md+++ b/docs/gen.md@@ -100,6 +100,14 @@ strategy it can execute, and `--alpha-mode auto` (the default) follows it:| `native` | `codex` (**first choice**, 2026-09-08) | The transport prompt asks image_gen for a genuinely transparent background (the bundled `imagegen` skill honours "transparent background" and keeps the generated alpha; codex reports `transparentBackground: true` on the completed item). The decoded PNG's alpha is **measured**: no alpha band or `alpha_zero_pct: 0.0` refuses to publish, RGB under alpha 0 is scrubbed, partial alpha (1–254) is left as produced and reported as `partial_alpha_pct`. | The model drew a checkerboard / flat background (RGB image) — nothing can recover alpha from that, so the run fails instead of silently keying. || `chroma` | `grok` (only option), `codex` with `--alpha-mode chroma` | Generate on a `#FF00FF` (or `#00FF00`) background — pick the key by subject colour (magenta subjects → green key) — and matte it out through the frame extractor's canonical YCbCr matte (`remove_chroma_background_ycbcr`). Gradients and texture within that chroma family are supported. | `alpha_zero_pct: 0.0` after keying, or stale RGB under alpha 0. |+- **`auto` steps down to `chroma` when `--ref` is attached**, even on codex. Measured+ 2026-09-08 (plan `sprite-gen/parts-rig`): codex `image_gen` with reference images+ returned real alpha in 1/6 runs and drew a checkerboard (RGB) in 5/6, while the same+ prompts on a `#00FF00` key + chroma keying succeeded 6/6. The decision is made before+ the model runs, printed to stderr, and recorded as `alpha.strategy_source:+ "refs-attached"` (`provider-default` / `explicit` otherwise). `--alpha-mode native`+ still forces native alpha with refs — and fails loud on an RGB result. So a ref run's+ prompt must carry the chroma key, exactly as the sprite-row pipeline already does.- `--alpha-mode chroma` on codex is for prompts that already carry a key background(the sprite-row pipeline today): the native request is **not** added to the promptand the raw is keyed like a grok run.diff --git a/sprite_gen/gen/__init__.py b/sprite_gen/gen/__init__.pyindex 64a5b62..181cdf1 100644--- a/sprite_gen/gen/__init__.py+++ b/sprite_gen/gen/__init__.py@@ -74,12 +74,26 @@ def _make_provider(name: str, *, keep_session: bool):raise SystemExit(f"gen: unknown provider {name!r}; expected one of {', '.join(PROVIDERS)}")-def resolve_transparency_strategy(backend, alpha_mode: str) -> str:+# Why `auto` steps down to chroma when reference images are attached (2026-09-08+# 실측, plan sprite-gen/parts-rig): codex image_gen with `--ref` returned real+# alpha in 1/6 runs and drew a checkerboard (RGB) in 5/6, while the same prompts+# on a #00FF00 key + chroma keying succeeded 6/6. The edit path is not a reliable+# alpha source, so `auto` does not gamble on it — the decision is made before the+# model runs, printed, and recorded in the report (`alpha.strategy_source`).+# An explicit `--alpha-mode native` still forces it (and fails loud on RGB).+STRATEGY_SOURCE_PROVIDER = "provider-default"+STRATEGY_SOURCE_REFS = "refs-attached"+STRATEGY_SOURCE_EXPLICIT = "explicit"+++def resolve_transparency_strategy(backend, alpha_mode: str, *, refs: list[Path] | None = None) -> tuple[str, str]:"""Decide which transparency strategy this generation runs.- The provider's declared `transparency` is the only source of what it can do;- `alpha_mode` may pick `chroma` on a native provider (the prompt already carries- a key background) but can never pick `native` on a chroma-only provider.+ Returns (strategy, source). The provider's declared `transparency` is the+ only source of what it can do; `alpha_mode` may pick `chroma` on a native+ provider (the prompt already carries a key background) but can never pick+ `native` on a chroma-only provider. `auto` on a native provider steps down to+ `chroma` when reference images are attached (see STRATEGY_SOURCE_REFS)."""if alpha_mode not in ALPHA_MODES:raise SystemExit(f"gen: unknown --alpha-mode {alpha_mode!r}; expected one of {', '.join(ALPHA_MODES)}")@@ -90,13 +104,15 @@ def resolve_transparency_strategy(backend, alpha_mode: str) -> str:f"strategy (got {declared!r}); expected one of {', '.join(TRANSPARENCY_STRATEGIES)}")if alpha_mode == ALPHA_MODE_AUTO:- return declared+ if declared == TRANSPARENCY_NATIVE and refs:+ return TRANSPARENCY_CHROMA, STRATEGY_SOURCE_REFS+ return declared, STRATEGY_SOURCE_PROVIDERif alpha_mode == TRANSPARENCY_NATIVE and declared != TRANSPARENCY_NATIVE:raise SystemExit(f"gen: --alpha-mode native is not a capability of provider {backend.name!r} "f"(its transparency strategy is {declared!r}); use --alpha-mode chroma or another provider")- return alpha_mode+ return alpha_mode, STRATEGY_SOURCE_EXPLICITdef _codex_available() -> tuple[bool, str]:@@ -188,7 +204,17 @@ def generate_image(backend = _make_provider(provider, keep_session=keep_session)# Decided before the model runs: the strategy shapes the transport prompt# (native asks for alpha) and the post-process (chroma keys it out).- strategy = resolve_transparency_strategy(backend, alpha_mode) if transparent else None+ strategy: str | None = None+ strategy_source: str | None = None+ if transparent:+ strategy, strategy_source = resolve_transparency_strategy(backend, alpha_mode, refs=refs)+ if strategy_source == STRATEGY_SOURCE_REFS:+ print(+ f"[gen] {len(refs)} reference image(s) attached — using chroma keying instead of "+ f"{backend.name}'s native alpha (native output with refs is unstable, 2026-09-08). "+ "Pass --alpha-mode native to force it.",+ file=sys.stderr,+ )owns_workdir = workdir is Noneworkdir = Path(workdir).expanduser().resolve() if workdir else Path(tempfile.mkdtemp(prefix="sprite-gen-gen-"))workdir.mkdir(parents=True, exist_ok=True)@@ -218,11 +244,12 @@ def generate_image(if strategy == TRANSPARENCY_NATIVE:alpha_stats = {"strategy": TRANSPARENCY_NATIVE,+ "strategy_source": strategy_source,**chroma_mod.verify_native_alpha(raw, out, white_check=white_check),}elif strategy == TRANSPARENCY_CHROMA:chroma_stats = chroma_mod.key_transparent(raw, out, key=chroma_key, white_check=white_check)- alpha_stats = {"strategy": TRANSPARENCY_CHROMA, **chroma_stats}+ alpha_stats = {"strategy": TRANSPARENCY_CHROMA, "strategy_source": strategy_source, **chroma_stats}else:shutil.copyfile(raw, out)verify_png(out)@@ -358,9 +385,10 @@ def add_arguments(parser: argparse.ArgumentParser) -> None:choices=ALPHA_MODES,default=ALPHA_MODE_AUTO,help=(- "transparency strategy for --transparent: auto = the provider's declared strategy; "+ "transparency strategy for --transparent: auto = the provider's declared strategy "+ "(native on codex, but chroma whenever --ref is attached — native alpha with refs is unstable); ""chroma forces chroma keying (e.g. a codex prompt that already carries a key background); "- "native is refused on a provider that cannot return alpha"+ "native forces native alpha and is refused on a provider that cannot return alpha"),)parser.add_argument("--chroma-key", choices=sorted(chroma_mod.KEYS), default="magenta")diff --git a/tests/gen/test_gen.py b/tests/gen/test_gen.pyindex 1e8d1c3..f3279a1 100644--- a/tests/gen/test_gen.py+++ b/tests/gen/test_gen.py@@ -581,6 +581,7 @@ def test_native_strategy_publishes_measured_alpha_and_asks_provider_for_it(payload = json.loads(report.read_text(encoding="utf-8"))assert payload["transparent"] is Trueassert payload["alpha"]["strategy"] == "native"+ assert payload["alpha"]["strategy_source"] == "provider-default"assert payload["alpha"]["method"] == "native"assert payload["alpha"]["alpha_zero_pct"] == 75.0assert payload["alpha"]["partial_alpha_pct"] == 25.0@@ -653,6 +654,42 @@ def test_alpha_mode_chroma_forces_keying_on_a_native_provider(tmp_path: Path, moassert payload["chroma"]["key"] == "magenta"+def test_auto_steps_down_to_chroma_when_refs_are_attached(tmp_path: Path, monkeypatch, capsys) -> None:+ # 2026-09-08 실측: codex native alpha with --ref drew checkerboards 5/6, chroma 6/6.+ # `auto` therefore keys a ref run instead of gambling on native — decided before+ # the model call, printed, and recorded in the report.+ fake = _FakeNativeProvider(Image.new("RGBA", (8, 8), (255, 0, 255, 255)))+ monkeypatch.setattr(gen, "_make_provider", lambda name, *, keep_session: fake)+ ref = tmp_path / "ref.png"+ ref.write_bytes(_png_bytes())+ out = tmp_path / "asset.png"+ report = tmp_path / "report.json"++ assert gen.run(**_gen_kwargs(out, report, ref=[ref])) == 0++ assert fake.requests[0].native_alpha is False+ payload = json.loads(report.read_text(encoding="utf-8"))+ assert payload["alpha"]["strategy"] == "chroma"+ assert payload["alpha"]["strategy_source"] == "refs-attached"+ assert "reference image(s) attached" in capsys.readouterr().err+++def test_explicit_native_still_runs_with_refs(tmp_path: Path, monkeypatch) -> None:+ fake = _FakeNativeProvider()+ monkeypatch.setattr(gen, "_make_provider", lambda name, *, keep_session: fake)+ ref = tmp_path / "ref.png"+ ref.write_bytes(_png_bytes())+ out = tmp_path / "asset.png"+ report = tmp_path / "report.json"++ assert gen.run(**_gen_kwargs(out, report, ref=[ref], alpha_mode="native")) == 0++ assert fake.requests[0].native_alpha is True+ payload = json.loads(report.read_text(encoding="utf-8"))+ assert payload["alpha"]["strategy"] == "native"+ assert payload["alpha"]["strategy_source"] == "explicit"++def test_provider_without_a_declared_strategy_fails_loud(tmp_path: Path, monkeypatch) -> None:class _Undeclared(_FakeProvider):name = "undeclared"