Skip to content

Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.

fix(gen): a ref run that auto plans to key asks for the key in its prompt

Soohong Kimaeb11d348945
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4187378..d954bee 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,9 +8,11 @@ All notable public changes to `sprite-gen` are recorded here. Versions track the
- **Left-facing views drawn, not mirrored — opt-in**: `video-set --facing right,left` films every side and diagonal view both ways, each from its own still (`--base side@right=… --base side@left=…`); a turned view missing a still for one facing is refused, naming the `gen --direction … --facing …` call that draws it. Items are named `<view>-<facing>-<state>`, the table names the facing, each side still is inspected for its own facing, and gaits are aligned across all eight. With `--handed`, a front or back walk's mid-step redraw is told the item's side as well. Mirroring stays the default (drawing costs as much again); one facing keeps the item names and table as before.
- **New `sprite-gen handed-check`** checks a still or loop frame by frame: a colour-marked item (`--marker`, a saturated colour nothing else on the character has) must sit on its view's picture side of the body's centre, in one place only, showing in at least half the frames on a near side and, against a `--reference` front or back picture, no more than a sliver on the far side of a side view and more than a sliver on its near side — a side view has no picture side, so a far sliver turned over to face the other way does not count as the near item shown. Without a reference both size rules are reported unchecked (`far_hidden`, `near_whole`). `--strap --zone` adds the item's band seen without its marker (a bare strap on the other arm) within the rows it sits in. Specks of the marker's hue left on outlines by a clip's colour blocks are recorded, not judged. `--board` draws every frame with its verdict; exit 1 on a failure. Drawn test figures pass as they should look and fail turned over in every view, a side view's far sliver against `--reference` (`tests/qa/test_handed_check.py`).
- **Fix: a diagonal facing left was filmed heading right.** The diagonal walk and run sentences said "to the right" and "toward the upper right" whatever `--facing` was; they now take the facing ("heading diagonally toward the viewer and to the left"). `video-prompt` and `video-set` also cut a left-facing diagonal's loop with `--facing left` (it was always `right`), which mirrors the jump repair's hair box. Right-facing prompts are unchanged.
-
-- **A `gen --transparent` run with `--ref` keeps the alpha it comes back with**: `auto` still plans a chroma key before the model runs (2026-09-08: codex drew a checkerboard in 5 of 6 ref runs asked for alpha), but the raw is read before the key is applied (`chroma.classify_raw_alpha`). A raw with an alpha band, at least 5 % of it at alpha 0 and at least half of its border at alpha 0 is published on its own alpha through the native check, with `alpha.strategy: "native"` and `alpha.strategy_source: "refs-attached-raw-alpha"`. Keying it read the RGB under alpha 0 as the background and took the outline and light fills off: a transparent reference is answered with alpha, and a fox redrawn from one lost its outline and cream belly. A checkerboard, a key background or an opaque RGBA (no alpha band, or no alpha 0) is keyed as before (`refs-attached`); alpha 0 that misses either bar is keyed as before with a `warning`. `alpha.raw_alpha` records the verdict and its numbers on every ref run that planned the key. `--alpha-mode chroma` keys whatever comes back, and `--decontam palette` refuses a raw that came back transparent. [docs/gen.md](docs/gen.md#transparent-output--strategy-per-provider).
+- **A `gen --transparent` run with `--ref` keeps the alpha it comes back with**: `auto` still plans a chroma key before the model runs (2026-09-08: codex drew a checkerboard in 5 of 6 ref runs asked for alpha), but the raw is read before the key is applied (`chroma.classify_raw_alpha`). A raw with an alpha band, at least 5 % of it at alpha 0 and at least half of its border at alpha 0 is published on its own alpha through the native check, with `alpha.strategy: "native"` and `alpha.strategy_source: "refs-attached-raw-alpha"`. Keying it read the RGB under alpha 0 as the background and took the outline and light fills off: a transparent reference is answered with alpha, and a fox redrawn from one lost its outline and cream belly. A checkerboard, a key background or an opaque RGBA (no alpha band, or no alpha 0) is keyed as before (`refs-attached`); alpha 0 that misses either bar is keyed as before with a `warning`. `alpha.raw_alpha` records the verdict and its numbers on every ref run that planned the key. `--alpha-mode chroma` keys whatever comes back. [docs/gen.md](docs/gen.md#transparent-output--strategy-per-provider).
- Measured 2026-10-04 on codex `image_gen` (subscription), one transparent front still as the reference, three takes per arm: with the planned key's prompt, a transparent reference came back with real alpha 3/3 and the same still on white came back on opaque white 3/3; asked for alpha (`--alpha-mode native`), both came back with real alpha 3/3, with no checkerboard in 6 runs. The step down is kept until a larger measurement replaces the 2026-09-08 one.
+- **The step down asks for the key it plans**: a `gen --transparent --ref` prompt that names no key background gets the `--chroma-key` key's line (`chroma.KEY_BACKGROUND_TEXT`, moved from `video.batch` so a clip's mid-step redraw and this run say the same sentence); a prompt that names a key — its hex code, or "magenta/green background", "chroma key", "screen" — is left as it is, with no second line. `alpha.key_background` records `injected` and the key. A reference on white with no key in the prompt came back on opaque white (3/3) and keying it took the outline and the cream fills; with the line, five takes (three on that reference, two on the transparent one) came back on a magenta key and kept both. `--alpha-mode chroma` and native runs are unchanged. [docs/gen.md](docs/gen.md#transparent-output--strategy-per-provider).
+- **`--decontam` is skipped, not refused, on a ref raw that came back transparent**: it has no key to remove, and the refusal came after the paid generation. `alpha.decontam` records what was asked and why it was skipped, and stderr says so (a warning for `palette`).
+- `chroma.classify_raw_alpha` judges on the pixel counts, not the rounded percentages: a raw with alpha 0 under 0.005 % was `no-alpha` and keyed with no warning; it is `ambiguous` now.
## v2.21.0 - A clip made by a video MCP on your agent (ZCRE) becomes a loop: the prompt comes out, the mp4 goes in
diff --git a/SKILL.md b/SKILL.md
index 595c7bd..96464d9 100644
--- a/SKILL.md
+++ b/SKILL.md
@@ -113,7 +113,7 @@ one wrist or a pin on one side, offer to draw them instead with `--handed` and c
| Optional scene placement, lighting, camera and render | `scene-render`, `scene-inspect` | [scene](docs/scene.md) |
| Defaults | `defaults show`, `defaults save`, `defaults clear` | [user-workflow](docs/user-workflow.md#one-settings-owner) |
-`gen --transparent` with `--ref` plans a chroma key, and publishes a result that already came back transparent on its own alpha instead of keying its outline away; `alpha.strategy_source` in the report says which (`refs-attached` keyed, `refs-attached-raw-alpha` not) — [gen](docs/gen.md#transparent-output--strategy-per-provider).
+`gen --transparent` with `--ref` plans a chroma key (adding the key's background line to a prompt that names none), and publishes a result that already came back transparent on its own alpha instead of keying its outline away; `alpha.strategy_source` in the report says which (`refs-attached` keyed, `refs-attached-raw-alpha` not) — [gen](docs/gen.md#transparent-output--strategy-per-provider).
Use existing automatic pipeline stages for background removal, extraction, alignment and export. Do not ask users to select each script. For a direct utility request, run that utility; no unrelated generation questions are needed. Preserve the row pipeline and component extraction for image sprites. One-shot grid generation and fixed cell cutting are not an alternative sprite-generation route.
diff --git a/docs/gen.md b/docs/gen.md
index 1dc91cd..6da86df 100644
--- a/docs/gen.md
+++ b/docs/gen.md
@@ -270,8 +270,23 @@ strategy it can execute, and `--alpha-mode auto` (the default) follows it:
"refs-attached"` (`provider-default` / `explicit` otherwise). The measurement is
codex's; openai's edit path is not separately measured and inherits the same
conservative default. `--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.
+ still forces native alpha with refs — and fails loud on an RGB result.
+- **The step down asks for its key.** A planned key needs a key background in the
+ prompt, so the engine adds the `--chroma-key` key's line
+ (`chroma.KEY_BACKGROUND_TEXT`, the sentence a clip's mid-step redraw also ends on)
+ to a prompt that names no key, and leaves a prompt that does as it is — no second
+ line. A prompt names a key with the key's hex code (`#FF00FF`, `00ff00`) or the
+ key's name right before "background", "backdrop", "chroma key", "key" or "screen"
+ (`chroma.named_key_background`); a colour in the subject ("a green frog") is not a
+ key. A prompt that names the other key is left on it: the matte reads the key off
+ the borders. `alpha.key_background` records `{"injected": true|false, "key": …}`,
+ stderr says which, and the report's `prompt` is the prompt sent. Without the line a
+ reference on white came back on opaque white (3/3, 2026-10-04) and keying white took
+ the outline and the cream fills with it. With it (the same prompt otherwise, three
+ takes on that RGB reference and two on the transparent one), all five came back on
+ a magenta key and were keyed with the outline and cream whole. Only `auto`'s step
+ down adds the line: `--alpha-mode chroma` is the caller's own key and prompt, and a
+ native run asks for alpha instead.
- **A ref run whose raw already has a transparent background is not keyed.** The key
is planned before the model runs, but the raw is read before it is applied
(`chroma.classify_raw_alpha`): a raw with an alpha band, at least 5 % of its pixels
@@ -284,8 +299,12 @@ strategy it can execute, and `--alpha-mode auto` (the default) follows it:
(`strategy_source: "refs-attached"`). Alpha 0 that misses either bar is `ambiguous`:
keyed as before, with a `warning` in the report and on stderr. The verdict and its
numbers are in `alpha.raw_alpha` on every ref run that planned the key. The check
- belongs to `auto`'s step down only — `--alpha-mode chroma` keys whatever comes back —
- and `--decontam palette` refuses a `real-alpha` raw, which has no key to remove.
+ belongs to `auto`'s step down only — `--alpha-mode chroma` keys whatever comes back.
+ A `real-alpha` raw has no key to remove, so `--decontam` is skipped on it, not
+ refused after the paid call: `alpha.decontam` records `{"requested": …, "skipped":
+ …}` and stderr says so (a warning for `palette`, which demands the pass). The check
+ is the counts, not the rounded percentages: a raw with a single alpha-0 pixel is
+ `ambiguous`, reported as `0.0`.
Measured 2026-10-04 (codex `image_gen`, subscription, one transparent front still as
the reference, three takes per arm): with the step down's prompt (no transparency
request, no key colour), a transparent (RGBA) reference came back with real alpha
diff --git a/sprite_gen/gen/__init__.py b/sprite_gen/gen/__init__.py
index 44b9edc..52ac9ce 100644
--- a/sprite_gen/gen/__init__.py
+++ b/sprite_gen/gen/__init__.py
@@ -190,6 +190,9 @@ def _make_provider(name: str, *, keep_session: bool):
# 2026-10-04: a transparent `--ref` is answered with alpha) is published on its own
# alpha, measured as a native one (STRATEGY_SOURCE_REFS_RAW_ALPHA), because keying
# it again mattes the outline away. A checkerboard or key background is still keyed.
+# Because the key is the engine's plan, the engine asks for it: a prompt that names no
+# key background gets the chosen key's line (`chroma.KEY_BACKGROUND_TEXT`), since a ref
+# prompt without one came back on white and keying white takes the outline with it.
STRATEGY_SOURCE_PROVIDER = "provider-default"
STRATEGY_SOURCE_REFS = "refs-attached"
STRATEGY_SOURCE_REFS_RAW_ALPHA = "refs-attached-raw-alpha"
@@ -374,6 +377,7 @@ def generate_image(
# (native asks for alpha) and the post-process (chroma keys it out).
strategy: str | None = None
strategy_source: str | None = None
+ key_background: dict[str, Any] | None = None
if transparent:
# The layout guide is an attached image as much as a --ref is: the same step down applies.
attached_for_strategy = [*refs, Path(LAYOUT_GUIDE_NAME)] if layout_guide else refs
@@ -383,10 +387,19 @@ def generate_image(
raise SystemExit(f"gen: --decontam removes a chroma key; this image would use {strategy} alpha "
"(pass --alpha-mode chroma to key it instead)")
if strategy_source == STRATEGY_SOURCE_REFS:
+ # The key is the engine's plan, so the engine asks for it: a ref prompt with no key
+ # background is answered on white or another light ground, and keying that takes the
+ # outline and light fills with it (2026-10-04). A key the prompt already names stays.
+ named_key = chroma_mod.named_key_background(prompt)
+ if named_key is None:
+ prompt += "\n\n" + chroma_mod.KEY_BACKGROUND_TEXT[chroma_key]
+ key_background = {"injected": named_key is None, "key": named_key or chroma_key}
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); "
- "a result that already has a transparent background keeps its own alpha. "
+ + (f"added a {chroma_key} key background line to the prompt; " if named_key is None
+ else f"the prompt already asks for a {named_key} key background; ")
+ + "a result that already has a transparent background keeps its own alpha. "
"Pass --alpha-mode native to force it.",
file=sys.stderr,
)
@@ -432,16 +445,20 @@ def generate_image(
# Only the key `auto` planned because of the refs is checked against the raw; an
# explicit --alpha-mode chroma is the caller's own key and runs as asked.
raw_alpha: dict[str, Any] | None = None
+ decontam_skipped: dict[str, Any] | None = None
if strategy_source == STRATEGY_SOURCE_REFS:
raw_alpha = chroma_mod.classify_raw_alpha(raw)
if raw_alpha["verdict"] == chroma_mod.RAW_ALPHA_REAL:
- if decontam == "palette":
- raise SystemExit(
- f"gen: --decontam palette removes a chroma key, but the raw came back with a "
- f"transparent background ({raw_alpha['alpha_zero_pct']}% alpha 0) and has no key "
- "to remove; run again without --decontam palette, or with --alpha-mode chroma "
- "and a key background in the prompt"
- )
+ if decontam != "off":
+ # The generation is paid for and its alpha is good: decontam has no key to
+ # remove, so it is skipped and said, not refused (see the refusal before the call).
+ decontam_skipped = {
+ "requested": decontam,
+ "skipped": f"the raw came back with a transparent background "
+ f"({raw_alpha['alpha_zero_pct']}% alpha 0) and has no key to remove",
+ }
+ print(f"[gen] {'warning: ' if decontam == 'palette' else ''}--decontam {decontam} skipped: "
+ f"{decontam_skipped['skipped']}", file=sys.stderr)
strategy, strategy_source = TRANSPARENCY_NATIVE, STRATEGY_SOURCE_REFS_RAW_ALPHA
print(
f"[gen] the raw came back with a transparent background ({raw_alpha['alpha_zero_pct']}% "
@@ -457,7 +474,11 @@ def generate_image(
"of the border); keyed as planned — check the outline, or pass --alpha-mode native"
)
print(f"[gen] warning: {raw_alpha['warning']}", file=sys.stderr)
- raw_alpha_stats = {"raw_alpha": raw_alpha} if raw_alpha is not None else {}
+ ref_stats = {
+ **({"key_background": key_background} if key_background is not None else {}),
+ **({"raw_alpha": raw_alpha} if raw_alpha is not None else {}),
+ **({"decontam": decontam_skipped} if decontam_skipped is not None else {}),
+ }
chroma_stats: dict[str, Any] | None = None
alpha_stats: dict[str, Any] | None = None
@@ -466,14 +487,14 @@ def generate_image(
alpha_stats = {
"strategy": TRANSPARENCY_NATIVE,
"strategy_source": strategy_source,
- **raw_alpha_stats,
+ **ref_stats,
**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,
decontam=decontam)
alpha_stats = {"strategy": TRANSPARENCY_CHROMA, "strategy_source": strategy_source,
- **raw_alpha_stats, **chroma_stats}
+ **ref_stats, **chroma_stats}
else:
shutil.copyfile(raw, out)
verify_png(out)
@@ -681,7 +702,8 @@ def add_arguments(parser: argparse.ArgumentParser) -> None:
default=ALPHA_MODE_AUTO,
help=(
"transparency strategy for --transparent: auto = the provider's declared strategy "
- "(native on codex and openai, but chroma whenever --ref is attached — native alpha with refs is unstable); "
+ "(native on codex and openai, but chroma whenever --ref is attached — native alpha with refs is unstable — "
+ "with the --chroma-key background line added to a prompt that names no key); "
"chroma forces chroma keying (e.g. a codex prompt that already carries a key background); "
"native forces native alpha and is refused on a provider that cannot return alpha"
),
diff --git a/sprite_gen/gen/chroma.py b/sprite_gen/gen/chroma.py
index ead2d93..21af241 100644
--- a/sprite_gen/gen/chroma.py
+++ b/sprite_gen/gen/chroma.py
@@ -15,6 +15,7 @@ output is published.
from __future__ import annotations
+import re
from pathlib import Path
from typing import Any
@@ -29,6 +30,35 @@ KEYS: dict[str, dict[str, tuple[int, int, int]]] = {
"green": {"target": (0, 255, 0)},
}
+# The sentence that asks a model for a key background, per key. A still redrawn from a
+# reference for a clip (`video.batch.walk_start_prompt`) and a ref run whose transparency
+# `auto` planned as a chroma key (`gen.generate_image`) both end their prompt with it.
+KEY_BACKGROUND_TEXT = {
+ "green": ("The entire background is one perfectly flat, uniform pure green chroma-key fill (#00FF00) with no gradient, "
+ "no texture, no shadow and no ground line."),
+ "magenta": ("The entire background is one perfectly flat, uniform pure magenta chroma-key fill (#FF00FF) with no "
+ "gradient, no texture, no shadow and no ground line."),
+}
+
+
+def _key_background_pattern(key: str) -> re.Pattern[str]:
+ hex_code = "".join(f"{channel:02x}" for channel in KEYS[key]["target"])
+ return re.compile(rf"(?<![0-9a-z])#?{hex_code}(?![0-9a-z])"
+ rf"|\b{key}\s+(?:chroma[- ]?key|key|screen|background|backdrop)\b", re.IGNORECASE)
+
+
+def named_key_background(prompt: str) -> str | None:
+ """The key a prompt already asks for as its background, or None.
+
+ A prompt names a key when it carries the key's hex code (`#FF00FF`, `00ff00`) or the key's
+ name right before "background", "backdrop", "chroma key", "key" or "screen" ("a green
+ screen", "magenta chroma-key background"). A colour in the subject ("a green frog on
+ white") is not a key. The first key named wins; the matte reads the key off the borders,
+ so a prompt naming the other key than `--chroma-key` is keyed on the one drawn.
+ """
+ found = [(match.start(), key) for key in KEYS if (match := _key_background_pattern(key).search(prompt))]
+ return min(found)[1] if found else None
+
# What a generated raw is, before a planned chroma key runs on it (`classify_raw_alpha`).
# A drawn checkerboard or a painted key background is an RGB picture: it has no alpha
@@ -63,21 +93,23 @@ def classify_raw_alpha(path: Path) -> dict[str, Any]:
if alpha is None:
return {**stats, "verdict": RAW_ALPHA_NONE, "alpha_zero_pct": 0.0, "border_alpha_zero_pct": 0.0}
total = width * height
- alpha_zero_pct = round(alpha.histogram()[0] / total * 100, 2) if total else 0.0
+ alpha_zero = alpha.histogram()[0]
edges = [(0, 0, width, 1), (0, height - 1, width, height),
(0, 1, 1, height - 1), (width - 1, 1, width, height - 1)]
edges = [box for box in edges if box[2] > box[0] and box[3] > box[1]]
border_total = sum((r - l) * (b - t) for l, t, r, b in edges)
border_zero = sum(alpha.crop(box).histogram()[0] for box in edges)
- border_alpha_zero_pct = round(border_zero / border_total * 100, 2) if border_total else 0.0
- if alpha_zero_pct == 0.0:
+ # judged on the counts, reported rounded: a single alpha-0 pixel is not "none"
+ alpha_zero_pct = alpha_zero / total * 100 if total else 0.0
+ border_alpha_zero_pct = border_zero / border_total * 100 if border_total else 0.0
+ if alpha_zero == 0:
verdict = RAW_ALPHA_NONE
elif alpha_zero_pct >= RAW_ALPHA_MIN_ZERO_PCT and border_alpha_zero_pct >= RAW_ALPHA_MIN_BORDER_ZERO_PCT:
verdict = RAW_ALPHA_REAL
else:
verdict = RAW_ALPHA_AMBIGUOUS
- return {**stats, "verdict": verdict, "alpha_zero_pct": alpha_zero_pct,
- "border_alpha_zero_pct": border_alpha_zero_pct}
+ return {**stats, "verdict": verdict, "alpha_zero_pct": round(alpha_zero_pct, 2),
+ "border_alpha_zero_pct": round(border_alpha_zero_pct, 2)}
def write_white_check(image: Image.Image, path: Path) -> None:
diff --git a/sprite_gen/video/batch.py b/sprite_gen/video/batch.py
index f34f910..d571080 100644
--- a/sprite_gen/video/batch.py
+++ b/sprite_gen/video/batch.py
@@ -25,6 +25,7 @@ from typing import Any, Callable
from PIL import Image
from sprite_gen.spec.runio import atomic_write_text
+from sprite_gen.gen.chroma import KEY_BACKGROUND_TEXT
from sprite_gen.gen.facing import FACINGS, validate as validate_facing
from sprite_gen.gen import handedness as handed_mod
from sprite_gen.gen.handedness import Handed
@@ -368,12 +369,6 @@ WALK_START_TEXT = {
),
}
WALK_START_MODES = ("redraw", "as-given")
-KEY_BACKGROUND_TEXT = {
- "green": ("The entire background is one perfectly flat, uniform pure green chroma-key fill (#00FF00) with no gradient, "
- "no texture, no shadow and no ground line."),
- "magenta": ("The entire background is one perfectly flat, uniform pure magenta chroma-key fill (#FF00FF) with no "
- "gradient, no texture, no shadow and no ground line."),
-}
def starts_mid_step(state: str, direction: str) -> bool:
diff --git a/tests/gen/test_gen.py b/tests/gen/test_gen.py
index 30b548d..1aa86e4 100644
--- a/tests/gen/test_gen.py
+++ b/tests/gen/test_gen.py
@@ -688,7 +688,7 @@ def test_ref_run_publishes_a_real_alpha_raw_without_keying_its_outline(
fake, rc, out, report = _ref_run(tmp_path, monkeypatch, _real_alpha_raw())
assert rc == 0
- assert fake.requests[0].native_alpha is False # still planned as a key: the prompt is unchanged
+ assert fake.requests[0].native_alpha is False # still planned as a key: no transparency request
published = Image.open(out)
assert published.getpixel(_OUTLINE_PX) == _OUTLINE + (255,)
assert published.getpixel(_CREAM_PX) == _CREAM + (255,)
@@ -745,15 +745,138 @@ def test_ref_run_keys_an_ambiguous_raw_and_warns(tmp_path: Path, monkeypatch, ca
assert "warning: the raw has some transparent pixels" in capsys.readouterr().err
-def test_ref_run_with_decontam_palette_refuses_a_real_alpha_raw(tmp_path: Path, monkeypatch) -> None:
[email protected]("decontam", ["palette", "auto"])
+def test_ref_run_with_decontam_skips_it_on_a_real_alpha_raw(tmp_path: Path, monkeypatch, capsys, decontam) -> None:
+ # The generation is paid for and its alpha is good: there is no key to decontaminate,
+ # so the pass is skipped, said on stderr and recorded — not refused after the call.
fake = _FakeNativeProvider(_real_alpha_raw())
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"
- with pytest.raises(SystemExit, match="has no key to remove"):
- gen.generate_image("fake", "a mushroom", out, refs=[ref], transparent=True, decontam="palette")
- assert not out.exists()
+ result = gen.generate_image("fake", "a mushroom", out, refs=[ref], transparent=True, decontam=decontam)
+
+ assert result.alpha["strategy_source"] == "refs-attached-raw-alpha"
+ assert result.alpha["decontam"]["requested"] == decontam
+ assert "has no key to remove" in result.alpha["decontam"]["skipped"]
+ assert Image.open(out).getpixel(_OUTLINE_PX) == _OUTLINE + (255,)
+ err = capsys.readouterr().err
+ assert f"--decontam {decontam} skipped" in err
+ assert ("warning: --decontam" in err) is (decontam == "palette")
+
+
+def test_ref_run_with_decontam_palette_still_decontaminates_a_keyed_raw(tmp_path: Path, monkeypatch) -> None:
+ fake = _FakeNativeProvider(_key_background_raw())
+ monkeypatch.setattr(gen, "_make_provider", lambda name, *, keep_session: fake)
+ ref = tmp_path / "ref.png"
+ ref.write_bytes(_png_bytes())
+ result = gen.generate_image("fake", "a mushroom", tmp_path / "asset.png", refs=[ref], transparent=True,
+ decontam="palette")
+ assert result.alpha["strategy_source"] == "refs-attached"
+ assert "skipped" not in result.alpha["decontam"]
+
+
+# `auto`'s step down plans a key, so the prompt must ask for one: a ref prompt with no key
+# background came back on white (2026-10-04), and keying white takes the outline's light
+# neighbours and the cream with it. The engine adds the line unless the prompt names a key.
+class _PromptFollowingProvider(_FakeNativeProvider):
+ """Draws the figure on the key the prompt asks for, or on white when it asks for none."""
+
+ def generate(self, request: GenRequest, workdir: Path):
+ key = chroma_mod.named_key_background(request.prompt)
+ ground = chroma_mod.KEYS[key]["target"] if key else (255, 255, 255)
+ self.image = _outlined_figure(Image.new("RGB", (64, 64), ground))
+ return super().generate(request, workdir)
+
+
+def test_ref_run_adds_the_key_background_line_to_a_prompt_without_one(tmp_path: Path, monkeypatch, capsys) -> None:
+ fake = _PromptFollowingProvider()
+ 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
+
+ prompt = fake.requests[0].prompt
+ assert prompt.startswith("a mushroom")
+ assert prompt.endswith(chroma_mod.KEY_BACKGROUND_TEXT["magenta"])
+ payload = json.loads(report.read_text(encoding="utf-8"))
+ assert payload["alpha"]["key_background"] == {"injected": True, "key": "magenta"}
+ assert payload["prompt"] == prompt
+ published = Image.open(out)
+ assert published.getpixel((0, 0)) == (0, 0, 0, 0)
+ assert published.getpixel(_OUTLINE_PX) == _OUTLINE + (255,)
+ assert published.getpixel(_CREAM_PX) == _CREAM + (255,)
+ assert "added a magenta key background line" in capsys.readouterr().err
+
+
+def test_ref_run_adds_the_line_in_the_chosen_key(tmp_path: Path, monkeypatch) -> None:
+ fake = _PromptFollowingProvider()
+ monkeypatch.setattr(gen, "_make_provider", lambda name, *, keep_session: fake)
+ ref = tmp_path / "ref.png"
+ ref.write_bytes(_png_bytes())
+ result = gen.generate_image("fake", "a magenta mushroom", tmp_path / "asset.png", refs=[ref],
+ transparent=True, chroma_key="green")
+ assert fake.requests[0].prompt.endswith(chroma_mod.KEY_BACKGROUND_TEXT["green"])
+ assert result.alpha["key_background"] == {"injected": True, "key": "green"}
+ assert result.chroma["key"] == "green"
+
+
+ ("prompt", "named"),
+ [
+ ("a mushroom. " + chroma_mod.KEY_BACKGROUND_TEXT["magenta"], "magenta"),
+ ("a mushroom on a flat #ff00ff background", "magenta"),
+ ("a mushroom on a pure magenta chroma-key background", "magenta"),
+ ("a mushroom in front of a green screen", "green"),
+ ],
+ ids=["engine-line", "hex", "name", "other-key"],
+)
+def test_ref_run_keeps_a_key_background_the_prompt_already_names(
+ tmp_path: Path, monkeypatch, prompt: str, named: str
+) -> None:
+ fake = _PromptFollowingProvider()
+ monkeypatch.setattr(gen, "_make_provider", lambda name, *, keep_session: fake)
+ ref = tmp_path / "ref.png"
+ ref.write_bytes(_png_bytes())
+ result = gen.generate_image("fake", prompt, tmp_path / "asset.png", refs=[ref], transparent=True)
+ assert fake.requests[0].prompt == prompt
+ assert result.alpha["key_background"] == {"injected": False, "key": named}
+
+
+ "overrides",
+ [{"alpha_mode": "chroma"}, {"alpha_mode": "native"}, {"ref": []}, {"transparent": False}],
+ ids=["explicit-chroma", "explicit-native", "no-ref", "opaque"],
+)
+def test_only_autos_ref_step_down_adds_the_key_line(tmp_path: Path, monkeypatch, overrides) -> 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"
+ gen.run(**_gen_kwargs(out, report, **{"ref": [ref], **overrides}))
+ assert fake.requests[0].prompt == "a mushroom"
+ alpha = json.loads(report.read_text(encoding="utf-8")).get("alpha") or {}
+ assert "key_background" not in alpha
+
+
+ ("prompt", "named"),
+ [
+ ("a green frog on a white background", None),
+ ("a magenta mushroom, red cap", None),
+ ("draw it on #00FF00", "green"),
+ ("FF00FF", "magenta"),
+ ("a colour FF00FFAA nearby", None),
+ ("a green backdrop; #FF00FF elsewhere", "green"),
+ ],
+)
+def test_named_key_background(prompt: str, named: str | None) -> None:
+ assert chroma_mod.named_key_background(prompt) == named
def test_explicit_chroma_keys_even_a_real_alpha_raw(tmp_path: Path, monkeypatch) -> None:
@@ -795,6 +918,17 @@ def test_classify_raw_alpha_needs_a_transparent_border(tmp_path: Path) -> None:
assert stats["verdict"] == "ambiguous"
+def test_classify_raw_alpha_judges_before_rounding(tmp_path: Path) -> None:
+ # One alpha-0 pixel in 200 x 200 is 0.0025 %, reported as 0.0 but not "no alpha".
+ image = Image.new("RGBA", (200, 200), (255, 0, 255, 255))
+ image.putpixel((0, 0), (0, 0, 0, 0))
+ path = tmp_path / "raw.png"
+ image.save(path)
+ stats = chroma_mod.classify_raw_alpha(path)
+ assert stats["alpha_zero_pct"] == 0.0
+ assert stats["verdict"] == "ambiguous"
+
+
def test_provider_without_a_declared_strategy_fails_loud(tmp_path: Path, monkeypatch) -> None:
class _Undeclared(_FakeProvider):
name = "undeclared"