Skip to content

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

56.7 KB
Raw Blame

Run Contract — pipeline stages · run-dir folder tree · curation-view display (SSoT)

Owns: The atlas pipeline's normative contract: stages, a flag against the file that holds the same key (every verb), the run-dir folder tree, curation-view display, atomic extract, concurrency scope · Index: docs/README.md

Status: contract (normative). This doc is the single source of truth for three things every sprite-gen run must satisfy so that any agent who serves a view gets the same experience — the base reference row, the per-state generation-material chips, the pixel grid, and the original-quality toggle.

Precedence (no overlap, so no contradiction):

  • user-workflow.md owns the conversation; atlas-workflow.md owns row execution.
  • This doc owns the structural contract — the stage I/O table, the run-dir folder tree, the curation-view display payload, and the import-run source rule. These are the parts the scripts enforce.
  • architecture.md explains how the code realizes both; it is always description, never contract.

If the three ever disagree: behavior → the workflow docs win; structure/display → this doc wins; architecture.md is the bug.

Contents

1. Pipeline stages

One image-gen call per state row is the only AI step; every stage after it is deterministic (same input → same output). Each script does one job and reads/writes canonical files, not hidden imports.

Stage Script Input Output
Prepare prepare_sprite_run.py base image + request flags/JSON sprite-request.json, per-state layout guide, per-state prompt, empty raw/+frames/
Generate sprite-gen gen (generate_sprite_image.py) prompts/<state>.txt + refs verified raw/<state>.png strip + audit raw/report
Extract extract_sprite_row_frames.py raw/<state>.png on success: frames/<state>/frame-N.png (+ .plain.png twin on pixel-unfake runs), frames/frames-manifest.json; on failure: nothing in frames/, extract-failure.json instead (§6)
Curate (opt) sprite-gen curation (serve_curation.py) + curation.py frames/ curation.json sidecar
Compose compose_sprite_atlas.py frames/ + curation.json sprite-sheet-alpha.png, manifest.json, *.report.json
Engine export (opt) sprite-gen export-aseprite (sprite_gen/compose/export_aseprite.py) composed manifest.json + existing atlas exports/aseprite.json, or exports/aseprite/<state>.json for Flame
Recolor (opt) sprite-gen recolor / recolor-palette (sprite_gen/effects/recolor.py) base sheet (default sprite-sheet-alpha.png) + recolor spec variants/<name>.png, optional variants/<name>.manifest.json, variants/recolor.report.json
QA preview_animation.py frames/ qa/<state>-contact.png, qa/<state>.gif
Inspect inspect_sprite_run.py sprite-request.json, raw/ or frames/ sprite-inspect.report.json
Score score_sprite_run.py sprite-inspect.report.json sprite-score.report.json, correction hints
Correction loop run_correction_loop.py run dir + optional provider command correction-loop.report.json, per-attempt inspect/score/hints
GIF export compose_sprite_gif.py, gif_utils.py selected frames clean transparent GIF into exports/
Selected cycle compose_selected_cycle.py curation.json / --frames selected-cycle manifest + QA
Inverse / import unpack_atlas_run.py finished atlas or --pngs-dir curator-ready run dir (§4)
Export stills export_curated_pngs.py curated frames/ named PNGs under curated/
Chroma guard scripts/dev/check_visible_magenta.py screenshot leakage warning

A flag and the file that holds the same key. A key given both as a flag and in the file a verb reads with its flags — prepare --request / --request-json, pixel-draw --spec — takes the flag, and one stderr line names every flag the file also set: [prepare] --style, --cell-size given both as a flag and in --request-json: the flag wins. A value the file holds is never replaced in silence, and no verb answers this question another way (gen.base.flags_over_spec). For prepare a flag replaces a cell measure however the request spelled it (--cell-size, --cell-width and --cell-height the width and height whether the request said size, width or cell_width; --safe-margin both margins).

The happy path is prepare -> gen -> extract -> compose, followed by delivery and an optional curation view. Curation is opened only when requested or enabled in saved defaults; edits are composed again for export. Stage internals (chroma removal, connected components, pixel-unfake path, the .sprite-gen.lock single-writer rule, the inspect/score/loop split) are described in architecture.md §2, §6 — this table is the contract, that doc is the explanation.

2. Run-dir folder contract

One worker owns exactly one character folder. This is the canonical tree — do not restate it elsewhere; point here.

