Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.
docs: the safe-area rule is written once, in pixel-unfake.md, naming safe_area_fit and both of its callers; pixel-draw.md points there - G8's tiers, the physical cap per canvas, the info lines in the report, and the safe area as a size target in the prompt
Soohong Kima9bc491c32f3
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f321753..8e2866d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,7 +4,7 @@ All notable public changes to `sprite-gen` are recorded here. Versions track the## Unreleased-- **New (experimental): `sprite-gen pixel-draw` — Claude Opus draws pixel art of 8–48 px directly, as a pixel grid.** The model writes a palette and one line of keys per pixel row (a character grid, or JSON with `--format json`); code checks it and renders it. `--subject` (or `--spec`), `--size` 8–48 (32), `--kind sprite|icon|tile`, `--frames` (up to four, drawn in one call; `--walk-cycle` for contact, passing, contact, passing), `--palette free[:N]|pico8|#hex,…|file`, `--candidates` (2), `--effort medium|high|xhigh` (high), `--batch` (Message Batches, half price), `--max-tokens` (32000 for one frame, 64000 for more), `--pick vision|human`. G1 reads every answer strictly; a row one key too long or short, a key outside the palette or rows missing at the end go back to the model on their own with a column ruler and are spliced in (two rounds), and an answer still broken — or broken beyond its rows — is drawn once more; a single frame written without its `FRAME` line is recovered and recorded. A sprite or icon keeps the engine's safe area — `prepare`'s margin, 9.4% of the side, floored, taken from `prepare` rather than copied: at 32 px the body is drawn inside the central 26×26 (16 → 14, 24 → 20, 48 → 40), only a thin detail such as a weapon tip, a strand of hair or an effect reaches into the margin, the canvas's outermost rows and columns stay clear, and a sprite's feet stand on the safe area's bottom row, the row `prepare`'s fit grounds a frame on, in every frame; the prompt says it in rows and columns counted from 1. G2 palette, G3 alpha, G6 frames (one ground line, heights within a pixel, no two frames the same — a sprite's or icon's measured inside the safe area, so a staff or a spark that reaches into the margin in one frame is not a taller figure) and G8 safe area (no pixel on the canvas edge) fail a candidate; G4 tile seam, G5 stray pixels, a walk whose legs barely change sides, a body more than a pixel past the safe area and feet off its bottom row warn. Of two or more candidates that pass, one vision call at effort low picks (G7). An answer that spent every token thinking is drawn once more one effort lower; a refusal is reported as it came (`refused by the provider's content policy (stop_reason=refusal category=…)`); nothing falls back to another model. The run folder holds `grid.txt` (the truth: edit it and re-render with `--grid`), `palette.json`, `frame-<name>.png` written by an encoder whose bytes depend on the pixels alone, `preview-x<s>.png`, `tiled-3x3.png` for a tile, `anim.gif` for several frames, every call under `calls/` and `report.json` with each call's model, effort, usage (thinking tokens included), price, seconds and request id, the gate results and the repair history. A batch is recorded the moment it is submitted, and `--resume` collects it — and reads every answered call back — instead of buying it twice. It runs on `ANTHROPIC_API_KEY`, billed per call and said so on stderr; the transport is urllib, so the dependency surface stays Pillow and NumPy — [docs/pixel-draw.md](docs/pixel-draw.md).+- **New (experimental): `sprite-gen pixel-draw` — Claude Opus draws pixel art of 8–48 px directly, as a pixel grid.** The model writes a palette and one line of keys per pixel row (a character grid, or JSON with `--format json`); code checks it and renders it. `--subject` (or `--spec`), `--size` 8–48 (32), `--kind sprite|icon|tile`, `--frames` (up to four, drawn in one call; `--walk-cycle` for contact, passing, contact, passing), `--palette free[:N]|pico8|#hex,…|file`, `--candidates` (2), `--effort medium|high|xhigh` (high), `--batch` (Message Batches, half price), `--max-tokens` (32000 for one frame, 64000 for more), `--pick vision|human`. G1 reads every answer strictly; a row one key too long or short, a key outside the palette or rows missing at the end go back to the model on their own with a column ruler and are spliced in (two rounds), and an answer still broken — or broken beyond its rows — is drawn once more; a single frame written without its `FRAME` line is recovered and recorded. A sprite or icon is drawn to the engine's safe area — `prepare`'s margin, 9.4% of the side, floored, taken from `prepare` rather than copied — as a target for the body's average size, not a wall: at 32 px the body is about the size of the central 26×26 (16 → 14, 24 → 20, 48 → 40), a pose or a detail that needs the room (a raised weapon, a long blade, an effect, a wide stance) may reach past it into the margin, up to the canvas edge, and a sprite's feet stand on the safe area's bottom row, the row `prepare`'s fit grounds a frame on, in every frame; the prompt says it in rows and columns counted from 1. G2 palette, G3 alpha and G6 frames (one ground line, heights within a pixel, no two frames the same — a sprite's or icon's measured inside the safe area, so a staff or a spark that reaches into the margin in one frame is not a taller figure) fail a candidate; G4 tile seam, G5 stray pixels and a walk whose legs barely change sides warn. G8 safe area never fails a candidate: it takes the judgment the pixel snap already makes — one function, `safe_area_fit` in `frames/extract.py`, lifted out of the snap with its lines unchanged — on each frame's opaque box: past the physical cap (the canvas's width, its height less the margin under the floor row, 32×29 at 32 px) warns, a reroll candidate; past the safe area but within the cap is an info line, `info` in the report, which asks for nothing; and a sprite whose feet are off the floor row warns. Of two or more candidates that pass, one vision call at effort low picks (G7). An answer that spent every token thinking is drawn once more one effort lower; a refusal is reported as it came (`refused by the provider's content policy (stop_reason=refusal category=…)`); nothing falls back to another model. The run folder holds `grid.txt` (the truth: edit it and re-render with `--grid`), `palette.json`, `frame-<name>.png` written by an encoder whose bytes depend on the pixels alone, `preview-x<s>.png`, `tiled-3x3.png` for a tile, `anim.gif` for several frames, every call under `calls/` and `report.json` with each call's model, effort, usage (thinking tokens included), price, seconds and request id, the gate results and the repair history. A batch is recorded the moment it is submitted, and `--resume` collects it — and reads every answered call back — instead of buying it twice. It runs on `ANTHROPIC_API_KEY`, billed per call and said so on stderr; the transport is urllib, so the dependency surface stays Pillow and NumPy — [docs/pixel-draw.md](docs/pixel-draw.md).- **Fix: a poll xAI answers 429 or 5xx asks the same request again — the clip is bought once.** `video`, `video-extend` and `video-edit` ended the run on any non-2xx poll, after xAI had accepted the request and may bill it, and the line read `(HTTP 429)` — what `video-set`, and any caller that backs off on a refused submission, answers by submitting the clip again: a second clip paid for, the first never published. A poll answered `429`, `500`, `502`, `503` or `504` is now asked again on the same `request_id`, after a wait that doubles from 8 s up to 60 s while the polls are refused and goes back to 4 s on an answer; a stderr note says each, the status in plain digits. The poll timeout (`SPRITE_GEN_VIDEO_TIMEOUT_SECONDS`) still bounds the whole poll, a pending poll's waits included (and, below, the downloads). A refused POST is still never sent again, and a `400` or `404` poll still ends the run with its status (a `401` or `403` poll is unfinished, below).- **Output change: a generation the poll timeout cut short is unfinished, named by its `request_id`.** Polls still pending or still refused at the timeout end the run with a line that names `request_id=<id>`, says the generation may still finish and be billed, and carries no `(HTTP <n>)`, a refusal line's status — a caller that reads `(HTTP 429)` there sends the request again, unbilled only when it was refused. The pending line keeps its front (`still 'pending' after N polls — poll timeout;`). With `--report` the run leaves a `sprite-gen-video-unfinished` report there (`verb`, `auth_source`, `model`, `request_id`, `out`, `polls`, `polls_refused`, `last_poll`, `elapsed_seconds`) and prints nothing on stdout; Python callers catch `GenerationUnfinished`, a `SystemExit`. The success report gains `polls_refused`, how many of its `polls` xAI answered 429 or 5xx (docs/video.md, An unfinished generation).- **`tests/gen/test_video.py`** scripts the polls: each of the five statuses refused twice, then pending, then done, is asked on the one request with waits 8, 16, 4 and published with `polls_refused` 2; polls refused until a 300 s timeout wait 8, 16, 32, 60 × 4, ask no poll whose wait would reach the timeout and end unfinished after eight with no `(HTTP n)` and no `HTTP 429` on stderr; a pending timeout names the request; a 400 or 404 poll ends at once; a refused POST is sent once; the CLI leaves the unfinished report and an empty stdout. The 500-poll case of the failure table is a 404 now, the status that still ends a run.diff --git a/docs/pixel-draw.md b/docs/pixel-draw.mdindex c145db8..dc69e7c 100644--- a/docs/pixel-draw.md+++ b/docs/pixel-draw.md@@ -68,7 +68,7 @@ candidate's files are at the top of the run folder.|---|---|---|| `--subject TEXT` | words | What to draw. For several frames, say what each one is (the frame names are listed for the model, their meaning comes from your words). || `--spec FILE` | JSON object | `subject`, `size`, `kind`, `frames`, `walk_cycle`, `palette` instead of the flags. A key given both in the file and as a flag is refused. |-| `--size N` | 8–48 (32) | Canvas side in pixels; every frame is N×N, a sprite's or icon's body inside the [safe area](#the-safe-area) (26×26 at 32). Measured best at 32 or less. |+| `--size N` | 8–48 (32) | Canvas side in pixels; every frame is N×N, a sprite's or icon's body about the size of the [safe area](#the-safe-area) (26×26 at 32). Measured best at 32 or less. || `--kind` | `sprite`, `icon`, `tile` (`sprite`) | Sprites and icons have a transparent background, a dark outline and a margin around the body; a tile fills every pixel and repeats seamlessly. || `--frames a,b,…` | 1–4 names (one frame named after `--kind`) | Frames drawn **in one call**, so they share one palette and one design. Names are letters, digits, `_` and `-`. || `--walk-cycle` | flag | The four frames are contact, passing, contact, passing: the prompt says so and G6 checks the legs change sides. |@@ -100,8 +100,9 @@ For each candidate, independently (in parallel, or in one batch):a broken palette, a frame missing, too many rows), is drawn again at the same effort. An answerthat spent all `--max-tokens` thinking and wrote nothing is drawn again **one effort lower**(xhigh → high → medium → low). A candidate is drawn at most twice in all.-4. **G2–G6 and G8** on the pixels. G2, G3, G6 and G8 fail the candidate; G4, G5, the walk check and- G8's body and floor checks warn.+4. **G2–G6 and G8** on the pixels. G2, G3 and G6 fail the candidate; G4, G5, the walk check and G8+ (a frame past the physical cap, feet off the floor row) warn; G8 also notes a frame past the safe+ area within the cap in an info line, which asks for nothing.5. **G7 pick.** Of two or more candidates that passed, one vision call (`claude-opus-5-5`, effortlow, structured output) looks at all of them on one sheet, shuffled under letters, scores each andnames the best; with `--pick human` nobody picks and the candidates wait for a person. One that@@ -113,33 +114,37 @@ another model, provider or effort beyond the one lowered redraw.## The safe areaA pixel artist drawing a 32×32 sprite does not fill the cell: the body sits in about 26×26, and a-sword tip or a strand of hair may stray past it. sprite-gen keeps the same reserve around every cell it+raised sword, a cast or an effect may go past it. sprite-gen keeps the same reserve around every cell itlays out — [`prepare`](run-contract.md)'s safe margin, 9.4% of the side, floored — and `pixel-draw` takesits numbers from there instead of keeping its own:-| Canvas | Margin | Safe area | Floor row (counted from 1) | A thin detail may reach past it |+| Canvas | Margin | Safe area | Floor row (counted from 1) | Physical cap ||---|---|---|---|---|-| 8–10 | 0 | the whole canvas | the last row | — |-| 16 | 1 | 14×14 | 15 | not at all: the margin is the canvas edge |-| 24 | 2 | 20×20 | 22 | 1 px |-| 32 | 3 | 26×26 | 29 | 2 px |-| 48 | 4 | 40×40 | 44 | 3 px |--The prompt of a sprite or an icon says these in rows and columns the model can count: the body inside-the safe area; only a thin detail — a weapon tip, a strand of hair, an effect — in the margin; the-canvas's outermost rows and columns transparent; and for a sprite, the feet on the floor row, the safe-area's bottom row, in every frame. That is the row `prepare`'s fit grounds a frame on, so a sprite-drawn here stands where sprite-gen's other sprites of the same cell size stand. (`gen --layout-guide`-draws its floor line one margin further in: that is room for an image model's still to bob into once-a video moves it, and a grid drawn here is the frame itself.)--G8 checks it ([below](#gates)). A pixel on the canvas edge fails. The body box — the rows and columns-holding at least a quarter as many opaque pixels as the fullest one, which a blade, a strand or a-spark does not — more than a pixel past the safe area warns, and so do feet off the floor row (a-sprite that flies or floats is told the same floor and gets the same warning). G6 compares the frames-inside the safe area for the same reason: a weapon raised or an effect thrown into the margin in one-frame leaves the figure's height and floor as they were. `--grid` measures a grid by its own size,-each side on its own when it is not square. A tile has no margin: it fills every pixel and repeats.+| 8–10 | 0 | the whole canvas | the last row | the canvas |+| 16 | 1 | 14×14 | 15 | 16×15 |+| 24 | 2 | 20×20 | 22 | 24×22 |+| 32 | 3 | 26×26 | 29 | 32×29 |+| 48 | 4 | 40×40 | 44 | 48×44 |++The safe area is a target for the body's average size, not a wall. The prompt of a sprite or an icon+says it in rows and columns the model can count: the body about the size of the safe area; a pose or a+detail that needs the room — a raised weapon, a long blade, an effect, a wide stance — may reach past it+into the margin, up to the canvas edge, the four corner pixels kept transparent; and for a sprite, the+feet on the floor row, the safe area's bottom row, in every frame. That is the row `prepare`'s fit+grounds a frame on, so a sprite drawn here stands where sprite-gen's other sprites of the same cell size+stand. (`gen --layout-guide` draws its floor line one margin further in: that is room for an image+model's still to bob into once a video moves it, and a grid drawn here is the frame itself.)++G8 checks it ([below](#gates)) with the judgment sprite-gen already makes when it snaps a picture to+pixels — one function, `safe_area_fit` in [`frames/extract.py`](../sprite_gen/frames/extract.py), whose+rule is written once, in [pixel-unfake.md](pixel-unfake.md#pixel_unfake-mode): G8 hands it each frame's+opaque box, the canvas as the cell. It never fails a candidate. G8 also warns when a sprite's feet are off+the floor row: the body box — the rows and columns holding at least a quarter as many opaque pixels as+the fullest one, which a blade, a strand or a spark does not — ending above or below it (a sprite that+flies or floats is told the same floor and gets the same warning). G6 compares the frames inside the+safe area: a weapon raised or an effect thrown into the margin in one frame leaves the figure's height+and floor as they were. `--grid` measures a grid by its own size, each side on its own when it is not+square. A tile has no margin: it fills every pixel and repeats.Measured on `claude-opus-5-5` at effort high, one candidate, on 2026-10-13 — seven drawings: a knightand a wizard standing, walking and attacking at 32 px, the knight standing at 16 px. Every one kept its@@ -147,7 +152,9 @@ body inside the safe area, stood on the floor row in every frame and left the cablade, a staff and a spark reached one or two pixels into the margin. Under the earlier prompt, whichasked to fill the canvas, the same knight (2026-10-12) stood 29–31 px tall with its boots two rowsbelow the floor row, and one of its walks put the plume on the canvas edge. One wizard walk drew its-two passing frames alike and failed G6, as walk drafts do.+two passing frames alike and failed G6, as walk drafts do. Those seven were drawn when the prompt still+asked for only a thin detail in the margin and the canvas edge clear; the wording that lets a pose go+past the safe area has not been measured yet.## Gates@@ -159,7 +166,7 @@ two passing frames alike and failed G6, as walk drafts do.| G4 tile seam | Colour step across the wrap edges ÷ the mean step inside the tile ≤ 1.5 | warns — mortar lines that meet the edge raise it on tiles that repeat cleanly; look at `tiled-3x3.png` || G5 stray pixels | Opaque pixels of a sprite/icon with no opaque 4-neighbour | warns || G6 frames | Same bottom row in every frame, heights within one pixel, no two frames the same; a sprite's or icon's rows are measured inside the [safe area](#the-safe-area), so a staff raised or a spark into the margin in one frame is not a taller figure (the margin is G8's). With `--walk-cycle`: the contact frames differ by at least 40% of the mean contact↔passing difference | fails; the walk check warns ("weak leg alternation — touch up the legs") |-| G8 safe area | Sprite/icon: no opaque pixel on the canvas's outermost row or column; the body box no more than 1 px past the [safe area](#the-safe-area); a sprite's body box ending on the floor row | a pixel on the edge fails; the body past the safe area, and feet off the floor row, warn. Below 11 px the margin is 0 and there is no edge to keep |+| G8 safe area | Sprite/icon: each frame's opaque box against the [safe area](#the-safe-area) and the physical cap, by the pixel snap's own judgment (`safe_area_fit`, [pixel-unfake.md](pixel-unfake.md#pixel_unfake-mode)); a sprite's body box ending on the floor row | never fails: past the physical cap, and feet off the floor row, warn; past the safe area within the cap is an info line (`info`), which asks for nothing. Below 11 px the margin is 0: the safe area and the cap are the canvas || G7 pick | Two or more passed: the vision pick (or a person) | a pick that fails ends the run `pick_failed`, candidates kept |## The run folder@@ -193,9 +200,9 @@ zlib build. The previews, the tiling and the GIF are views for the eye.|---|---|| `status` | `ok`, `failed` (no candidate passed), `refused` (every candidate refused), `pick_failed`, `unfinished` (a batch not collected yet) || `request` | the resolved inputs (`palette` with its rule and colours) |-| `chosen`, `files`, `warnings` | the picked candidate, its top-level files, its warnings |+| `chosen`, `files`, `warnings`, `info` | the picked candidate, its top-level files, its warnings (worth a look, maybe a redraw) and its info lines (nothing to do) || `pick` | `by` (`vision` / `only` / `human`), `best`, and for the vision pick its `labels`, `sheet` and `verdict` |-| `candidates[]` | per candidate: `status`, `reason`, `effort` of the answer kept, `generations` (call ids), `redraws` (after which call, why, at which effort), `repairs` (rows asked, answered, still broken), `G1` (issues and what was recovered), `gates` (G2–G6 and G8 with their measures), `warnings`, `files` |+| `candidates[]` | per candidate: `status`, `reason`, `effort` of the answer kept, `generations` (call ids), `redraws` (after which call, why, at which effort), `repairs` (rows asked, answered, still broken), `G1` (issues and what was recovered), `gates` (G2–G6 and G8 with their measures), `warnings`, `info`, `files` || `calls[]` | per call: `id` (`c1-gen1`, `c1-gen1-fix1`, `pick`), `purpose`, `mode` (`realtime` / `batch`), `model`, `effort`, `max_tokens`, `request_id`, `message_id`, `batch_id`, `stop_reason`, `stop_details`, `usage` (as the API reported it), `thinking_tokens`, `cost_usd`, `seconds`, and for a failed call `error` and `billed` || `batches[]` | per batch: `id`, `custom_ids`, `submitted_at`, `collected`, `ended_at`, `waited_seconds` || `usage`, `cost_usd`, `seconds` | totals over the calls, and the run's wall time |diff --git a/docs/pixel-unfake.md b/docs/pixel-unfake.mdindex 4fa180b..f047c74 100644--- a/docs/pixel-unfake.md+++ b/docs/pixel-unfake.md@@ -34,7 +34,7 @@ For true pixel-unfake output (game-ready chunky pixel art with intact 1px outlin"fit": { "pixel_unfake": true, "logical_height": 64, "palette_size": 48, "align_x": "foot-centroid", "align_y": "bottom" }```-**눌림 없음 — 유일한 동작** (maintainer 확정 2026-07-14, 옵트인 잔재 완전 제거 2026-07-17): 스냅된 네이티브 논리 크기를 유지한다 — `logical_height` 계약으로의 conform 축소는 칸을 병합해 디테일(눈·아웃라인)을 갈라먹는다. 과거의 `"conform": true` 옵트인은 **제거됐고 선언 시 요란하게 거부된다** — 제거된 결정이 플래그 하나로 되살아나는 회귀 경로였다 (회귀 2026-07-17: 높이 통일 시도가 이 플래그로 재발). 물리 한계(셀 바닥 마진 유지, `(cell_h − margin_y)/scale`)만 캡으로 강제되고 캡에 걸린 프레임은 경고로 관측된다. **안전영역(사방 여백 준수 상한)을 넘었지만 물리캡 이내인 여백 침범은 리롤 대상이 아니다** — 정보성 알림만 남는다(manifest warning + 큐레이터 줄 헤더 "여백 침범" 배지, maintainer 확정 2026-07-14). 계약 키(logical_height)는 생성 목표/경고 기준일 뿐 강제 수단이 아니다.+**눌림 없음 — 유일한 동작** (maintainer 확정 2026-07-14, 옵트인 잔재 완전 제거 2026-07-17): 스냅된 네이티브 논리 크기를 유지한다 — `logical_height` 계약으로의 conform 축소는 칸을 병합해 디테일(눈·아웃라인)을 갈라먹는다. 과거의 `"conform": true` 옵트인은 **제거됐고 선언 시 요란하게 거부된다** — 제거된 결정이 플래그 하나로 되살아나는 회귀 경로였다 (회귀 2026-07-17: 높이 통일 시도가 이 플래그로 재발). 물리 한계(셀 바닥 마진 유지, `(cell_h − margin_y)/scale`)만 캡으로 강제되고 캡에 걸린 프레임은 경고로 관측된다. **안전영역(사방 여백 준수 상한)을 넘었지만 물리캡 이내인 여백 침범은 리롤 대상이 아니다** — 정보성 알림만 남는다(manifest warning + 큐레이터 줄 헤더 "여백 침범" 배지, maintainer 확정 2026-07-14). 실패는 없다. 이 판정은 함수 하나다 — `frames/extract.py` 의 `safe_area_fit`(프레임 크기 → 물리캡 `over` = 경고, 안전영역만 넘침 `soft` = 정보): 픽셀 스냅이 부르고, [`pixel-draw`](pixel-draw.md#the-safe-area) 의 G8 도 각 프레임의 불투명 상자 크기로 같은 함수를 부른다(캔버스 = 셀, 배율 1). 계약 키(logical_height)는 생성 목표/경고 기준일 뿐 강제 수단이 아니다.`logical_height` 를 **생략하면 셀 높이와 동일(1:1)** 이 기본이다 — 생성 프롬프트가 "TRUE `<셀>`x`<셀>` pixel grid" 를 명시하는 현행 레시피에서 원본 그리드 해상도를 그대로 따라간다(권장). 더 청키한 저해상 룩을 원할 때만 작은 값을 명시한다: 셀 64 + 로지컬 32 → 2× 청키 픽셀.