<target>/assets/generated/sprites/<character-id>/
  sprite-request.json                # numeric SSoT (cell, chroma, states, fit) — every stage reads this
  base-source.<ext>                  # identity truth; drives the view's base reference row (§3)
  references/layout-guides/<state>.png   # per-state layout guide (motion only)
  references/anchors/<dir>-anchor-x8.png # DERIVED CACHE: the curated direction-anchor frame, baked
                                         #   ×8 NEAREST for row generation. `sprite-gen anchor`
                                         #   (SSoT sprite_gen/curate/anchor.py) rewrites it on demand —
                                         #   never hand-edit it and never treat it as truth.
  references/imported/<group>/           # imported-run generation material → chips (§4); real runs use raw/ anchors instead
  prompts/<state>.txt                # generated row prompt (frame count, safe margin, anchor lock)
  raw/<state>.png                    # one horizontal image-gen strip per state (the only AI output)
  frames/<state>/frame-N.png         # extracted transparent cells — PRE-CURATION.
                                     #   **Not the deliverable.** These are the extractor's own
                                     #   output; the human's picks, pixel edits, transforms,
                                     #   deletions and clones live in `curation.json` and are
                                     #   applied downstream. An app that copies from here
                                     #   silently ships the un-edited image (see §2-c).
  # ── 파일 택소노미 (layout: taxonomy/v1 — 신규 런 기본, maintainer 확정 2026-07-14) ──
  # 방향 계약(directions) 런은 위 두 경로가 방향/자세 폴더로 나뉜다. 상태 ID 는 그대로
  # <direction>_<pose>, 파일 경로만 분리. 리졸버 SSoT = sprite_gen/spec/layout.py.
  # 이미 추출된 프레임을 읽는 소비자는 frames-manifest 의 row.files 경로를 따른다
  # (row_frame_rel) — 패턴 조립 금지. layout 필드 없는 legacy 런은 flat 유지.
  # 프로젝트별 정비 방식이 지침으로 오면 지침이 우선한다.
  raw/<direction>/<pose>.png                 # 택소노미: 생성 스트립
  raw/<direction>/<pose>.takes/<label>.png   # 테이크: 같은 상태의 추가 후보/보강 스트립 (아래 참조)
  frames/<direction>/<pose>/frame-N.png      # 택소노미: 추출 프레임 (+ .plain / orig/)
  references/layout-guides/<direction>/<pose>.png
  prompts/<direction>/<pose>.txt
  # ── 테이크 (takes 1급 계약, 2026-07-15) ── request `states.<s>.takes: [{label, frames}]`
  # 가 선언하면 추출이 primary 스트립 뒤에 각 테이크 스트립을 이어붙여 한 행의 프레임
  # 풀을 만든다 (스트립별로 따로 스냅 — 프레임 자체 검출 격자 1순위, 스트립 합의는
  # 검출 실패 프레임 fallback 전용. 행 정합·팔레트·배치는 함께).
  # manifest row 에 labels("blink#0"…)/takes(start·frames·raw)가 남고, 소비자가 행
  # 크기를 request 에서 셀 때는 layout.state_frame_total(primary+takes 합)을 쓴다.
  # 어느 스트립 하나라도 실패하면 행 전체가 이전 세대로 남는다 (부분 풀 게시 금지).
  frames/<state>/frame-N.plain.png   # pixel-unfake runs only: cell-sized pre-pixel-unfake twin, baked by compose on pixel_unfake:false (§3)
  frames/<state>/orig/frame-N.png    # pixel-unfake runs only: hi-res original twin (display-only), drives the pp-off toggle at original quality (§3)
  frames/frames-manifest.json        # per-row extract report (files, labels, ok) — only ever a COMPLETE ok generation (§6)
  # frames/ 는 (raw + request + 엔진)의 파생 캐시다 (실시간 계약, maintainer 확정 2026-07-14):
  # 행별 engine_revision(엔진 소스 해시) 스탬프가 캐시 키. 소비자(큐레이션 뷰 /api/run·
  # /api/progress, compose_atlas, /download/*)는 진입 시 extract.heal_run 으로 stale 행을
  # raw 에서 자동 재유도한다 — 뷰에 '재추출' 개념이 없다. raw 가 없는 행은 보존 + 관측
  # 노트(kept_stale). manifest 의 extract_args 가 재유도 플래그 재현을 보장한다.
  extract-failure.json               # while any state's extract is unresolved: per-state ok:false diagnostics, OUTSIDE frames/ (§6); merged per state, removed once all resolved
  curation.json                      # optional, non-destructive sidecar (selected/order/transforms/pixel_unfake)
  unpack-source.json                 # import runs only (unpack_atlas_run.py): provenance — atlas/pngs source, base_source, imported_refs
  sprite-sheet-alpha.png             # composed runtime atlas
  sprite-sheet-alpha.report.json     # compose report
  manifest.json                      # runtime SSoT: frame_layout absolute rects
  variants/                          # only when sprite-gen recolor runs — baked colourway sheets
                                     #   (<name>.png + optional <name>.manifest.json) +
                                     #   recolor.report.json (SSoT for substituted / unused /
                                     #   passthrough pixels). Adopted pick lives in
                                     #   curation.json.recolor.picked (name-keyed). See
                                     #   docs/recolor.md.
  sprite-inspect.report.json         # inspect_sprite_run.py output (per-state health rows)
  sprite-score.report.json           # score_sprite_run.py output (overall score + correction hints)
  correction-loop/                   # run_correction_loop.py: attempt-N/ (inspect/score/hints) + candidate-N/ regenerated run dirs
  qa/<state>-contact.png             # QA contact sheet
  qa/<state>.gif                     # QA state GIF
  qa/<name>.gif, qa/<name>-contact.png, qa/<name>.json   # compose_selected_cycle.py: named selected-frame cycle + its manifest
  qa-notes.md                        # per-state motion verdict + reference-plan notes
  curated/                           # only when export_curated_pngs.py runs — CURATION APPLIED.
                                     #   This is what an external consumer installs (§2-c).
  exports/                           # only when compose_sprite_gif.py --run-dir runs (per-state GIF + gif-manifest.json)
  .sprite-gen.lock                   # single-writer lock (runio.py); a live holder blocks a second writer (§7 guarantee boundary)
  .frames.sg-staging/                # transient: extract builds the new generation here, swapped into frames/ under publish_guard

Transient publish sidecars exist only during an extract/import commit: .frames.sg-backup and .extract-failure.sg-backup (extract's in-place rollback copies), an import's own .<name>.<pid>-<random>.sg-staging (beside the run dir) and .sg-backup.<pid>-<random> (in it, §4), and .<name>.sg-rwlock (in the parent dir — the publish reader/writer lock). Their durability/concurrency boundary is §7.

Rules the display depends on:

  • base-source.* is the identity truth and must survive independent of baking — the view shows it as a top reference row (§3) whether or not it was attached to any row. Real runs write it in Prepare; imported runs write it from pngs/_base/ (§4).
  • raw/<direction>_idle.png and raw/down_<state>.png are what the view resolves into per-state generation-material chips for real (directional-anchor) runs — the chip is "which anchor / basis row / guide generated this state". See directional-anchor-workflow.md for the naming.
  • references/imported/<group>/ is the imported-run equivalent of those raw anchors: an imported row carries its generation material here so the view produces the same chips (§4).
  • frames/<state>/frame-N.plain.png (pixel-unfake runs only) is the cell-sized pre-fit twin that compose bakes when the sidecar turns pixel-unfake off for that state (states.<state>.pixel_unfake:false, or the run-wide pixel_unfake:false default — resolver: curation.frame_variant(curation, state)) — the atlas slot is cell-sized, so this twin must be too. frames/<state>/orig/frame-N.png is the hi-res (S×cell) pre-fit twin the view displays when the user turns pixel-unfake off, so "off = original" is crisp instead of an upscaled cell blur. S is per-row native: the ceil of the largest component-crop / final-content-bbox ratio across the row's frames (bounded by 2048 // cell), so the twin resample is a mild upscale — never a downscale (and, like the other places that scaled with LANCZOS, through resize_cell: coverage and colour scaled apart, no rim or key tint added at the edge). The old fixed ×4 cap squeezed high-pitch raws (synthetic_fixture_b down rows, ~14px pitch) ~3.5× and the "original" view stopped being the original (maintainer, 2026-07-23). The view prefers orig/, falling back to .plain.png when no hi-res twin exists. Both twins are fitted into the pixel-unfake frame's content bbox (same footprint), so the toggle compares pixel treatment at identical size and a plain bake keeps the same character size as pixel rows. Sidecar-baking semantics are owned by pixel-unfake.md; the display contract for the toggle is §3.

The runtime manifest.json.frame_layout contract (absolute rects, no runtime alpha-recovery, degraded_static_fallback: false) is owned by ../SKILL.md "Runtime Contract" and is out of scope here.

2-b-2. Reading a run never writes to it

sprite-request.json has exactly one read gate (runio.load_request) and exactly one schema writer (runio.migrate_request_file, exposed as sprite-gen migrate-request <run-dir> --apply). They are separate on purpose.

  • Reads are byte-stable. load_request, and everything that goes through it (state_revision, run_revision, load_curation, the view's snapshot endpoints), leave the run directory byte for byte identical. A retired key is normalized in memory only, so an old approved run keeps working without its file being touched: a renamed key (fit.pixel_perfect) is read as the current key (fit.pixel_unfake), and a key retired with nothing in its place (rig, layers and states.<state>.track, read by no code since layer-tracks was removed in 3.0.0) is left out. The first read of such a run in a process names those keys once on stderr. A renamed key and its current key both present is still a hard fail — code cannot pick which of two truths is real. The curation sidecar reads the same way: a generation-mismatched curation.json is salvaged row by row in memory and the file itself is left alone — the load gate writes no backup copy (see the bullet below).
  • Schema migration is an explicit command. It is a dry run unless --apply is passed. The write takes the publish rwlock (runio.publish_guard) — the same exclusive lock the request editors take — re-reads the document after acquiring it, and replaces the file atomically. It deliberately does not take the pipeline .sprite-gen.lock: that lock guards stage outputs (frames, atlas), and extraction/compose never write the request, so holding it would look like protection while the actual competitors (reroll, interpolate, the view's fps edit) walked straight past it. One resource, one isolation domain.
  • Every request read-modify-write shares that one domain. Migration, take recording (reroll.record_take, interpolate.write_take) and the view's fps POST all do acquire → fresh re-read → atomic replace inside publish_guard, so no pair of them can lose the other's write. Locked by named race tests plus a structural assertion that no production request write sits outside the guard (tests/test_request_write_isolation.py).
  • A stale backup is written by the writer, never by a read. curation.stale-<hash>.json is created only by curation.write_curation_atomic, at the moment an overwrite would actually lose rows. The load gate used to write it while merely judging a generation-mismatched sidecar — a read that created a file in the run dir, the same class of defect as the incident below. Nothing is lost at drop time: curation.json is still on disk, untouched.
  • Unrelated edits preserve the on-disk key form. Take recording (reroll / interpolate) and the view's fps edit reload the whole document through the gate and write it back, so they go out through runio.write_request, which folds a normalized key back to whatever the file actually carries and writes a left-out key back with the file's own value. Otherwise changing one fps value would migrate the schema as a side effect, and "only the explicit command changes the schema" would be false the moment anyone edited anything.

A synthetic regression fixes the failure mode: normalizing a retired key during a state_revision() query must not rewrite sprite-request.json, move run_revision, or knock a curation sidecar stale. A query has no business changing what it reports on.

Migration does change the file bytes, so it does move run_revision. The curation sidecar survives it through per-row revision salvage (§ curation.load_curation_report); rows with no stamp are dropped as usual, and migrate-request prints which rows those are before it writes.

2-b-3. A run never writes over, moves or deletes its inputs

Every verb that writes beside what it reads checks, before anything is made and with or without --force, that no input is something the run replaces or deletes. There is one judgment for this, runio.refuse_overlap, and every such verb calls it; section 4 covers unpack-atlas in detail. What counts as an input is each path given to read, and each file or folder found in a folder given and then read (for example a frame in --frames-dir, or each file, folder and link the best candidate's copy reads in --run-dir). Each input is followed the way the system opens it (runio.follow_path): every link and folder its path looks up counts. What counts as an output is each file the run writes, each folder it replaces or empties, and its report. A folder the run only adds files to is not an output. That is why the --out-dir of video-loop and video-stop is not itself compared: the keyed frames those verbs read usually lie inside it (video-frames writes them to <out>/keyed/). Each output is compared at the path the run writes, opened the way the system opens it: a link already at that place is the entry it leads to (for example attempt-1 in the --out-dir of correction-loop, a link to the run dir, is the run dir; before this change only --out-dir itself was compared, and the loop wrote its attempt into the run it read). A link at a file the run writes is refused as well when it leads to an input, even where the run would replace the link rather than write through it. An input that is the same file or folder as an output, lies inside an output, or whose path goes through anything inside an output is refused, naming both the input and the output. Comparison is by real path and file identity (runio.same_folder, runio.inside_folder), so a link, or another spelling on a volume that ignores case, is the same entry. An input path with a link loop is refused by name. A path that only passes through an output and comes out of it again with .. (for example out/cycle.source/../keyed) is not refused.

Verb Inputs What the run replaces or deletes
unpack-atlas see section 4 the run dir, whose prior content --force replaces; an --out-dir inside an input is refused as well
video-loop --frames-dir and every PNG found in it cycle/, cycle.source/, cycle.refused/, follow.source.png, <name>.strip.png, <name>.strip.json, <name>.gif, <name>.webp, the report
video-stop --frames-dir and every PNG found in it; --loop and the strip PNG beside it <name>.strip.png, <name>.strip.json, <name>.gif, <name>.webp, the report
video-chain Each --piece's folder; --places; --holds keyed/, keyed.refused/, the report
video-frames --clip, --reference raw/ (its frames are replaced), keyed/, keyed.refused/, the report, --source-manifest
correction-loop --run-dir, and every file, folder and link the best candidate's copy reads in it --out-dir and everything the loop writes in it: each attempt's folder and the files in it, each candidate a provider makes, best-candidate/, the report
logo --mood, --lettering lettering.png, logo.png, logo.rejected.png, logo.preview.png, mood.png (when the run writes one), the report
video-extend, video-edit --video --out, the download staged beside it (<out>.part), the report
video-loop-compare every artifact given (--baseline-*, --candidate-*, --origin-*), the source inputs (--source-*) and every PNG in --source-frames-dir, --repair-evidence the report
video-loop-repair --baseline-*, --origin-*, the source inputs (--source-*) and every PNG in --source-frames-dir the report (the candidate's --out-dir must not exist yet)
video-source-manifest --clip, --canvas, --frames-report, --frames-dir and every PNG in it --out
shadow --source and every file the asset loader reads for it the frame PNGs, shadow.png, shadow.asset.json

Two verbs have an exception. In logo, --mood may be the folder's own mood.png and --lettering may be the folder's own lettering.png. That is a picture an earlier run made, given back to start again from it; the run reads it and writes its own pixels back. Any other output file given as --mood or --lettering is refused. In correction-loop, an --out-dir inside the run dir (the default, <run-dir>/correction-loop, is) is only added to, and the best candidate's copy of the run dir leaves it out. Before this change the copy copied itself into itself until the path was too long. An out dir that already holds an earlier loop's attempts, best candidate and report is the loop's own, and a second loop into it is not refused.

A folder a run writes into and then deletes is a new one of its own, made with runio.new_stage (named .<name>.<pid>-<random><suffix>). These are: the frames video-loop scales back for a size hold or the gait fallback (.gait-fallback-frames.<pid>-<random>, removed however the run ends); the PNG frames every animated WebP is built from (.<name>.webp.<pid>-<random>.frames beside the WebP, for video-loop, video-stop, video-cycle-align, video-sway and video-loop-repair); the working folder video-frames keys into (.keyed.<pid>-<random>.work); and the working folder of logo (.logo-work.<pid>-<random>). A folder at one of the old fixed names (.gait-fallback-frames, .webp-frames, .keyed.work, .logo-work), whether it holds an input or belongs to anyone else, is never written into or removed.

The verbs that check a single output against their inputs call the same two functions, runio.same_folder and runio.inside_folder, and have no comparison of their own: background-tile, inspect-motion, scene-inspect, scene-render and video-sway-inspect. video-sway-inspect now refuses an --out-dir that is the loop directory spelt in capitals on a volume that ignores case; before, it wrote its boards into the loop directory. video-loop-compare, video-loop-repair, video-source-manifest and shadow compared their report or outputs with their inputs by resolved spelling; they now call runio.refuse_overlap, so a report or output spelt in capitals of an input on a volume that ignores case is refused (before, it was written over the input).

2-c. External consumers install from curated/, never from frames/

frames/ is the extractor's own output. Everything a human does in the curation view — frame picks, play order, pixel edits, transforms, deletions, clones — lives in curation.json and is applied downstream, not written back into frames/.

So an app that copies frames/<state>/frame-N.png into its assets silently ships the un-edited image. Nothing fails: extract succeeded, the file exists, the copy succeeded. The only signal is a human noticing their work is gone.

A synthetic regression fixes this failure mode: copying from frames/ after a pixel edit must not be treated as a curated export, because it would silently discard the edit.

Rules for anything outside this repo:

  • Stills / single frames → run export_curated_pngs.py, install from curated/.
  • Animation → consume sprite-sheet-alpha.png + manifest.json from compose_sprite_atlas.py (compose already reads curation.json).
  • Never reach into frames/ unless you are re-deriving the cache itself.
  • If a tool must accept both, it prefers curated/ and says which one it read — a silent choice between two sources is how the edit disappears.

Inside this repo the compose/GIF/atlas paths already read frames/ together with curation.json, which is correct; the hazard is external copying.

3. Curation-view display contract

serve_curation.py serves one run dir and returns the run snapshot at GET /api/run. The webview (sprite_gen/serve/curator/*) renders exactly four contract elements from that payload. A view that omits any element it has the data for is a broken view — the whole point is that the experience does not vary by who launched it.

Element Shown when Payload source Rule
Base reference row base-source.* exists baseUrl (null if absent) Top row, pure image — no preview/select UI. Identity truth, always visible.
Generation-material chips the state has resolvable material states[].refs[] — each {role, name, url} Per-state header shows what generated this row. role ∈ {anchor, basis, guide}, labelled 방향 앵커 / basis row / 레이아웃 가이드 (i18n key ref_<role>). Only run-dir files that actually exist appear — except the anchor chip (anchorFrame: true), which is a live bake (/api/anchor?direction=<dir>) named <state>#<index>, because the on-disk references/anchors/*.png is a derived cache that goes stale the moment the user edits the anchor frame.
Anchor frame request has a directions block directionGroups[].anchorFrame {state, index, source} + anchorError/anchorErrorCode/anchorPending/anchorUrl · curation.anchors The one curated instance that is this direction's identity for generating its other rows. source: "picked" = pinned by the human (frame card pin button → curation.anchors.<dir>), "default" = the anchor row's sequence head. The anchor card carries an 앵커 badge (tinted when pinned); an unresolvable pin surfaces anchorError in the status bar instead of silently reverting — archived frame (pick-missing) or regenerated row (pick-stale-generation: the pin carries the pinned row's state_revision, so a re-derived row makes the pin stale rather than silently pointing it at a different image). anchorPending: true is not an error — the anchor row is not generated yet (the normal mid-work state), so the view must not colour it as a failure. Resolution SSoT = sprite_gen/curate/anchor.py.
Pixel grid always — the measurement cannot fail states[].pixelScale (≥1, never null) + pixelUnfake{label,scale} + states[].frames[].contentBox Per-state checkbox on every row's refs strip; the top checkbox is a toggle-all (indeterminate when mixed). Display only, never persisted. pixelScale is an exact test (largest k where the frame is only uniform k×k blocks; k=1 is trivially true — identity), so "unknown grid" does not exist and nothing gates on it. On the pixel-unfake view: the output raster (request scale on fit.pixel_unfake runs, measured k labelled auto otherwise). On the original (plain) view: the final correspondence grid — green, one cell = one result pixel. (The stage-1 cut lattice in frames-manifest input_grids stays diagnostic-only.) An identity grid (k=1) is a true grid, not a missing one — density is a property of the fact, not a reason to hide the control.
Direction groups request has a directions block directionGroups[] — {direction, anchor, states, anchorFrame, anchorError} + mirror entries {direction, mirrorOf} States render grouped per direction with the direction anchor first (badge 방향 앵커); mirrored directions render as an informational strip (<src> 런타임 미러 — 생성 없음), never as silently missing rows. Runs without the block keep the flat request order.
Original-quality toggle always — every row has the control states[].frames[].plainUrl + fitPixelUnfake Per-state checkbox on every row's refs strip + zoom modal (same contract, no per-surface gating). Twin rows: on = canonical frame-N.png, off = plainUrl (hi-res orig/ else .plain.png) — a source switch, persisted per state. Twin-less rows: on = the display renderer re-quantizes by the measured grid pixelScale (the same k the grid overlay draws — grid-based pixel-unfake; k=1 is identity), a display lens, never persisted (persisting would make the bake resolver demand a .plain variant that does not exist). The top-right checkbox is a toggle-all (indeterminate when mixed).

GET /api/run payload — the display-relevant subset below (the full snapshot, including non-display fields like states[].action, is assembled by build_run_state):

{
  "characterId": "demo-hero",
  "runDir": "<abs path>",
  "baseUrl": "/run/base-source.png",        // base reference row; null when no base-source.*
  "cell": { "width": 256, "height": 256 },
  "pixelUnfake": { "logicalHeight": 48, "scale": 5, "source": "request", "label": "48px" },
                                            // or { "source": "auto", "label": "auto", "scale": <min measured k, ≥1> } — never null
  "fitPixelUnfake": true,                   // request opted into the deterministic pixel-unfake path
  "runRevision": "9f3c1a0b7e2d4c58",         // frame-content fingerprint of this generation; POST /api/curation echoes it (stale ⇒ 409)
  "hasAtlas": true,
  "iso": null,                               // sibling meta.json iso tile/anchor → ground-grid overlay
  "lang": "ko",
  "schemaVersion": 1,
  "states": [
    {
      "name": "down_walk",
      "pixelScale": 5,                       // request scale, or exact measured k — always ≥1, never null (k=1 = identity)
      "refs": [                              // generation-material chips
        { "role": "anchor", "name": "down_idle#2 · picked",  // live bake of the curated anchor frame
          "url": "/api/anchor?direction=down&v=9f3c1a0b7e2d4c58", "anchorFrame": true },
        { "role": "guide",  "name": "down_walk.png", "url": "/run/references/layout-guides/down_walk.png" }
      ],
      "fps": 8, "loop": true, "requestFrames": 6, "extractOk": true,
      "frames": [
        { "index": 0, "url": "/frames/down_walk/frame-0.png",
          "plainUrl": "/frames/down_walk/orig/frame-0.png",    // hi-res orig/ twin (else cell-sized .plain.png); present ⇒ toggle available
          "present": true, "label": "step-1",
          "size": [256, 256], "contentSize": [120, 210] }      // contentSize = alpha bbox, for size-parity review
      ]
    }
  ],
  "contract": { "base": true, "refs": true, "refsStates": 1, "grid": true, "sourceless": false },
                                            // self-report (§3): grid is always true (measurement cannot fail); sourceless=true when base+refs are both absent → server warns at startup
  "curation": { /* current sidecar snapshot, or empty */ }
}

pixelUnfake.scale is cell.height // fit.logical_height (integer floor), so the example's 256 // 48 = 5 (not 5.33 — floor); label is "<logical_height>px" and logicalHeight echoes fit.logical_height. states[].pixelScale mirrors that scale on a fit.pixel_unfake run, or carries the per-row auto-measured block pitch on a run with no pixel-unfake contract (import/plain), or null when a row's pitch cannot be measured. Real runs are usually smaller than this synthetic 256 example — the synthetic fixture anchor is cell 56 / logical 48 → 56 // 48 = 1.

Display invariants (enforced by the server, not by the launching agent):

  • The base row, chips, grid, and toggle are all derived from run-dir files — an agent cannot "forget" to set them up. If a source file is missing the element is simply absent; there is no per-agent styling step to get wrong.
  • contentSize (alpha bbox) is exposed so a reviewer can spot size-parity drift across a row without opening each frame.
  • Standalone image-candidate curation (icons / logos / drafts — not sprites) and the webview interaction model (select/reorder/transform, curation.json schema, multi-agent launch rules) live in curation.md; this section owns only the four display-contract elements above.

4. Import-run source rule (--pngs-dir)

An imported run (a folder of separate PNGs, no generation pipeline) must reach the same display contract as a real run: a base reference row and per-state generation-material chips. The importer treats source material as first-class, not just frames.

Import folder layout accepted by unpack_atlas_run.py --pngs-dir <dir>:

pngs/
  _base/<any>.png            # optional — identity/base image for the whole set
  <group-a>/                 # one subfolder = one curator row (state)
    1-name.png               # frames; numeric prefix sets play order
    2-name.png
    _refs/                   # optional — this row's generation material
      anchor-<name>.png      #   role = direction anchor
      basis-<name>.png       #   role = basis row
      guide-<name>.png       #   role = layout guide
  <group-b>/ ...
  meta.json                  # optional — human labels + iso tile/anchor (§3 grid overlay)

Mapping into the run dir (so both view code paths resolve identically):

  • pngs/_base/<img> → base-source.png → drives the base reference row (baseUrl).
  • pngs/<group>/<frames>.png → frames/<group>/frame-N.png → the row's frames.
  • pngs/<group>/_refs/<role>-<name>.png → references/imported/<group>/<role>-<name>.png → the row's generation-material chips. The role is the filename prefix and must be anchor / basis / guide (same vocabulary as §3, owned by curation.IMPORTED_REF_ROLES). A _refs file with any other prefix is malformed input: the importer fails loud (lists the offending files) — it never silently relabels an unknown role as guide.

serve_curation.py's _state_refs resolves chips from raw/ anchors for real runs and from references/imported/<group>/ for imported runs — one chip vocabulary, two sources, identical rendering. A _base/_refs-free import still works (frames only, no base row, no chips), but then the view honestly shows "no source material" rather than a divergent experience.

--force re-import is a writer-isolated, rollback-safe, reader-atomic rebuild. It validates all inputs, builds the new run into a staging dir, then publishes it over the run dir. A successful re-import reflects only the current input — removing a _base/_refs source and re-importing leaves no stale base-source.png / references/imported/* behind, so provenance (unpack-source.json) and the served view never disagree (Idempotency/SSoT: the result never depends on the prior out-dir state). A failed or invalid re-import (e.g. a bad _refs role) leaves the prior run byte-intact — it is never cleared-then-failed (write-side Atomicity: a rebuild fully succeeds or rolls back). The publish holds the run-dir single-writer lock in place throughout, so a concurrent writer cannot preempt (writer Isolation).

An import never touches its inputs. An input — --pngs-dir, --atlas, --manifest, the atlas a manifest names, and what the import reads in --pngs-dir (every frame, _base image, _refs PNG and meta.json, and every folder it reads one from), any of which may be a link — that is the run dir, lies inside it, goes through anything inside it, or holds it is refused before anything is made, with or without --force: a publish replaces the run dir's whole prior content entry by entry — a link as a link, so a path that goes through one breaks — and the run would otherwise be written into its input. An input is followed the way the system opens it (runio.follow_path): its path as given, made absolute but never resolved or folded, one entry at a time — every link (a Windows directory junction counts as one) and every folder it looks up, including a folder that a later .. leaves again. The refusal names the first entry it goes through inside the run dir, and a link loop is refused by name. A path that only passes through the run dir itself (run/../incoming) is not refused: the run dir stays where it is while its content is replaced. What is found in --pngs-dir is checked once all of it is found and is named in the refusal by where it was found. Folders are compared by real path and file identity (runio.same_folder, runio.inside_folder), so a link or a second spelling on a case-insensitive volume is the same folder. The run is built in a staging folder of its own beside the run dir and the prior content is moved aside into a backup folder of its own inside it (runio.new_stage: .<name>.<pid>-<random>.sg-staging, .sg-backup.<pid>-<random>). A folder that already has a staging or backup name, an input's or anyone else's, is never reused or removed: besides those two folders the run deletes only the prior content it replaces, and a failed publish puts every prior file back. The run dir's single-writer lock is the entry .sprite-gen.lock itself (runio.acquire_run_dir_lock, every writer): a link or a folder at that name is refused by name and never followed, read or removed, so reclaiming a stale lock deletes only a stale lock file. The run carries the run dir's name (character.id) and path (frames-manifest.json run_dir), never the staging folder's.

Reader isolation (named strategy: reader/writer locking). Every operation that republishes frames — a --force re-import and a re-extract (extract builds into a staging dir, then swaps frames/ into place) — holds the run dir's exclusive publish lock (a sidecar .<name>.sg-rwlock flock, runio.publish_guard) around the swap, while serve_curation reads (/api/run and run-dir file requests) under the matching shared read lock (runio.read_guard). So a webview serving that same run dir concurrently always sees a complete old-or-new snapshot — never a half-published (old/new-mixed or missing-file) state, and never a transient HTTP 500. The reader blocks only for the brief swap. The rwlock is a sidecar (beside the run dir), so it survives content swaps and is never itself published. Where fcntl is unavailable or the sidecar can't be created, the guard fails loud (raises runio.RWLockUnavailable) rather than degrading to a no-op: a no-op would be a failover that lets canonical truth change inside a read transaction (a reader could observe a half-published run), and the isolation contract permits an availability failover only when it stays observable and does not change canonical truth. The pipeline runs on platforms with fcntl advisory locks (macOS/Linux); a platform without them refuses the publish/read rather than silently serving a partial run.

The curation write (POST /api/curation) takes the same exclusive publish lock, so a select/reorder/transform autosave is serialized with a concurrent re-import; and the POST must echo the runRevision (a frame-content fingerprint) it was loaded with — a POST from a different run generation is rejected (HTTP 409). So a stale autosave from a webview still on a pre-re-import (or pre-re-extract) run can never apply old selections/transforms to new frames, even when the re-import keeps the same state names but swaps the candidate images (Consistency — run identity, not just state membership).

Load 쪽은 행 단위다: run_revision 이 어긋나도 각 행의 revision(원료 세그먼트 지문, curation.state_revision)이 현재의 접두면 그 행 큐레이션은 유지된다 — 같은 raw 를 새 엔진이 재유도(heal)해도 선택이 살아남는다. 드롭되는 행이 생기면 /api/run 의 curationDropped 로 웹뷰 배너에 보고된다 (조용한 소실 금지). 로드는 아무것도 쓰지 않는다 — 원문은 그대로 남아 있고, 실제로 덮이는 순간 writer 가 curation.stale-<hash>.json 으로 보존한다. 스키마/규칙 상세: curation.md.

5. Conformance status

All four contracts are enforced by the shipped scripts today:

  • Stage table (§1), folder tree (§2), and the base-row / chips / grid elements of §3.
  • The "off = original quality" toggle (§3): extract writes a hi-res orig/ twin the view prefers, so pp-off is crisp; the cell-sized .plain.png stays for the compose bake. Canonical frame-N.png bytes are unchanged (deterministic — verified byte-identical on re-extraction of hero v6/v7).
  • The --pngs-dir _base/_refs embedding (§4): imported runs reach the same base row + chips as real runs.
  • The view-contract self-report (§3): serve_curation logs base/refs/grid coverage at startup and warns on a sourceless view.

Verified end-to-end on three views — hero v6 (base=yes refs=12/12 grid=yes), synthetic fixture (refs=36/36, anchor/basis/guide chips across down/side/up), and a comprehensive _base+_refs import — plus a sourceless run that emits the warning.

6. Failed extract is atomic — no partial generation in frames/

Canonical frames/ only ever holds a complete generation. A failed extract — the first extract on a fresh run or a re-extract — publishes nothing to frames/ (strict whole-generation Atomicity: the operation fully succeeds or leaves canonical state untouched). A failed re-extract additionally leaves the prior complete generation byte-intact, and the frames publish stays reader-atomic under publish_guard (§4).

The per-state failure signal is not discarded — it is written outside frames/ as extract-failure.json in the run-dir root, so it stays observable (No Silent Fallback) and still drives the automatic correction loop:

  • extract-failure.json holds the union of the run's currently-unresolved per-state failures — ok:false, per-state errors/warnings — and the CLI exits 1.
  • The automatic correction loop consumes it: inspect._manifest_state_notes reads the per-state errors from extract-failure.json (alongside the published frames/frames-manifest.json row) to drive inspect → score → correction-hint → regeneration. So error-driven regeneration keeps its which state failed, and why signal even though frames/ holds only complete generations.
  • The evidence is maintained per state, because a subset --states extract (the formal single-row / auto-correction path) only determines the outcome of the states it targets: a target state that succeeds is removed, a target state that fails is (re)recorded, and states the attempt did not touch keep their prior failure. So a walk success never erases an unresolved idle failure, and an idle failure never overwrites a walk one. The file is deleted only once no per-state failure remains (Consistency — never re-flag a now-good state, never silently drop a still-broken one).
  • Advancing the two canonical surfaces is one transaction: extract swaps frames/ and (re)writes/removes extract-failure.json under a single publish_guard, rolling both back together on any in-process I/O failure (a raised exception), so a reader never sees a new generation beside a stale failure record. Readers that combine them (inspect / the correction loop, via inspect_run) hold the matching read_guard for the whole read. (This rollback covers raised exceptions; a hard process kill mid-swap is a known durability gap — see the guarantee boundary in §7.)
  • A complete generation is enforced beyond JSON schema: a finished-generation consumer (compose_* / export_pngs / preview) calls extract.require_frames_manifest, and serve_curation / inspect call extract.load_consistent_frames_manifest, which verify the manifest AGREES with the physical frame tree and the request — every request state has exactly one row, no physical frame dir is an orphan the manifest omits, and every row's canonical frames exist on disk. {"ok":true,"rows":[]} over real frames, a deleted frame, or frames with no manifest (an orphan, distinct from a fresh scaffold) all fail loud; compose_gif / export_pngs likewise fail on a missing selected frame instead of silently skipping it. A run with no generation at all (no manifest, no frames) still serves the request/state scaffold.
  • A corrupt canonical record fails loud on every path — the writer and every reader. Extract's subset-seeding + commit, inspect._manifest_state_notes, and every finished-generation consumer (compose_atlas / compose_cycle / compose_gif / export_pngs / preview via extract.require_frames_manifest, and serve_curation via extract.load_frames_manifest) go through the shared typed loaders (extract.load_frames_manifest / load_failure_evidence) that refuse an unreadable / unparseable / broken-schema record (must be a dict; errors/warnings/rows lists whose entries are non-empty strings / state-bearing objects; a frames manifest must be ok:true, failure evidence ok:false with non-empty state-scoped errors) rather than treating it as empty. Absence still returns empty (a run with no generation yet); only an existing-but-broken record fails loud. Silently reading a corrupt extract-failure.json as "no failures", or a corrupt frames/frames-manifest.json as "no prior rows" (then publishing an incomplete manifest that disagrees with the carried frame tree), is exactly the No-Silent-Fallback violation this forbids. A corrupt prior manifest fails a subset re-extract loud before it stages anything, so the prior generation stays byte-intact.
  • compose_atlas requires a complete generation: it fails loud if frames/frames-manifest.json is absent (a failed extract published none) and refuses a non-ok manifest, so a partial never becomes an atlas.

The curation view tolerates a run with no generation (no frames/, no manifest): serve_curation falls back to an empty row set and curation.run_revision treats the missing manifest as an empty fingerprint, so the view shows the request/state scaffold rather than erroring. Physical frames without a manifest are an orphan, not a scaffold — that fails loud (see the complete-generation bullet above).

7. Guarantee boundary — atomicity & concurrency (honest scope)

To avoid claiming guarantees the code does not provide (No Silent Fallback), this is the exact boundary of the run-dir's atomicity and concurrency guarantees. What is in force today:

  • In-process transaction rollback. The frames/ + extract-failure.json commit (§6) and the --force re-import publish (§4) roll back on any raised exception, leaving the prior generation byte-intact. atomic_write_text / os.replace make each file write torn-free. atomic_write_set extends the same mechanism to a set that only means anything together — the layer bake's sheets, manifests and the report naming them: everything is staged before anything is renamed in, so a write error partway through publishes nothing (a SIGKILL between renames stays out of scope, below).
  • Reader isolation. A publish holds the exclusive publish_guard for its swap; a reader sees a complete old-or-new snapshot, never a mix (§4). Where advisory locks are unavailable the guard fails loud (RWLockUnavailable), never a silent no-op. Every finished-generation consumer has exactly one named isolation strategy against a concurrent extract/import publish:
    • shared read_guard wrapping the whole manifest + curation + frame read — serve_curation (/api/run + static), inspect, preview, run-dir compose_gif, compose_cycle. They block only for the brief swap, then read a complete generation.
    • writer exclusion via the run-dir single-writer lock (acquire_run_dir_lock) — compose_atlas, export_pngs. They serialize with the extract writer, so they never overlap a publish at all. A consumer that only calls the manifest gate once but then reads the frame tree unguarded would leave a TOCTOU window; the full read must be inside the strategy.
  • Cross-process single-writer. .sprite-gen.lock blocks a second process from writing the same run dir (a link or a folder at that name is refused, never followed: §4). A process removes only the very lock entry it made, or judged stale to reclaim, and only while it still holds it — same device, inode and content, and release_run_dir_lock withdraws that lock's exit cleanup — while making, reclaiming and removing the entry queue on a kernel lock on the run dir itself, so among sprite-gen processes on one host, on a file system that locks folders, neither a released writer's exit nor a late reclaimer removes a lock another writer took meanwhile. A lock that names its holder's pid is reclaimed only when that process has ended on this host, asked without sending it anything: signal 0 on POSIX; on Windows, where os.kill(pid, 0) is CTRL_C_EVENT — a Ctrl+C to the console — the process is opened only to see whether it has ended, and one that cannot be opened (a system or another user's process) counts as alive, never as dead. Removing and holding belong to the process that made the entry: a hold is bound to the pid that took it, so a forked child never re-enters, releases or removes its parent's lock and is refused by it like any other writer. Where os.register_at_fork exists, a child forgets its parent's holds and exit cleanups and closes its copies of the run dir's kernel-lock descriptors at the fork, and the parent never locks a descriptor a Python fork may have copied before it was recorded: a fork that runs the hooks between reading the fork count and recording the descriptor (on any thread, a signal handler on the same thread included) makes the parent open another, and the parent opens none while another thread's fork that already ran the hooks has not returned — it waits for that fork, and fails loudly when the fork is still marked in progress after ten seconds. A release that fails that way keeps its lock: the process can release it again, and its exit cleanup still tries to (an entry it leaves when it ends is a dead holder's, reclaimed by the next writer). The parent unlocks a descriptor before taking it out of the record, even when an exception skipped the first unlock. So a holder killed inside that kernel lock, or thrown out of it by an exception, leaves it to no child that Python's fork hooks ran in and that does not return into the code the fork interrupted. Every guarantee in this paragraph holds except at three boundaries. A child forked by C code that skips Python's fork hooks: the pid check still keeps it from removing or re-entering the parent's lock, but it keeps any kernel-lock descriptor it inherited until it ends or execs, and a writer waits for it. A child forked in a signal handler that returns from the handler and goes on with the code the signal interrupted: it is a copy of the parent's flow, so the lock cannot tell it from the parent — there is always a bytecode boundary between the helper's last check and the system call it guards. Inside the lock helper it can remove whatever is at the lock name, a lock another writer took meanwhile included, and after the lock is taken it goes on writing the run dir as the parent; such a child must not return into code that uses the lock (a caller's contract). An exception that a signal handler raises inside runio's fork hooks: CPython reports it and goes on with the fork, so that fork may go unseen by a parent opening its kernel lock, or leave a mark that makes the process's other threads fail loudly as above. The pipeline's one worker owns one character folder rule (§2, SKILL.md) is what excludes concurrent writers on the same run dir in the first place. Same-process re-entry is intentionally allowed so one interpreter can run prepare → extract → compose in sequence.

What is intentionally out of scope for this local, single-user, re-runnable tool — and so not claimed here (a decision, not a deferral: maintainer 2026-07-12):

  • Process-kill durability. A hard SIGKILL between the commit's rename steps can leave a new generation beside a stale extract-failure.json plus an orphan .sg-backup. This is not silent corruption: the consistency gate (§6) catches the mixed state and fails loud, and a re-run fixes it (the next extract's cleanup reconciles the leftover .sg-backup / .sg-staging). A journal / self-heal replay protocol would auto-heal it instead, but that is database-grade durability that a local sprite-curation tool does not need — observable-fail-loud + re-run is the deliberate design. In-process rollback (above) still covers every raised-exception case.
  • Thread-level write isolation. .sprite-gen.lock re-entry is keyed per process, not per thread. This is a non-scenario under the pipeline's one-worker-owns-one-folder rule (§2, SKILL.md): concurrent writers on the same run dir are already excluded, and same-process re-entry is the intended path for one interpreter to run prepare → extract → compose in sequence. A thread-aware per-run mutex would only matter for a multi-threaded server host, which is not this tool.

Both are deliberate boundaries, not TODOs; §4/§6's atomicity claims are scoped to the in-process cases above and do not contradict this. If sprite-gen is ever re-homed as a multi-user or server service, revisit both here.

Related

  • ../SKILL.md — behavior contract (Workflow, Base Lock Gate, Runtime Contract)
  • architecture.md — how the code realizes these contracts (stage internals, lock, extraction, pixel-unfake path)
  • curation.md — webview interaction model, curation.json schema, standalone image-candidate path, multi-agent launch rules
  • recolor.md — palette-swap bake (variants/), report schema, colourway adopt
  • pixel-unfake.md — fit/pixel_unfake behavior + plain-twin bake decision
  • directional-anchor-workflow.md — directional/45° anchor chains that name the raw/ anchors §3 resolves into chips