Skip to content

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

retire(rig): 3.0.0 removes layer-tracks — compose-layers, its two modules, docs/layer-tracks.md, and the request keys rig, layers and states.*.track, which an old run reads through the retired-key path

Soohong Kim59aa176b1c4d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e511993..5faa809 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,27 @@
All notable public changes to `sprite-gen` are recorded here. Versions track the `version:` field in `SKILL.md` and `pyproject.toml`.
+## v3.0.0 - Remove rig layer composition
+
+**Upgrading from 2.46.0: `sprite-gen compose-layers` and its other launch forms are removed, and rig layer declarations are no longer read.** `compose-atlas` no longer writes a manifest `rig` block or `animation.rows.<state>.track` for a run that declared a rig. Runs that never declared `rig`, `layers` or a state `track` get the same manifest as before. Existing run files and `layers/` folders stay on disk.
+
+### Breaking
+
+The rig layer feature has no replacement in 3.0.0:
+
+| Removed | Use |
+|---|---|
+| `sprite-gen compose-layers`, `python -m sprite_gen.compose.compose_layers`, `scripts/compose_layers.py` | No replacement. The CLI verb now ends as an unknown command with argparse exit code 2. |
+| `sprite_gen/compose/layers.py` (declaration checks for rig profiles, row tracks and composite stacks), `sprite_gen/compose/compose_layers.py` (baking declared stacks into `<run>/layers/`) | No replacement. |
+| `sprite-request.json` keys `rig`, `layers` and `states.<state>.track` | Remove them with `sprite-gen migrate-request <run> --apply`. |
+| `sprite_gen.spec.runio.normalize_retired_fit_keys` | `normalize_retired_keys`, which returns a list of keys moved or left out, or an empty list. |
+| `docs/layer-tracks.md` | No replacement. Its links are gone from the other docs, READMEs and `SKILL.md`; the skill description no longer lists "rig layers". |
+
+- `prepare` drops the retired keys from `--request` and `--request-json`, naming them in its existing stderr note. Code no longer reads them. On the first read of an old run's request, the process prints one stderr line naming the keys, treats them as absent in memory and leaves the file byte for byte unchanged. Unrelated request rewrites, including reroll and interpolate takes and curation fps edits, preserve those keys as they were.
+- `sprite-gen migrate-request <run>` lists the keys it would remove without writing. `--apply` removes them from the file; a second apply has nothing to move. The changed bytes move `run_revision`, and the command names the curation rows it will drop before writing. The command also retains its existing `fit.pixel_perfect` to `fit.pixel_unfake` migration. `runio.migrate_request_file` now returns the list of keys moved or left out instead of a boolean.
+- Talking face parts are planned as a new feature in a later 3.x minor release.
+- **Tests**: Added `tests/spec/test_request_retired_rig_keys.py` to check the one-time stderr note and unchanged old request bytes, migration dry runs and repeated applies, preservation on unrelated edits, and named drops in `prepare`. Removed `tests/compose/test_layer_compose.py`, `tests/compose/test_layer_contract.py` and `tests/packaging/test_layer_cli_entrypoint.py` with the feature.
+
## v2.46.0 - Changed loop and framing defaults, recognition of cyan or yellow leaning green border keys, Breathe smooth mode and Sway commands
**Upgrading from 2.45.3: Some existing runs produce different bytes because defaults changed.**
diff --git a/README.es.md b/README.es.md
index e0a96e0..7587e02 100644
--- a/README.es.md
+++ b/README.es.md
@@ -54,7 +54,7 @@ flowchart LR
end
subgraph D["D · posprocesado"]
direction LR
- d1[recolor] ~~~ d2[compose-layers] ~~~ d3[export-*]
+ d1[recolor] ~~~ d2[export-*]
end
subgraph E["E · herramientas de recursos (independientes)"]
e1[background-tile] ~~~ e2[shadow] ~~~ e3[inspect-motion]
@@ -70,7 +70,7 @@ flowchart LR
| **A · filas de atlas** | una imagen fija + una lista de estados → `sprite-sheet-alpha.png` + `manifest.json.frame_layout`, con **Breathe** horneado en las poses de reposo | [run-contract](docs/run-contract.md) · [breathing](docs/breathing.md) |
| **B · vídeo → bucle** | una imagen fija → por estado, un GIF / WebP / tira transparente sin costuras, animado por Grok Imagine y cortado en su periodo real | [video-pipeline](docs/video-pipeline.md) · [video](docs/video.md) |
| **C · utilidades** | una imagen importada u hoja en cuadrícula → recortes transparentes limpios; un atlas terminado → una ejecución lista para curación | [sheet-slicing](docs/sheet-slicing.md) · [curation](docs/curation.md) |
-| **D · posprocesado** | una hoja terminada → combinaciones de color deterministas, composiciones de capas de rig, exportaciones a Aseprite / Phaser / Flame | [recolor](docs/recolor.md) · [layer-tracks](docs/layer-tracks.md) · [engine-export](docs/engine-export.md) |
+| **D · posprocesado** | una hoja terminada → combinaciones de color deterministas, exportaciones a Aseprite / Phaser / Flame | [recolor](docs/recolor.md) · [engine-export](docs/engine-export.md) |
| **E · herramientas de recursos** | PNG o animaciones independientes → mosaicos repetibles, sombras proyectadas, mediciones de movimiento/contacto | [asset-tools](docs/asset-tools.md) |
| **S · escena** | recursos existentes + colocación, cámara e iluminación → fotogramas PNG, MP4/GIF, metadatos de inspección y colocación | [scene](docs/scene.md) |
@@ -131,7 +131,6 @@ sprite-gen unpack-atlas --atlas sheet.png # atlas terminado → ejec
```bash
sprite-gen recolor-palette --base <run>/sprite-sheet-alpha.png --out palette.draft.json
sprite-gen recolor --run-dir <run> --spec recolor.spec.json # → <run>/variants/
-sprite-gen compose-layers --run-dir <run> # ejecuciones de rig: pilas declaradas → <run>/layers/
sprite-gen export-aseprite --run-dir <run> # JSON de Aseprite para Phaser / Flame
```
diff --git a/README.fr.md b/README.fr.md
index 838dd58..c1754c5 100644
--- a/README.fr.md
+++ b/README.fr.md
@@ -54,7 +54,7 @@ flowchart LR
end
subgraph D["D · post-traitement"]
direction LR
- d1[recolor] ~~~ d2[compose-layers] ~~~ d3[export-*]
+ d1[recolor] ~~~ d2[export-*]
end
subgraph E["E · outils d'assets (indépendants)"]
e1[background-tile] ~~~ e2[shadow] ~~~ e3[inspect-motion]
@@ -70,7 +70,7 @@ flowchart LR
| **A · lignes d'atlas** | une image fixe + une liste d'états → `sprite-sheet-alpha.png` + `manifest.json.frame_layout`, avec **Breathe** cuit sur les poses idle | [run-contract](docs/run-contract.md) · [breathing](docs/breathing.md) |
| **B · vidéo → boucle** | une image fixe → par état, un GIF / WebP / bande transparent sans raccord, animé par Grok Imagine et coupé à sa véritable période | [video-pipeline](docs/video-pipeline.md) · [video](docs/video.md) |
| **C · utilitaires** | une image importée ou une feuille en grille → des découpes transparentes propres ; un atlas terminé → un run prêt pour la curation | [sheet-slicing](docs/sheet-slicing.md) · [curation](docs/curation.md) |
-| **D · post-traitement** | une feuille terminée → des variantes de couleurs déterministes, des composites de couches de rig, des exports Aseprite / Phaser / Flame | [recolor](docs/recolor.md) · [layer-tracks](docs/layer-tracks.md) · [engine-export](docs/engine-export.md) |
+| **D · post-traitement** | une feuille terminée → des variantes de couleurs déterministes, des exports Aseprite / Phaser / Flame | [recolor](docs/recolor.md) · [engine-export](docs/engine-export.md) |
| **E · outils d'assets** | des PNG ou animations indépendants → tuiles répétables, ombres projetées, mesures de mouvement/contact | [asset-tools](docs/asset-tools.md) |
| **S · scène** | assets existants + placement, caméra et éclairage → frames PNG, MP4/GIF, métadonnées d'inspection et de placement | [scene](docs/scene.md) |
@@ -131,7 +131,6 @@ sprite-gen unpack-atlas --atlas sheet.png # atlas terminé → run p
```bash
sprite-gen recolor-palette --base <run>/sprite-sheet-alpha.png --out palette.draft.json
sprite-gen recolor --run-dir <run> --spec recolor.spec.json # → <run>/variants/
-sprite-gen compose-layers --run-dir <run> # runs de rig : piles déclarées → <run>/layers/
sprite-gen export-aseprite --run-dir <run> # JSON Aseprite pour Phaser / Flame
```
diff --git a/README.ja.md b/README.ja.md
index abd8d6e..c99dac0 100644
--- a/README.ja.md
+++ b/README.ja.md
@@ -54,7 +54,7 @@ flowchart LR
end
subgraph D["D · ポストプロセス"]
direction LR
- d1[recolor] ~~~ d2[compose-layers] ~~~ d3[export-*]
+ d1[recolor] ~~~ d2[export-*]
end
subgraph E["E · アセットツール (独立)"]
e1[background-tile] ~~~ e2[shadow] ~~~ e3[inspect-motion]
@@ -70,7 +70,7 @@ flowchart LR
| **A · アトラス行** | 一枚の静止画 + ステート一覧 → `sprite-sheet-alpha.png` + `manifest.json.frame_layout`、アイドルポーズには **Breathe** を焼き込み | [run-contract](docs/run-contract.md) · [breathing](docs/breathing.md) |
| **B · 動画 → ループ** | 一枚の静止画 → ステートごとに、Grok Imagine がアニメートし実周期でカットされたシームレスな透過 GIF / WebP / ストリップ | [video-pipeline](docs/video-pipeline.md) · [video](docs/video.md) |
| **C · ユーティリティ** | 取り込んだ画像やグリッドシート → きれいな透過カット。完成したアトラス → キュレーション可能な run | [sheet-slicing](docs/sheet-slicing.md) · [curation](docs/curation.md) |
-| **D · ポストプロセス** | 完成したシート → 決定論的カラーウェイ、リグレイヤー合成、Aseprite / Phaser / Flame エクスポート | [recolor](docs/recolor.md) · [layer-tracks](docs/layer-tracks.md) · [engine-export](docs/engine-export.md) |
+| **D · ポストプロセス** | 完成したシート → 決定論的カラーウェイ、Aseprite / Phaser / Flame エクスポート | [recolor](docs/recolor.md) · [engine-export](docs/engine-export.md) |
| **E · アセットツール** | 独立した PNG やアニメーション → 繰り返しタイル、投影された影、モーション/接地の計測 | [asset-tools](docs/asset-tools.md) |
| **S · シーン** | 既存アセット + 配置・カメラ・ライティング → PNG フレーム、MP4/GIF、検査と配置のメタデータ | [scene](docs/scene.md) |
@@ -131,7 +131,6 @@ sprite-gen unpack-atlas --atlas sheet.png # 完成したアトラス
```bash
sprite-gen recolor-palette --base <run>/sprite-sheet-alpha.png --out palette.draft.json
sprite-gen recolor --run-dir <run> --spec recolor.spec.json # → <run>/variants/
-sprite-gen compose-layers --run-dir <run> # リグ run: 宣言されたスタック → <run>/layers/
sprite-gen export-aseprite --run-dir <run> # Phaser / Flame 向け Aseprite JSON
```
diff --git a/README.ko.md b/README.ko.md
index c838ceb..accd57f 100644
--- a/README.ko.md
+++ b/README.ko.md
@@ -60,7 +60,7 @@ flowchart LR
end
subgraph D["D · 후처리"]
direction LR
- d1[recolor] ~~~ d2[compose-layers] ~~~ d3[export-*]
+ d1[recolor] ~~~ d2[export-*]
end
subgraph E["E · 에셋 도구 (독립)"]
e1[background-tile] ~~~ e2[shadow] ~~~ e3[inspect-motion]
@@ -76,7 +76,7 @@ flowchart LR
| **A · 아틀라스 행** | 정지 이미지 한 장 + 상태 목록 → `sprite-sheet-alpha.png` + `manifest.json.frame_layout`, 아이들 포즈에 **Breathe** 가 구워짐 | [run-contract](docs/run-contract.md) · [breathing](docs/breathing.md) |
| **B · 비디오 → 루프** | 정지 이미지 한 장 → 상태별로 이음매 없는 투명 GIF / WebP / 스트립, 그록 이매진이 움직이고 실제 주기에서 잘라냄 | [video-pipeline](docs/video-pipeline.md) · [video](docs/video.md) |
| **C · 유틸리티** | 가져온 이미지 또는 그리드 시트 → 깨끗한 투명 컷; 완성된 아틀라스 → 큐레이터가 바로 쓸 수 있는 런 | [sheet-slicing](docs/sheet-slicing.md) · [curation](docs/curation.md) |
-| **D · 후처리** | 완성된 시트 → 결정론적 컬러웨이, 리그 레이어 합성, Aseprite / Phaser / Flame 익스포트 | [recolor](docs/recolor.md) · [layer-tracks](docs/layer-tracks.md) · [engine-export](docs/engine-export.md) |
+| **D · 후처리** | 완성된 시트 → 결정론적 컬러웨이, Aseprite / Phaser / Flame 익스포트 | [recolor](docs/recolor.md) · [engine-export](docs/engine-export.md) |
| **E · 에셋 도구** | 독립적인 PNG 또는 애니메이션 → 반복 타일, 투영 그림자, 모션/접지 측정 | [asset-tools](docs/asset-tools.md) |
| **S · 씬** | 기존 에셋 + 배치, 카메라, 조명 → PNG 프레임, MP4/GIF, 검사 및 배치 메타데이터 | [scene](docs/scene.md) |
@@ -137,7 +137,6 @@ sprite-gen unpack-atlas --atlas sheet.png # 완성된 아틀라스
```bash
sprite-gen recolor-palette --base <run>/sprite-sheet-alpha.png --out palette.draft.json
sprite-gen recolor --run-dir <run> --spec recolor.spec.json # → <run>/variants/
-sprite-gen compose-layers --run-dir <run> # 리그 런: 선언된 스택 → <run>/layers/
sprite-gen export-aseprite --run-dir <run> # Phaser / Flame 용 Aseprite JSON
```
diff --git a/README.md b/README.md
index bfbca08..7024d7e 100644
--- a/README.md
+++ b/README.md
@@ -67,7 +67,7 @@ flowchart LR
end
subgraph D["D · post-processing"]
direction LR
- d1[recolor] ~~~ d2[compose-layers] ~~~ d3[export-*]
+ d1[recolor] ~~~ d2[export-*]
end
subgraph E["E · asset tools (independent)"]
e1[background-tile] ~~~ e2[shadow] ~~~ e3[inspect-motion]
@@ -83,7 +83,7 @@ flowchart LR
| **A · atlas rows** | one still + a list of states → `sprite-sheet-alpha.png` + `manifest.json.frame_layout`, with **Breathe** baked on idle poses | [run-contract](docs/run-contract.md) · [breathing](docs/breathing.md) |
| **B · video → loop** | one still → per state, a seamless transparent GIF / WebP / strip, animated by Grok Imagine and cut at its true period | [video-pipeline](docs/video-pipeline.md) · [video](docs/video.md) |
| **C · utilities** | an imported image or grid sheet → clean transparent cuts; a finished atlas → a curator-ready run | [sheet-slicing](docs/sheet-slicing.md) · [curation](docs/curation.md) |
-| **D · post-processing** | a finished sheet → deterministic colourways, rig layer composites, Aseprite / Phaser / Flame exports | [recolor](docs/recolor.md) · [layer-tracks](docs/layer-tracks.md) · [engine-export](docs/engine-export.md) |
+| **D · post-processing** | a finished sheet → deterministic colourways, Aseprite / Phaser / Flame exports | [recolor](docs/recolor.md) · [engine-export](docs/engine-export.md) |
| **E · asset tools** | independent PNGs or animations → repeating tiles, projected shadows, motion/contact measurements | [asset-tools](docs/asset-tools.md) |
| **S · scene** | existing assets + placement, camera and lighting → PNG frames, MP4/GIF, inspection and placement metadata | [scene](docs/scene.md) |
@@ -147,7 +147,6 @@ sprite-gen unpack-atlas --atlas sheet.png # finished atlas → curat
```bash
sprite-gen recolor-palette --base <run>/sprite-sheet-alpha.png --out palette.draft.json
sprite-gen recolor --run-dir <run> --spec recolor.spec.json # → <run>/variants/
-sprite-gen compose-layers --run-dir <run> # rig runs: declared stacks → <run>/layers/
sprite-gen export-aseprite --run-dir <run> # Aseprite JSON for Phaser / Flame
```
diff --git a/README.zh-Hans.md b/README.zh-Hans.md
index e25c796..9d2c2ab 100644
--- a/README.zh-Hans.md
+++ b/README.zh-Hans.md
@@ -54,7 +54,7 @@ flowchart LR
end
subgraph D["D · 后期处理"]
direction LR
- d1[recolor] ~~~ d2[compose-layers] ~~~ d3[export-*]
+ d1[recolor] ~~~ d2[export-*]
end
subgraph E["E · 素材工具(独立)"]
e1[background-tile] ~~~ e2[shadow] ~~~ e3[inspect-motion]
@@ -70,7 +70,7 @@ flowchart LR
| **A · 图集行** | 一张静态图 + 一组状态列表 → `sprite-sheet-alpha.png` + `manifest.json.frame_layout`,并在待机姿势上烘焙 **Breathe** | [run-contract](docs/run-contract.md) · [breathing](docs/breathing.md) |
| **B · 视频 → 循环** | 一张静态图 → 每个状态一份无缝透明 GIF / WebP / 条带,由 Grok Imagine 驱动动画并按其真实周期裁切 | [video-pipeline](docs/video-pipeline.md) · [video](docs/video.md) |
| **C · 实用工具** | 一张导入图像或网格表 → 干净的透明切片;一份成品图集 → 可供策展的运行目录 | [sheet-slicing](docs/sheet-slicing.md) · [curation](docs/curation.md) |
-| **D · 后期处理** | 一份成品表 → 确定性配色方案、骨骼图层合成、Aseprite / Phaser / Flame 导出 | [recolor](docs/recolor.md) · [layer-tracks](docs/layer-tracks.md) · [engine-export](docs/engine-export.md) |
+| **D · 后期处理** | 一份成品表 → 确定性配色方案、Aseprite / Phaser / Flame 导出 | [recolor](docs/recolor.md) · [engine-export](docs/engine-export.md) |
| **E · 素材工具** | 独立的 PNG 或动画 → 可重复平铺图、投影阴影、运动/接地测量 | [asset-tools](docs/asset-tools.md) |
| **S · 场景** | 现有素材 + 摆放、相机与灯光 → PNG 帧、MP4/GIF、检查与摆放元数据 | [scene](docs/scene.md) |
@@ -131,7 +131,6 @@ sprite-gen unpack-atlas --atlas sheet.png # 成品图集 → 可供
```bash
sprite-gen recolor-palette --base <run>/sprite-sheet-alpha.png --out palette.draft.json
sprite-gen recolor --run-dir <run> --spec recolor.spec.json # → <run>/variants/
-sprite-gen compose-layers --run-dir <run> # 骨骼运行:声明的图层栈 → <run>/layers/
sprite-gen export-aseprite --run-dir <run> # 供 Phaser / Flame 使用的 Aseprite JSON
```
diff --git a/SKILL.md b/SKILL.md
index 3d442ac..582698d 100644
--- a/SKILL.md
+++ b/SKILL.md
@@ -1,7 +1,7 @@
---
name: sprite-gen
-version: 2.46.0
-description: "Generates images and game sprites through GPT or Grok with guided provider choices, separate saved defaults, automatic cleanup and optional curation. Handles sprite requests, ordinary image generation/editing, typography logos (로고, 타이포그래피, 타이틀 글자, 타이틀 로고, wordmark, logo, title lettering: a title screen drawn with the title in it, its lettering lifted out transparent), standalone image-to-video clips (i2v, animate this still, 그록 영상, 이매진 비디오, 스틸 움직여줘, first/last frame, reference-to-video, 영상 이어붙이기, 영상 편집, extend/edit a clip), clips from a video MCP on the agent (ZCRE, 지크 MCP), chroma removal, animation atlases, video loops, 큐레이션뷰, image candidates, 팔레트 스왑, palette swap, recolor, rig layers, engine exports, repeating backgrounds, projected shadows, motion/contact inspection and optional scene composition from existing assets."
+version: 3.0.0
+description: "Generates images and game sprites through GPT or Grok with guided provider choices, separate saved defaults, automatic cleanup and optional curation. Handles sprite requests, ordinary image generation/editing, typography logos (로고, 타이포그래피, 타이틀 글자, 타이틀 로고, wordmark, logo, title lettering: a title screen drawn with the title in it, its lettering lifted out transparent), standalone image-to-video clips (i2v, animate this still, 그록 영상, 이매진 비디오, 스틸 움직여줘, first/last frame, reference-to-video, 영상 이어붙이기, 영상 편집, extend/edit a clip), clips from a video MCP on the agent (ZCRE, 지크 MCP), chroma removal, animation atlases, video loops, 큐레이션뷰, image candidates, 팔레트 스왑, palette swap, recolor, engine exports, repeating backgrounds, projected shadows, motion/contact inspection and optional scene composition from existing assets."
license: Apache-2.0
depends_on:
required_bins:
@@ -37,7 +37,6 @@ depends_on:
- scripts/unpack_atlas_run.py
- scripts/export_curated_pngs.py
- scripts/recolor.py
- - scripts/compose_layers.py
modes:
default: component-row
---
@@ -131,7 +130,6 @@ hold the arms still, and check the loop with `handed-check --state walk`.
| Curation view or existing image candidates | `curation`, `unpack-atlas --pngs-dir` | [curation](docs/curation.md) |
| Uniform background removal or imported sheets | `cutout`, `slice-sheet` | [sheet-slicing](docs/sheet-slicing.md) |
| Palette swap | `sprite-gen recolor-palette`, `sprite-gen recolor` | [recolor](docs/recolor.md) |
-| Rig layer composition | `sprite-gen compose-layers` | [layer-tracks](docs/layer-tracks.md) |
| Idle breathing as a post-processing layer (the Breathe layer): pixel (default, pixel art) or smooth (large illustrations, video frames: head fixed, chest breathes, shoulders follow; facing values for a turned body) | curation sidecar, baked by compose; or `sprite-gen breathe <frames> <out>` on a folder of loop frames | [breathing](docs/breathing.md) |
| Engine exports | `export-aseprite`, `export-pngs` | [engine-export](docs/engine-export.md) |
| Background recipe or repeating tile | existing `gen` / `cutout`, then optional `background-tile` | [asset-tools](docs/asset-tools.md#background-recipe) |
diff --git a/docs/README.md b/docs/README.md
index b8a576c..6fdb6f0 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -26,7 +26,7 @@ flowchart LR
end
subgraph D["D · post-processing"]
direction LR
- d1[recolor] ~~~ d2[compose-layers] ~~~ d3["breathe (compose)"] ~~~ d4[export-*]
+ d1[recolor] ~~~ d2["breathe (compose)"] ~~~ d3[export-*]
end
subgraph E["E · asset tools (independent)"]
e1[background-tile] ~~~ e2[shadow] ~~~ e3[inspect-motion]
@@ -42,7 +42,7 @@ flowchart LR
| **A · atlas rows** — one still becomes a runtime sprite sheet | [run-contract.md](run-contract.md) | `prepare` → `gen` / `gen-set` → `extract` → `compose-atlas`; optional `curation` and recompose |
| **B · video → loop** — one still becomes transparent motion loops | [video-pipeline.md](video-pipeline.md) | `video-canvas` → `video` (or `video-prompt` and a video MCP on your agent) → `video-frames` → `video-loop`, `video-set`, `video-cycle-align`, `video-sway`, the Sway layer (`video-sway-inspect` shows every cell of it and moves nothing; old names `video-follow`, `video-follow-inspect`), `video-set-sheet` (a set's directions on one sheet, on one ground line), `video-stop` (a walk or run that stops, from the clip's own start played backwards); `handed-check` for an item on one side |
| **C · utilities** — imported images in, clean cuts out | [sheet-slicing.md](sheet-slicing.md) | `cutout`, `slice-sheet`, `ui-kit`, `unpack-atlas` |
-| **D · post-processing** — finished sheets, refined | [recolor.md](recolor.md) | `recolor`, `recolor-palette`, `compose-layers`, breathing (compose, or `breathe` on a folder of frames), `export-pngs`, `export-aseprite` |
+| **D · post-processing** — finished sheets, refined | [recolor.md](recolor.md) | `recolor`, `recolor-palette`, breathing (compose, or `breathe` on a folder of frames), `export-pngs`, `export-aseprite` |
| **E · asset tools** — independent background, shadow and motion tools | [asset-tools.md](asset-tools.md) | `background-tile`, `shadow`, `inspect-motion` |
| **S · scene** — optional composition of existing assets | [scene.md](scene.md) | `scene-render`, `scene-inspect` |
@@ -103,7 +103,6 @@ grouping is derived from `sprite_gen/_modules.py`, the one taxonomy table.
| Doc | Owns |
|---|---|
| [recolor.md](recolor.md) | Deterministic palette-swap bake, colourway pick, `variants/` and its report |
-| [layer-tracks.md](layer-tracks.md) | Rig runs: `rig` / `track` / `layers` contract and `compose-layers` |
| [engine-export.md](engine-export.md) | Aseprite-compatible export for Phaser and Flame |
| [`game-pack`](game-pack.md) | Compile sprite assets into deterministic multi-page texture atlases and manifests. |
diff --git a/docs/architecture.md b/docs/architecture.md
index fa8bae7..74a0eda 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -85,7 +85,7 @@ flowchart TD
CUT["cutout<br/>white matte / chroma engine"] ~~~ SLICE["slice-sheet"] ~~~ UNPACK["unpack-atlas"]
end
subgraph D["D · post-processing"]
- RECOLOR["recolor · recolor-palette"] ~~~ LAYERS["compose-layers"] ~~~ EXPORT["export-pngs · export-aseprite"]
+ RECOLOR["recolor · recolor-palette"] ~~~ EXPORT["export-pngs · export-aseprite"]
end
ATLAS --> D
UNPACK --> CURATE
@@ -130,17 +130,6 @@ block on a running compose. The curation write is, however, serialized against a
no longer matches is rejected — a stale autosave cannot apply old selections to a
re-imported run's frames, even when it keeps the same state names (run-contract.md §4).
-`compose_layers.py` (the optional composite bake) is another consumer of those same
-shared primitives: it resolves a curated instance exactly as `compose_atlas` does and
-then stacks instances by integer translation, so a composite is a combination of what
-the atlas bakes rather than a second extraction path. Its declaration half,
-`layers.py`, is filesystem-free on purpose — the request is validated before a run dir
-is touched, and every entry point calls that one validator (`layer-tracks.md` §6):
-`prepare` when it carries the declared layer keys into `sprite-request.json`,
-`compose_atlas` before it publishes a rig block, and `compose_layers` before it bakes.
-The bake publishes its sheets, manifests and report through a single
-`runio.atomic_write_set`, so the set that only means anything together lands together.
-
The automatic correction loop is intentionally split into three owners:
`inspect.py` measures deterministic signals (frame count, RGB histogram, dHash,
motion presence, centroid jitter, existing extraction warnings), `score.py`
@@ -423,11 +412,6 @@ Required fields:
- `frame_layout` also carries `sheetWidth/sheetHeight/cellWidth/cellHeight`
- `curation_applied` records whether a sidecar was baked; `frame_variant`
records which frame variant (canonical / plain) was baked
-- **rig runs only** (`sprite_gen/compose/layers.py`, `compose_layers.py`): `rig.profile` +
- `rig.landmarks.<state>[i]` — atlas-absolute integer pivots indexed by play
- position, so they zip 1:1 against `frame_layout.rows.<state>` — and
- `animation.rows.<state>.track`. A run that declares no rig produces exactly the
- key set above; `layer-tracks.md` §1 owns that boundary
Static fallback is allowed only as explicit survival output when generation is
blocked; it must not create `sprite-sheet-alpha.png` and is not a pass.
@@ -477,6 +461,5 @@ whole atlas in a single generation.
- [`curation.md`](curation.md) — webview usage + `curation.json` field semantics
- [`chroma-alpha.md`](chroma-alpha.md) — chroma key selection + alpha cleanup contract
- [`gen.md`](gen.md) — provider CLI, verified PNG/report contract, and `image-gen` shuttle boundary
-- [`layer-tracks.md`](layer-tracks.md) — optional rig profiles, row track kinds, deterministic composite stacks
- [`directional-anchor-workflow.md`](directional-anchor-workflow.md) — 방향성/45도 앵커 체인
- [`locomotion-curation.md`](locomotion-curation.md) — selected-cycle + clean GIF export
diff --git a/docs/atlas-workflow.md b/docs/atlas-workflow.md
index 4c3a071..f73692f 100644
--- a/docs/atlas-workflow.md
+++ b/docs/atlas-workflow.md
@@ -24,4 +24,4 @@ $SPRITE_GEN_ROOT/.venv/bin/sprite-gen compose-gif --run-dir /absolute/run --out-
$SPRITE_GEN_ROOT/.venv/bin/sprite-gen inspect --run-dir /absolute/run
```
-The runtime consumes `manifest.json.frame_layout`; it does not infer a grid from alpha. AI operates only at generation. Frame cleanup and atlas assembly remain deterministic, with one writer per run and atomic publication. [architecture](architecture.md) explains these boundaries. [subject-profiles](subject-profiles.md) covers effects and sparse subjects. [breathing](breathing.md), [recolor](recolor.md) and [layer-tracks](layer-tracks.md) own optional post-processing; none is an extra default question for every sprite request.
+The runtime consumes `manifest.json.frame_layout`; it does not infer a grid from alpha. AI operates only at generation. Frame cleanup and atlas assembly remain deterministic, with one writer per run and atomic publication. [architecture](architecture.md) explains these boundaries. [subject-profiles](subject-profiles.md) covers effects and sparse subjects. [breathing](breathing.md) and [recolor](recolor.md) own optional post-processing; neither is an extra default question for every sprite request.
diff --git a/docs/layer-tracks.md b/docs/layer-tracks.md
deleted file mode 100644
index 190a119..0000000
--- a/docs/layer-tracks.md
+++ /dev/null
@@ -1,486 +0,0 @@
-# Layer Tracks — rig · track · composite contract (SSoT)
-
-> Owns: Rig runs: `rig` / `track` / `layers` contract and `compose-layers` · Index: [docs/README.md](README.md)
-
-> Status: **contract** (normative). This doc owns the optional layer feature: the
-> character rig profile, the per-row track kind, the composite stack, and what a
-> layer bake is allowed to touch.
->
-> Precedence, same as the rest of the docs: [`../SKILL.md`](../SKILL.md) owns the
-> behavior contract, [`run-contract.md`](run-contract.md) owns the structural
-> contract (stage table, run-dir tree, view payload), and
-> [`architecture.md`](architecture.md) only ever describes the code. This doc owns
-> the layer vocabulary and its boundaries; where it touches the run-dir tree or the
-> stage table, `run-contract.md` still wins.
->
-> Declaration validation is implemented by [`../sprite_gen/compose/layers.py`](../sprite_gen/compose/layers.py)
-> and pinned by `tests/test_layer_contract.py`; the composite bake is
-> [`../sprite_gen/compose/compose_layers.py`](../sprite_gen/compose/compose_layers.py), pinned by
-> `tests/test_layer_compose.py`.
-
-## Contents
-
-- [0. One sentence](#0-one-sentence)
-- [1. The compatibility rule (read this first)](#1-the-compatibility-rule-read-this-first)
-- [2. Ownership audit — what already owns what](#2-ownership-audit-what-already-owns-what)
- - [Boundary findings](#boundary-findings)
-- [3. Request schema extension](#3-request-schema-extension)
- - [3.1 Profiles and landmarks](#31-profiles-and-landmarks)
- - [3.2 Tracks](#32-tracks)
- - [3.3 Stack elements](#33-stack-elements)
-- [4. Composition contract (deterministic)](#4-composition-contract-deterministic)
-- [5. Output and manifest extension](#5-output-and-manifest-extension)
-- [6. Validation contract](#6-validation-contract)
-- [7. Using it — the CLI and where it sits in the run](#7-using-it-the-cli-and-where-it-sits-in-the-run)
- - [7.1 Declaring](#71-declaring)
- - [7.2 Baking](#72-baking)
-- [8. Out of scope](#8-out-of-scope)
-- [Related](#related)
-
-## 0. One sentence
-
-A run may declare a **rig** (a character type profile plus integer landmarks per
-frame) and a **track** per row (`base`, `action_overlay`, `prop_effect`,
-`full_body_override`), which lets a **composite** stack rows onto each other by
-integer pivot translation and arbitrary alpha masks — deterministically, and
-without changing anything about a run that declares none of it.
-
-## 1. The compatibility rule (read this first)
-
-**A request with no `rig`, no `states.<state>.track`, and no `layers` is not a
-layer run, and every byte it produces is what it produced before this feature
-existed.** No new manifest key, no new sidecar field, no new file in the run dir,
-no new validation that could reject a request that used to pass.
-
-Concretely:
-
-- `layers.has_layer_contract(request)` is the single opt-in test. False ⇒ the
- layer validator returns an empty error list and every layer-aware stage is a
- no-op.
-- `manifest.json` gains `rig` / per-row `track` **only** when the request declares
- a rig. The non-layer manifest key set is pinned by
- `test_non_layer_run_manifest_surface_is_unchanged`.
-- Composite output never enters `frames/`, never enters `frames-manifest.json`,
- and never becomes a row of the base atlas (§2, findings B3/B4).
-
-## 2. Ownership audit — what already owns what
-
-This is the audit this contract is built on. Each row is the state of the code as
-shipped, with the enforcement point, so a layer change can be checked against a
-boundary instead of a memory.
-
-| Surface | Canonical owner | Single writer | Generation stamp | What layers may add |
-|---|---|---|---|---|
-| `sprite-request.json` | the run (numeric SSoT) | `prepare` writes it; `runio.load_request` is the only read gate | none | `rig`, `states.<state>.track`, `layers` |
-| `frames/` + `frames-manifest.json` | derived cache of (raw + request + engine) | `extract` only, published as one transaction | `engine_revision` per row, self-healed by `heal_run` | **nothing** |
-| `curation.json` | the human's edits | webview POST and `sprite-gen anchor --pick`, both via `curation.write_curation_atomic` | `run_revision` + per-state `revision` | **nothing** |
-| `manifest.json` / `sprite-sheet-alpha.png` | `compose_atlas` output | `compose_atlas` | derived from the above | `rig` block, `animation.rows.<state>.track` |
-| `variants/` | `recolor` bake | `recolor` | none (colourways survive re-bakes) | — (precedent for §5's `layers/`) |
-
-### Boundary findings
-
-- **B1 — `prepare` re-emits the request from a whitelist.** `prepare._run` builds a
- fresh dict (`version`/`kind`/`engine`/`character`/`cell`/`chroma_key`/`states`/
- `style`, plus `directions`/`layout`/`fit` when present), and
- `normalize_states` rebuilds each state entry as `frames`/`fps`/`loop`/`action`.
- Anything else in `--request` / `--request-json` is dropped, and the command still
- exits 0 — measured, not inferred: a request carrying `rig`, `tracks` and
- `states.idle.takes` came back out with none of the three. So `takes` (a
- first-class contract key, `run-contract.md` §2) has to be hand-written into
- `sprite-request.json` today. **Consequence:** the layer contract may never assume
- request passthrough. `rig`, `states.<state>.track` and `layers` must be added to
- the carried set explicitly, and the drop must become observable (§7).
-- **B2 — there is no central request schema.** Every stage reads the keys it wants
- (`request.get("fit")`, `request["cell"]`, …); `runio.load_request` only normalizes
- retired keys in memory (it never writes — `run-contract.md` §2-b-2). **Consequence:** layer validation lives in exactly one module
- (`sprite_gen/compose/layers.py`) that every layer-aware entry point calls, instead of
- per-stage key checks that drift.
-- **B3 — `frames/` is a derived cache with one writer.** `heal_run` re-derives a row
- from `raw/` whenever the engine revision moves, and a row with no `raw/` is kept
- with an observable `kept_stale` note. **Consequence:** a composite (whose source is
- other rows, not a raw strip) can never live in `frames/` — the next heal would
- either destroy it or permanently mark it stale.
-- **B4 — request states and manifest rows must match exactly.**
- `extract._require_generation_consistency` fails loud when a request state has no
- manifest row, when a row names a state the request does not, and when a physical
- frame dir is an orphan. **Consequence:** a composite must not be declared in
- `request.states`. This is what settles the "is a composite just another row?"
- question — it cannot be, without either faking an extraction or weakening the
- consistency gate. Composite names are therefore required to be disjoint from state
- names.
-- **B5 — `curation.json` is generation-stamped human truth.** A mismatched stamp
- drops the row's curation (with a backup and a stderr report). **Consequence:**
- machine-authored layer data must not live there. A rig in the sidecar would be
- silently dropped by an ordinary re-extract; a rig in the request survives it.
-- **B6 — the manifest key set is built in one place.** `compose_atlas` assembles
- `manifest.json` as a closed dict, and `animation.rows.<state>` already carries
- per-row extensions (`frame_variant`, `durations_ms`, `breathe`).
- **Consequence:** `track` belongs beside them; `rig` belongs at the top level; both
- appear only for a rig run.
-- **B7 — atlas cells are shared between identical instances.** `compose_atlas`
- reuses one cell for instances with the same (source frame, transform, pixel edits,
- breathe phase), so `frame_layout.rows.<state>` can repeat the same rect.
- **Consequence:** manifest landmark arrays are indexed by **play position** — same
- length and order as `frame_layout.rows.<state>` — never by unique cell. A consumer
- that zips landmarks against rects must get a 1:1 match.
-- **B8 — one cell shape end-to-end.** There is no separate generation cell and atlas
- cell (`architecture.md` §4). **Consequence:** a stack composes rows of one run, in
- that run's cell. Cross-run or cross-cell stacking is rejected, not rescaled.
-- **B9 — mirrored directions have no generated rows.** `directions.mirror` declares a
- runtime mirror. **Consequence:** a stack element must name a generated state;
- mirroring stays a runtime transform applied to the composite, so no landmark is
- mirrored at bake time.
-- **B10 — a row's frame pool includes its takes.** `layout.state_frame_total` is the
- pool size, and curation indices live in that space. **Consequence:** landmark frame
- indices are **pool indices** (takes included), and a composite consumes the
- **curated play sequence** (`curation.state_plan`), exactly like `compose_atlas` —
- so a composite carries the human's picks, order, pixel edits and transforms instead
- of the raw extractor output (`run-contract.md` §2-c).
-
-## 3. Request schema extension
-
-All three keys are optional. Types are strict: coordinates are JSON integers, never
-floats and never booleans.
-
-```jsonc
-{
- "rig": {
- "profile": "humanoid_biped", // humanoid_biped | quadruped | blob_or_tentacle | prop
- "landmarks": { // state -> pool frame index (string) -> name -> [x, y]
- "down_walk": {
- "0": {"root": [32, 44], "crown": [32, 8], "hand_r": [40, 30]},
- "1": {"root": [32, 43], "crown": [32, 7], "hand_r": [41, 31]}
- },
- "watering_can": {
- "0": {"root": [10, 10], "grip": [8, 12]}
- }
- }
- },
-
- "states": {
- "down_walk": {"frames": 2, "fps": 8, "loop": true, "track": "base"},
- "watering_can": {"frames": 1, "fps": 8, "loop": false, "track": "prop_effect"}
- },
-
- "layers": {
- "down_walk_watering": { // composite name — must NOT be a state name (B4)
- "stack": [ // list order = draw order, bottom first
- {"state": "down_walk"}, // body element, index 0
- {"state": "watering_can", "from": "grip", "to": "hand_r", // pivot pair
- "mask": "references/masks/can.png", "allow_clip": false}
- ],
- "fps": 8, "loop": true // optional; default = the body element's state entry
- }
- }
-}
-```
-
-### 3.1 Profiles and landmarks
-
-`root` is the composition pivot for **every** profile. Nothing is inferred from
-geometry: an undeclared landmark is an error, never a guess.
-
-| Profile | Required on every frame | Reserved optional vocabulary |
-|---|---|---|
-| `humanoid_biped` | `root`, `crown` | `head`, `neck`, `hand_l`, `hand_r`, `foot_l`, `foot_r` |
-| `quadruped` | `root` | `head`, `muzzle`, `tail`, `foot_fl`, `foot_fr`, `foot_bl`, `foot_br` |
-| `blob_or_tentacle` | `root` | `mouth`, `eye_l`, `eye_r`, `tip_a`…`tip_d` |
-| `prop` | `root` | `grip`, `tip`, `muzzle` |
-
-- `crown` (정수리) is a **humanoid head landmark for generation and QA framing**, not
- a pivot. It is required only for `humanoid_biped`; forcing a head rule onto an
- octopus or a quadruped is explicitly out of scope.
-- **Required landmarks are judged by profile AND track.** The profile answers *what
- this character is*; the track answers *what this row draws*. A `prop_effect` row
- draws a prop or an effect, not the character, so it is held to the `prop` profile's
- requirement — its own `root`, plus whatever self-meaning names (`grip`, `tip`) it
- declares — inside a `humanoid_biped` run just the same. A watering can has no
- 정수리: requiring one would leave a single way out, declaring a made-up `crown` on
- the row the composer aligns against, which turns a required pivot into noise. The
- narrowing is `prop_effect` only — `base`, `action_overlay` and `full_body_override`
- all draw the body and keep the rig profile's full set, so a humanoid run still
- cannot ship a body frame without a crown.
-- **An unknown `rig.profile` requires nothing, on every track.** Profile validity is
- judged before the `prop_effect` narrowing, so a run that declared no valid profile
- gets one error — the profile itself — and never a derived "missing `root`" on its
- prop rows next to it. This holds for any JSON type: a `rig.profile` that is a list
- or an object is reported like any other unknown value, not raised.
-- The reserved column is a naming recommendation, not a restriction: any name
- matching `^[a-z][a-z0-9_]{0,31}$` is accepted. Whatever is used must be declared on
- **every** frame of that row — a landmark that exists on some frames only is
- rejected, because a composite would otherwise skip frames.
-- `rig.landmarks.<state>` must cover the row's whole frame pool, `0 .. state_frame_total-1`,
- takes included (B10). A state **absent** from `rig.landmarks` is not a violation by
- itself — a rig run may declare landmarks for the rows it composes and leave the rest
- alone. It becomes a violation the moment a stack element refers to that row, and the
- base manifest simply carries no landmark array for it (§5).
-- Coordinates are integer cell coordinates of that state's frames, inside the cell —
- **the baked instance's coordinates**, i.e. what the curation view shows after the
- human's transform and pixel edits, which is exactly what a composite draws. Curation
- therefore comes first and landmarks second; re-transforming a row after declaring its
- pivots moves the art out from under them, which is what the `revision` pin (§3.3) and
- the row fingerprints in the bake report are there to make provable.
-- A **curated clone instance** lives outside the pool (its index is `>= state_frame_total`,
- `curation.state_clones`) and therefore has no declared landmarks. It carries its own
- transform, so borrowing the pivots of the frame it copies would be a guess: a clone in
- a layer row fails the bake and the base manifest's `rig` block, loudly, instead.
-
-### 3.2 Tracks
-
-An undeclared row is `base` — the explicit default, so a legacy run reads as an
-all-`base` run rather than as an unknown kind.
-
-| Track | Draws | Landmarks required per frame | Requires | Forbids |
-|---|---|---|---|---|
-| `base` | the whole body | the rig profile's set | — | sharing a stack with another body element |
-| `action_overlay` | a partial-body action drawn over the base | the rig profile's set | a `base` in the stack | coexisting with `full_body_override` |
-| `prop_effect` | a prop or effect placed at a socket landmark | the `prop` profile's set (`root`) | a body element; its `to` landmark declared on that body row | — |
-| `full_body_override` | the whole body, replacing the base | the rig profile's set | being the only body element | `base` and `action_overlay` in the same stack |
-
-`full_body_override` is the escape hatch for a motion that cannot be decomposed —
-a two-handed swing owns the whole body, so the contract makes that explicit
-instead of letting an overlay half-cover a base that is still walking.
-
-### 3.3 Stack elements
-
-| Key | Default | Meaning |
-|---|---|---|
-| `state` | required | the row this element draws |
-| `from` | `"root"` | the element's own landmark |
-| `to` | `"root"` | the landmark **on the body element** that `from` is placed onto |
-| `mask` | none | run-relative path to an alpha mask (§4); must stay inside the run dir |
-| `allow_clip` | `false` | permit opaque pixels to fall outside the cell |
-| `revision` | none | pin: the source row's `state_revision` segments as of the landmark declaration (§4) |
-
-The body element is `stack[0]`; every other element is aligned onto it. A stack has
-exactly one body element. A non-body element's row has either the same pool size as
-the body row, or exactly one frame (a held pose).
-
-A **held pose is a pool of one**, not a row that curation happened to shorten. An
-element whose pool matches the body plays the body's curated sequence position for
-position; if curation leaves the two sequences different lengths, the bake fails
-rather than choosing which body frames go unaccompanied.
-
-## 4. Composition contract (deterministic)
-
-The composer ([`../sprite_gen/compose/compose_layers.py`](../sprite_gen/compose/compose_layers.py),
-`compose_layers.bake(run_dir, names=None)`) bakes output frame `i` as:
-
-1. Start from a fully transparent cell of the run's `cell` geometry.
-2. For each element in stack order (bottom first):
- 1. Resolve the source instance from the element's **curated play sequence**
- (`curation.state_plan`), position `i`, or its only instance for a 1-frame
- element (B10, `run-contract.md` §2-c).
- 2. If `mask` is declared, multiply alpha: `a' = (a * m + 127) // 255`, integer
- arithmetic, rounding half up. The mask is an arbitrary shape — any PNG of the
- cell's size; its alpha (or luminance for an `L` image) is `m`. A missing file or
- a size mismatch is a hard error.
- 3. Translate by the integer offset `to_point - from_point`, where `to_point` is the
- body element's `to` landmark at position `i` and `from_point` is this element's
- `from` landmark. The body element itself translates by `(0, 0)`.
- 4. `alpha_composite` onto the accumulator.
-3. Emit the cell.
-
-**No resampling, no rotation, no scaling.** Layer composition is integer translation
-plus alpha compositing, which is why the same input produces the same bytes — the
-verification is composing twice and comparing SHA-256 of the atlas and the manifest.
-Rotation and scale remain curation's job, already baked into the source instance.
-
-Two more properties of that loop, both load-bearing:
-
-- The source instance is the **curated** one — the human's pick order, transform, pixel
- edits and breathe phase are already inside it, assembled from the same primitives
- `compose_atlas` uses. A composite is therefore a combination of what the atlas bakes,
- never of the raw extractor output.
-- Identical composed cells **share one column**, exactly like the atlas (B7): the rect
- list in the composite manifest is indexed by play position and may repeat.
-
-Failure diagnostics the composer owns (everything that needs the run dir):
-
-- a declared source frame missing from the published generation;
-- a mask file missing, unreadable, not the cell's size, or resolving outside the run dir;
-- an art pixel translated outside the cell while `allow_clip` is false — reported with
- the clipped pixel count and failed, never silently cropped. "Art" is alpha > 8, the
- same floor `recolor` and the GIF export already use, so a soft key's sub-threshold
- edge bleed is not a clip;
-- an element whose curated sequence does not match the body's (§3.3), and a body row
- curated down to no frames at all;
-- an instance with no declared landmarks — a curated clone (§3.1);
-- a declared landmark whose row was regenerated: the bake report records each source
- row's `state_revision`, and an element may declare `revision` to be checked, in
- which case a mismatch fails loud (same mechanism as `curation.anchors`: the stored
- segments must be a prefix of the current ones).
-
-The bake is **all-or-nothing**. Every composite is composed in memory first; one
-violation anywhere fails the call with the complete diagnostic list and writes nothing,
-so `layers/` never holds a partially valid set.
-
-## 5. Output and manifest extension
-
-**Composites are a sibling artifact tree, not atlas rows** (B3/B4), following the
-precedent `variants/` already set:
-
-```text
-<run-dir>/
- layers/<name>.png # composed atlas for that composite
- layers/<name>.manifest.json # runtime manifest, same shape as manifest.json
- layers/layers.report.json # per-composite provenance: stack, source revisions,
- # per-element offsets, clipped-pixel counts
-```
-
-`layers/<name>.manifest.json` keeps the runtime shape a consumer already reads
-(`game_input`, `degraded_static_fallback`, `animation.rows`, `frame_layout` with
-absolute rects), so a runtime needs no new code path, and adds a `layers` block
-recording the stack it came from. Concretely its key set is the base manifest's
-minus `rig`, plus `layers`; its single row is named after the composite and carries
-`track: "composite"`, because what it plays is a combination and not one of the four
-declarable row kinds. `fps` / `loop` come from the composite spec, defaulting to the
-body element's state entry.
-
-`sprite_sheet_alpha_report` is **`null`** in a composite manifest. That field names
-the alpha/extraction report *of this sheet*, and a composite has none: it is stacked
-from rows that were already extracted and keyed, so no alpha report was ever produced
-for it. The key stays (key-set parity above) and states the absence instead of
-pointing at a document of another kind — `layers/layers.report.json` is the bake's
-provenance record for **every** composite (`kind: "sprite-gen-layers-report"`), not
-this sheet's alpha report, so a consumer that resolved the field would open the wrong
-document. The provenance pointer is `layers.report` inside the `layers` block.
-
-A bake replaces the composites it produced and leaves everything else in `layers/`
-alone — the same rule `variants/` follows, and the only one compatible with baking a
-subset by name. `layers/layers.report.json` is the record of what the last bake
-produced, so a sheet that is not in it is a leftover, not a current output.
-
-**Publishing is one transaction.** §4's all-or-nothing rule covers declaration and
-composition; the write is held to the same rule. Every sheet, every manifest and the
-report are rendered in memory, staged as temp files beside their targets, and only
-then renamed in — so an `ENOSPC` on the second composite's sheet leaves the first
-one exactly as it was, and the report never names a sheet that failed to land.
-(A power loss between two renames can still land a subset; what this removes is the
-failure the process can observe — reporting success over a half-written publish.)
-
-The base run's `manifest.json` gains, **only for a rig run**:
-
-```jsonc
-{
- "rig": {
- "profile": "humanoid_biped",
- "landmarks": {
- "down_walk": [ // one entry per PLAY POSITION, same order and
- {"root": [312, 108], "crown": [312, 72]}, // length as frame_layout.rows.down_walk (B7)
- {"root": [408, 107], "crown": [408, 71]}
- ]
- }
- },
- "animation": {"rows": {"down_walk": {"track": "base"}}}
-}
-```
-
-Landmarks in the manifest are **atlas-absolute integers**, matching the
-`frame_layout` philosophy: a runtime samples rects and pivots, it never recovers
-geometry from alpha. That is what lets the runtime combine tracks live instead of
-consuming a pre-baked combination for every direction × action pair.
-
-## 6. Validation contract
-
-`sprite_gen.compose.layers.validate_layer_request(request)` returns **every** violation, in a
-deterministic order; `require_valid_layer_request` raises with all of them at once.
-It is filesystem-free, so it runs before a run dir is touched. Rejections:
-
-- unknown `rig.profile` — one error, whatever JSON type it is, and no landmark
- requirement is derived from it on any track (§3.1); malformed `rig` / `rig.landmarks`;
-- a composite `fps` that is not a positive integer, or a `loop` that is not a boolean;
-- a malformed element `revision` pin (it must be a non-empty list of segment strings);
-- landmarks for an unknown state; a frame key that is not a decimal index; a frame
- index outside the pool; a pool frame with no landmarks at all;
-- a required landmark missing on any frame — required per row by profile **and** track,
- so a `prop_effect` row is held to the `prop` set (§3.1); a landmark name that does not
- match the pattern; a landmark declared on part of a row only;
-- a coordinate that is not a pair of integers, or lands outside the cell;
-- an unknown `track` value;
-- a composite name that collides with a request state, or does not match
- `^[a-z][a-z0-9_]{0,63}$`; an empty stack; an unknown composite key
- (`stack` / `fps` / `loop` is the whole vocabulary); an unknown stack-element key;
-- zero or several body elements; a body element that is not `stack[0]`;
-- `action_overlay` under a `full_body_override`;
-- an element whose pool size is neither the body's nor 1;
-- `from` / `to` not declared on every frame of the row it refers to;
-- a stack with no `rig` at all.
-
-## 7. Using it — the CLI and where it sits in the run
-
-### 7.1 Declaring
-
-`prepare` carries `rig`, `layers` and `states.<state>.track` from `--request` /
-`--request-json` into `sprite-request.json`, and validates them (§6) before it
-creates the run dir — a malformed rig fails with every violation at once instead of
-scaffolding a run whose first bake is what reports it.
-
-Of the layer vocabulary it carries exactly those three keys and nothing else.
-`prepare` re-emits the whole request from a whitelist (B1), so any key outside that
-list is dropped — and every drop is now named on stderr:
-
-```text
-[prepare] dropped top-level request key(s) ['notes']: prepare re-emits sprite-request.json from …
-[prepare] dropped states.idle key(s) ['takes']: a state entry is rebuilt as ['frames', 'fps', 'loop', 'action', 'track']
-```
-
-That note is the contract, not a courtesy: `states.<state>.takes` is a documented
-first-class key (`run-contract.md` §2) that has to be written into
-`sprite-request.json` after `prepare` runs, and it went missing silently for as long
-as the whitelist said nothing. Landmarks are usually declared the same way — after
-curation, since coordinates are the *baked instance's* (§3.1) — by editing
-`sprite-request.json` directly.
-
-### 7.2 Baking
-
-```bash
-# every declared composite
-$SPRITE_GEN_ROOT/.venv/bin/sprite-gen compose-layers \
- --run-dir <target>/assets/generated/sprites/<character-id>
-
-# just the ones named (the rest of layers/ is left alone)
-$SPRITE_GEN_ROOT/.venv/bin/sprite-gen compose-layers \
- --run-dir <run> --names down_walk_watering,down_idle_watering
-```
-
-The `sprite-gen compose-layers` subcommand, the `-m sprite_gen.compose.compose_layers` module
-form and the `scripts/compose_layers.py` wrapper are three launch forms of one declaration
-(`compose_layers.add_arguments` / `.run`), and `compose_layers.bake(run_dir,
-names=None)` is the library form the three share.
-
-`--names` is a selection, so it is spelled exactly: an empty entry (`a,,b`, a trailing
-comma) is a typo and never "all", and a name listed twice is refused the same way.
-Both ways of passing over a repeat lie about the result — de-duplicating answers a
-selection nobody asked for, and keeping the repeat writes one sheet while
-`layers.report.json` counts two composites. `bake(names=[...])` enforces it too
-(`compose_layers.require_distinct_names`), so the library form cannot reach a bake the
-CLI would have refused.
-
-Order in the run: it consumes the **curated** rows and the same primitives
-`compose-atlas` does, so it belongs after curation, beside step 4 — a composite is
-a combination of what the atlas bakes. It self-heals the derived frame cache first
-(same rule as `compose-atlas`), takes the run-dir write lock, and prints a JSON
-summary naming each sheet, its manifest, its frame/cell counts and clipped-pixel
-total; the full record is `layers/layers.report.json`.
-
-Exit codes are the pipeline's: `0` with the summary, or a non-zero failure listing
-**every** violation at once, having written nothing (§4). A run that declares no rig
-is refused by name rather than treated as an empty bake — "nothing to compose" and
-"this is not a layer run" are different answers.
-
-## 8. Out of scope
-
-- **`unpack_atlas` / import runs** are untouched by this contract: an imported run
- has no rig, so it stays a non-layer run.
-- **Runtime track combination.** The manifest carries atlas-absolute landmarks per
- play position (§5) precisely so a runtime *can* combine tracks live; doing so is
- the consumer's job, not this pipeline's.
-
-## Related
-
-- [`../SKILL.md`](../SKILL.md) — behavior contract (workflow, gates, runtime contract)
-- [`run-contract.md`](run-contract.md) — stage table, run-dir tree, curation-view payload
-- [`architecture.md`](architecture.md) — how the code realizes the contracts
-- [`curation.md`](curation.md) — sidecar schema this contract deliberately does not extend
-- [`recolor.md`](recolor.md) — the sibling-artifact-tree precedent (`variants/`)
diff --git a/docs/run-contract.md b/docs/run-contract.md
index 72972ee..c4f774e 100644
--- a/docs/run-contract.md
+++ b/docs/run-contract.md
@@ -46,7 +46,6 @@ canonical files, not hidden imports.
| 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` |
-| Layer bake (opt) | `sprite-gen compose-layers` (`sprite_gen/compose/compose_layers.py`) | `frames/` + `curation.json` + the request's `rig` / `layers` | `layers/<name>.png`, `layers/<name>.manifest.json`, `layers/layers.report.json` (published as one set) |
| 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 |
@@ -133,12 +132,6 @@ not restate it elsewhere; point here.
# passthrough pixels). Adopted pick lives in
# curation.json.recolor.picked (name-keyed). See
# docs/recolor.md.
- layers/ # only when a rig run bakes composites (compose_layers) —
- # <name>.png + <name>.manifest.json (runtime shape,
- # one composite row) + layers.report.json (stack,
- # source revisions, per-element offsets, clipped
- # pixels). A composite is NEVER a frames/ row nor a
- # request state. See docs/layer-tracks.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
@@ -200,10 +193,13 @@ schema writer (`runio.migrate_request_file`, exposed as `sprite-gen migrate-requ
- **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 (`fit.pixel_perfect`)
- is normalized to the current key (`fit.pixel_unfake`) **in memory only**, so an old
- approved run keeps working without its file being touched. Both keys present is still
- a hard fail — code cannot pick which of two truths is real.
+ 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).
@@ -229,7 +225,7 @@ schema writer (`runio.migrate_request_file`, exposed as `sprite-gen migrate-requ
- **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. Otherwise changing one fps value would migrate the schema as a
+ 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.
@@ -572,6 +568,5 @@ service, revisit both here.
- [`architecture.md`](architecture.md) — how the code realizes these contracts (stage internals, lock, extraction, pixel-unfake path)
- [`curation.md`](curation.md) — webview interaction model, `curation.json` schema, standalone image-candidate path, multi-agent launch rules
- [`recolor.md`](recolor.md) — palette-swap bake (`variants/`), report schema, colourway adopt
-- [`layer-tracks.md`](layer-tracks.md) — optional rig / track / composite contract; the `layers/` sibling artifact tree and why a composite is never a `frames/` row or a request state
- [`pixel-unfake.md`](pixel-unfake.md) — `fit`/`pixel_unfake` behavior + plain-twin bake decision
- [`directional-anchor-workflow.md`](directional-anchor-workflow.md) — directional/45° anchor chains that name the `raw/` anchors §3 resolves into chips
diff --git a/pyproject.toml b/pyproject.toml
index fdfa956..4ed2a38 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -12,7 +12,7 @@ build-backend = "setuptools.build_meta"
name = "sprite-gen"
# Release discipline: keep this package metadata version synchronized with
# SKILL.md's `version:` field in the same release commit.
-version = "2.46.0"
+version = "3.0.0"
description = "Component-row pipeline for clean 2D game sprites and animation atlases"
readme = "README.md"
license = "Apache-2.0"
diff --git a/scripts/compose_layers.py b/scripts/compose_layers.py
deleted file mode 100644
index 8af1bc7..0000000
--- a/scripts/compose_layers.py
+++ /dev/null
@@ -1,16 +0,0 @@
-#!/usr/bin/env python3
-# SPDX-License-Identifier: Apache-2.0
-"""Backward-compatible wrapper for sprite_gen.compose.compose_layers."""
-
-import sys
-from pathlib import Path
-
-sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
-
-import sprite_gen.compose.compose_layers as _impl
-
-globals().update({name: value for name, value in vars(_impl).items() if name not in {"__name__", "__package__", "__loader__", "__spec__"}})
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/sprite_gen/__init__.py b/sprite_gen/__init__.py
index 656c1bc..e0b2166 100644
--- a/sprite_gen/__init__.py
+++ b/sprite_gen/__init__.py
@@ -14,7 +14,7 @@ __all__ = [
"audio", # provider-backed sound generation and browser exports
"frames", # sheet -> frames extraction (+ inverse unpack)
"curate", # curation decisions / sidecar / anchors
- "compose", # bake atlas / cycle / gif / layers / export
+ "compose", # bake atlas / cycle / gif / export
"effects", # per-frame transforms: breathe, recolor, interpolate, reroll
"qa", # inspect / score / correction-loop / preview
"serve", # webview servers (curation, compose) + SPAs
diff --git a/sprite_gen/_modules.py b/sprite_gen/_modules.py
index 7e8087f..dd526a7 100644
--- a/sprite_gen/_modules.py
+++ b/sprite_gen/_modules.py
@@ -57,8 +57,6 @@ MODULE_DOMAIN = {
'game_pack': 'compose',
'compose_cycle': 'compose',
'compose_gif': 'compose',
- 'compose_layers': 'compose',
- 'layers': 'compose',
'export_pngs': 'compose',
'export_aseprite': 'compose',
'breathe': 'effects',
@@ -88,7 +86,7 @@ DOMAINS: list[tuple[str, str]] = [
("video", "Video → loop — canvas, keyed frames, seamless cycle, batch"),
("frames", "Frames — chroma/white removal, row extraction, sheet slicing, atlas unpacking"),
("curate", "Curation — direction anchors and the curation sidecar"),
- ("compose", "Compose — runtime atlas, cycles, GIFs, layers, exports"),
+ ("compose", "Compose — runtime atlas, cycles, GIFs, exports"),
("background", "Background — repeating painted strips and textures"),
("effects", "Post-processing — recolor, breathing, interpolation, projected shadows"),
("scene", "Scene — asset placement, camera, lighting, rendering and inspection"),
@@ -114,8 +112,8 @@ PIPELINES: list[dict[str, object]] = [
TOOL_GROUPS: list[dict[str, object]] = [
{"key": "C", "name": "utilities", "verbs": ["cutout", "slice-sheet", "ui-kit", "unpack-atlas"],
"chain": "cutout · slice-sheet · ui-kit · unpack-atlas (each stands alone)", "doc": "docs/sheet-slicing.md"},
- {"key": "D", "name": "post-processing", "verbs": ["recolor", "recolor-palette", "compose-layers", "breathe", "export-pngs", "export-aseprite"],
- "chain": "recolor · compose-layers · breathe · export-pngs · export-aseprite", "doc": "docs/recolor.md"},
+ {"key": "D", "name": "post-processing", "verbs": ["recolor", "recolor-palette", "breathe", "export-pngs", "export-aseprite"],
+ "chain": "recolor · breathe · export-pngs · export-aseprite", "doc": "docs/recolor.md"},
{"key": "E", "name": "asset tools", "verbs": ["background-tile", "shadow", "inspect-motion"],
"chain": "background-tile · shadow · inspect-motion (independent; no generation required)", "doc": "docs/asset-tools.md"},
]
diff --git a/sprite_gen/cli.py b/sprite_gen/cli.py
index bd894e4..f105da8 100644
--- a/sprite_gen/cli.py
+++ b/sprite_gen/cli.py
@@ -11,7 +11,7 @@ from sprite_gen import _modules, gen
from sprite_gen.audio import sound
from sprite_gen.background import tile
from sprite_gen.curate import anchor
-from sprite_gen.compose import compose_atlas, compose_cycle, compose_gif, compose_layers, export_aseprite, export_pngs
+from sprite_gen.compose import compose_atlas, compose_cycle, compose_gif, export_aseprite, export_pngs
from sprite_gen.compose import game_pack
from sprite_gen.qa import correction_loop, inspect, preview, score, motion
from sprite_gen.qa import handed as handed_check
@@ -240,13 +240,6 @@ COMMANDS: dict[str, tuple[str, Callable[[argparse.ArgumentParser], None], Callab
compose_cycle.run,
),
"compose-gif": ("Compose selected sprite frames into a clean transparent GIF.", _add_compose_gif, compose_gif.run),
- # Same rule as `curation` / `recolor`: the subcommand reuses the module's own
- # argument declaration, so the three launch forms cannot drift apart.
- "compose-layers": (
- "Bake a rig run's declared composite stacks into <run-dir>/layers/.",
- compose_layers.add_arguments,
- compose_layers.run,
- ),
"unpack-atlas": (
"Unpack a composed sprite sheet back into a curator-ready run directory.",
_add_unpack_atlas,
@@ -272,7 +265,7 @@ COMMANDS: dict[str, tuple[str, Callable[[argparse.ArgumentParser], None], Callab
# and everything through it) normalize retired keys in memory and leave the file byte
# for byte — a query must never rewrite a canonical run.
"migrate-request": (
- "Migrate a run's retired sprite-request fit keys to the current schema.",
+ "Migrate a run's retired sprite-request keys to the current schema.",
migrate_request.add_arguments,
migrate_request.run,
),
diff --git a/sprite_gen/compose/compose_atlas.py b/sprite_gen/compose/compose_atlas.py
index fc60cab..bf9dbc1 100644
--- a/sprite_gen/compose/compose_atlas.py
+++ b/sprite_gen/compose/compose_atlas.py
@@ -16,8 +16,6 @@ from sprite_gen.effects.breathe import anatomy_report, fit_breathe_pattern, phas
from sprite_gen.curate.curation import apply_pixel_edits, apply_transform, edit_index, frame_variant, load_curation, pixel_snap_scale, source_frame_index, state_breathe, state_pixel_ops, state_plan
from sprite_gen.spec.layout import row_frame_rel, state_frame_total
from sprite_gen.frames.extract import heal_run, require_frames_manifest
-from sprite_gen.compose.layers import (has_layer_contract, landmark_map, require_valid_layer_request,
- state_track)
from sprite_gen.spec.runio import acquire_run_dir_lock, atomic_save_image, atomic_write_text, load_request
from sprite_gen.spec.subject import default_min_used_pixels
from sprite_gen.util.console import utf8_streams
@@ -59,10 +57,6 @@ def _run(args: argparse.Namespace):
print(f"[heal] re-derived stale rows: {', '.join(heal_report['healed'])}", file=sys.stderr)
acquire_run_dir_lock(run_dir, "compose_sprite_atlas")
request = load_request(run_dir)
- # A run that declares no rig / track / layers is not a layer run and this is a
- # no-op (docs/layer-tracks.md §1). One that does is checked before any bake
- # work, so an invalid rig never reaches the manifest as half-declared pivots.
- require_valid_layer_request(request)
if args.min_used_pixels is None:
args.min_used_pixels = default_min_used_pixels(request)
frames_manifest = require_frames_manifest(run_dir) # fail loud if absent/corrupt/not-ok
@@ -217,41 +211,6 @@ def _run(args: argparse.Namespace):
animation["rows"][state]["breathe"] = anatomy_report(row_source_frames, breathe_cfg) \
if row_source_frames else None
- # 레이어 런 확장 (docs/layer-tracks.md §5): rig 를 선언한 런만 매니페스트에
- # `rig` 블록과 행별 `track` 이 붙는다. 랜드마크는 **아틀라스 절대 정수 좌표**이고
- # **재생 위치**로 색인된다 — frame_layout.rows.<state> 와 길이·순서가 같아서
- # 소비자가 rect 와 1:1 로 zip 할 수 있다 (칸 재사용으로 rect 는 반복될 수 있다).
- # 런타임이 트랙을 실시간으로 합치기 위한 입력이고, 굽힌 조합의 소비가 아니다.
- rig_block: dict[str, Any] | None = None
- if has_layer_contract(request):
- for state in states:
- animation["rows"][state]["track"] = state_track(request, state)
- rig = request.get("rig")
- if isinstance(rig, dict):
- rig_landmarks: dict[str, Any] = {}
- for state in states:
- if not ((rig.get("landmarks") or {}).get(state)):
- continue
- entries = []
- for (instance, _phase), rect in zip(positions_by_state[state],
- frame_layout["rows"][state]):
- points = landmark_map(request, state, instance)
- if points is None:
- # 큐레이션 복제 인스턴스는 풀 밖 인덱스라 선언이 없다. 원본
- # 프레임의 피벗을 빌려오면 복제 자신의 변형만큼 어긋난 좌표를
- # 런타임에 내보내게 된다 — 추정하지 않고 실패한다.
- errors.append(
- f"{state}: instance {instance} declares no rig landmarks "
- f"(a curated clone carries its own transform, so its pivots "
- f"cannot be borrowed from the frame it copies)")
- entries = None
- break
- entries.append({name: [rect["x"] + point[0], rect["y"] + point[1]]
- for name, point in points.items()})
- if entries is not None:
- rig_landmarks[state] = entries
- rig_block = {"profile": rig.get("profile"), "landmarks": rig_landmarks}
-
# top-level summary: uniform value when every row agrees, else 'mixed'
# (per-row truth lives in animation.rows.<state>.frame_variant).
unique_variants = set(variants.values())
@@ -294,8 +253,6 @@ def _run(args: argparse.Namespace):
"animation": animation,
"frame_layout": frame_layout,
}
- if rig_block is not None:
- manifest["rig"] = rig_block
atomic_write_text(run_dir / args.manifest, json.dumps(manifest, ensure_ascii=False, indent=2) + "\n")
print(json.dumps({"ok": True, "atlas": str(atlas_path), "manifest": str(run_dir / args.manifest)}, ensure_ascii=False, indent=2))
return 0
diff --git a/sprite_gen/compose/compose_layers.py b/sprite_gen/compose/compose_layers.py
deleted file mode 100644
index cec6fc4..0000000
--- a/sprite_gen/compose/compose_layers.py
+++ /dev/null
@@ -1,653 +0,0 @@
-# SPDX-License-Identifier: Apache-2.0
-"""Deterministic composite bake — stack curated rows by integer pivot translation.
-
-The execution half of the layer feature (`docs/layer-tracks.md` §4/§5). Given a
-request that declares a `rig`, per-row `track`s and a `layers` stack, this bakes
-each composite into the `layers/` sibling artifact tree:
-
- layers/<name>.png composed sheet
- layers/<name>.manifest.json runtime manifest, same key set as manifest.json
- layers/layers.report.json provenance: stack, source revisions, offsets, clips
-
-Determinism is the whole point: composition is integer translation plus alpha
-compositing over the curated instances, with no resampling, rotation or scale of
-its own, so the same run bakes the same bytes every time. Rotation and scale are
-curation's job and are already inside the source instance by the time this runs.
-
-Boundary (SoC): declaration truth is `sprite_gen.compose.layers` (filesystem-free —
-profiles, tracks, stack shape). Everything here needs the run dir: does the
-declared frame exist, is the mask the cell's size, does an aligned element clip,
-was the source row re-rolled since its landmarks were declared.
-
-A curated instance is assembled from the shared primitives in `curation` /
-`layout` / `breathe`, in the same order as every other consumer of a finished
-generation (`compose_atlas`, `compose_gif`, `export_pngs`, `anchor`): the
-primitives are the single source of that math, and each consumer composes them
-for its own output.
-
-Atomicity: every composite is baked in memory first. One violation anywhere
-fails the whole call with the complete diagnostic list and writes nothing, so
-`layers/` never holds a half-baked set (No Silent Fallback: no composite is
-skipped quietly, none is written from partly-valid input). The write is held to
-the same rule — sheets, manifests and the report go out through one
-`runio.atomic_write_set`, so an IO failure partway through cannot leave a
-published sheet that no report names.
-"""
-
-from __future__ import annotations
-
-import argparse
-import io
-import json
-import sys
-from dataclasses import dataclass, field
-from pathlib import Path
-from typing import Any
-
-from PIL import Image
-
-from sprite_gen._deps import np
-from sprite_gen.effects.breathe import fit_breathe_pattern, phase_frame, resolve_anatomy
-from sprite_gen.compose.compose_atlas import cell_geometry
-from sprite_gen.curate.curation import (apply_pixel_edits, apply_transform, edit_index, frame_variant,
- load_curation, pixel_snap_scale, source_frame_index,
- state_breathe, state_pixel_ops, state_plan, state_revision)
-from sprite_gen.frames.extract import heal_run, require_frames_manifest
-from sprite_gen.compose.layers import (has_layer_contract, landmark_map, require_valid_layer_request,
- resolve_stack, state_track)
-from sprite_gen.spec.layout import row_frame_rel, state_frame_total
-from sprite_gen.spec.runio import acquire_run_dir_lock, atomic_write_set, load_request
-from sprite_gen.util.console import utf8_streams
-
-# Where a composite bake puts its output and what it names the report. The one
-# place these strings live (`docs/layer-tracks.md` §5 documents the same tree;
-# `docs/run-contract.md` §2 owns the run-dir tree it belongs to).
-LAYERS_DIRNAME = "layers"
-REPORT_NAME = "layers.report.json"
-REPORT_KIND = "sprite-gen-layers-report"
-
-# "A pixel" for the clip check. Matches the alpha floor recolor and compose-gif
-# already use, so the three agree on what counts as art rather than as the soft
-# key's edge bleed: a translated element that pushes only sub-threshold edge
-# pixels off the cell is not a clip.
-CLIP_ALPHA_THRESHOLD = 8
-
-
-@dataclass
-class _Source:
- """One source row of a stack: its curated play sequence and baked instances.
-
- `ordered[i]` is the instance index played at position `i` (pool index, or a
- curated clone index outside the pool), `phases[i]` its breathe phase.
- """
-
- state: str
- track: str
- row: dict[str, Any]
- total: int
- ordered: list[int]
- phases: list[float]
- transforms: dict[int, dict[str, float]]
- variant: str
- breathe: dict[str, Any] | None
- revision: list[str] | None
- anatomy: Any = None
- baked: dict[int, Image.Image] = field(default_factory=dict)
-
-
-def _resolve_source(run_dir: Path, request: dict[str, Any], curation: dict[str, Any] | None,
- row: dict[str, Any], state: str) -> _Source:
- total = state_frame_total(request, state)
- ordered, transforms = state_plan(curation, state, total)
- cfg = state_breathe(curation, state)
- phases = fit_breathe_pattern(len(ordered), cfg) if (cfg and ordered) else [0.0] * len(ordered)
- return _Source(
- state=state,
- track=state_track(request, state),
- row=row,
- total=total,
- ordered=ordered,
- phases=phases,
- transforms=transforms,
- variant=frame_variant(curation, state),
- breathe=cfg,
- revision=state_revision(run_dir, state, request=request, row=row),
- )
-
-
-def _instance(run_dir: Path, request: dict[str, Any], curation: dict[str, Any] | None,
- source: _Source, position: int, cell_size: tuple[int, int],
- snap_scale: int | None, errors: list[str]) -> Image.Image | None:
- """The curated, breathing instance played at `position` — what the atlas bakes."""
- if position in source.baked:
- return source.baked[position]
- instance = source.ordered[position]
- src_index = source_frame_index(curation, source.state, instance, source.total)
- try:
- rel = row_frame_rel(source.row, src_index, source.variant)
- except SystemExit as exc:
- errors.append(f"{source.state}: {exc}")
- return None
- path = run_dir / rel
- if not path.is_file():
- errors.append(
- f"{source.state} instance {instance}: missing frame ({source.variant} variant) "
- f"{rel} — the declared source is not in the published generation")
- return None
- edit_idx = edit_index(curation, source.state, instance)
- with Image.open(path) as opened:
- art = apply_pixel_edits(opened.convert("RGBA"),
- state_pixel_ops(curation, source.state).get(edit_idx))
- if art.size != cell_size:
- errors.append(
- f"{source.state} instance {instance}: frame {rel} is {art.width}x{art.height}; "
- f"expected the run's {cell_size[0]}x{cell_size[1]} cell")
- return None
- frame = apply_transform(art, source.transforms.get(edit_idx), cell_size,
- snap_scale=snap_scale if source.variant == "pixel" else None)
- if source.breathe:
- if source.anatomy is None:
- # One anatomy per row, resolved from its first played instance —
- # same rule as compose_atlas (anatomy is a character property).
- source.anatomy = resolve_anatomy(frame, source.breathe)
- frame = phase_frame(frame, source.breathe, source.phases[position], source.anatomy)
- source.baked[position] = frame
- return frame
-
-
-def _load_mask(run_dir: Path, rel: Any, cell_size: tuple[int, int], where: str,
- errors: list[str]) -> Image.Image | None:
- """An arbitrary alpha mask as an `L` channel of the cell's size.
-
- Any PNG shape is legal — that is the point of "arbitrary mask" — but its
- geometry is not: a mask of another size cannot be applied without resampling,
- and resampling is exactly what this bake refuses to do.
- """
- if not isinstance(rel, str) or not rel:
- errors.append(f"{where}: mask must be a run-relative path string (got {rel!r})")
- return None
- candidate = Path(rel)
- resolved = (run_dir / candidate).resolve()
- if candidate.is_absolute() or run_dir.resolve() not in resolved.parents:
- errors.append(f"{where}: mask path {rel!r} must stay inside the run dir")
- return None
- if not resolved.is_file():
- errors.append(f"{where}: mask file {rel} not found")
- return None
- try:
- with Image.open(resolved) as opened:
- opened.load()
- mask = opened.getchannel("A") if "A" in opened.getbands() else opened.convert("L")
- except OSError as exc:
- errors.append(f"{where}: mask file {rel} is unreadable ({exc})")
- return None
- if mask.size != cell_size:
- errors.append(
- f"{where}: mask {rel} is {mask.width}x{mask.height}; expected the run's "
- f"{cell_size[0]}x{cell_size[1]} cell (a mask is never resampled)")
- return None
- return mask
-
-
-def apply_alpha_mask(frame: Image.Image, mask: Image.Image) -> Image.Image:
- """`a' = (a * m + 127) // 255` — integer, rounding half up (contract §4).
-
- Spelled out rather than delegated to an imaging multiply: the library
- rounding a blend uses is an implementation detail that can differ by
- version, and this arithmetic is a published clause of the composite
- contract, not an internal choice.
- """
- alpha = np.asarray(frame.getchannel("A"), dtype=np.uint32)
- values = np.asarray(mask, dtype=np.uint32)
- masked = frame.copy()
- masked.putalpha(Image.fromarray(((alpha * values + 127) // 255).astype(np.uint8), "L"))
- return masked
-
-
-def _clipped_pixels(frame: Image.Image, offset: tuple[int, int],
- cell_size: tuple[int, int]) -> int:
- """Art pixels this offset would push outside the cell (0 = nothing is lost)."""
- dx, dy = offset
- cell_w, cell_h = cell_size
- alpha = frame.getchannel("A")
- total = sum(alpha.histogram()[CLIP_ALPHA_THRESHOLD + 1:])
- left, top = max(0, -dx), max(0, -dy)
- right, bottom = min(frame.width, cell_w - dx), min(frame.height, cell_h - dy)
- if right <= left or bottom <= top:
- return total
- inside = sum(alpha.crop((left, top, right, bottom)).histogram()[CLIP_ALPHA_THRESHOLD + 1:])
- return total - inside
-
-
-def _element_offset(request: dict[str, Any], name: str, element: dict[str, Any],
- body: _Source, source: _Source, body_instance: int, instance: int,
- errors: list[str]) -> tuple[int, int] | None:
- """`to_point - from_point`, both declared, neither inferred."""
- offset: list[int] = []
- for role, state, wanted, index in (
- ("to", body.state, str(element["to"]), body_instance),
- ("from", source.state, str(element["from"]), instance),
- ):
- points = landmark_map(request, state, index)
- if points is None:
- errors.append(
- f"layers.{name}: element {source.state!r} aligns {role}={wanted!r} against "
- f"{state!r} instance {index}, which declares no landmarks — a curated clone "
- f"instance carries its own transform, so its pivots cannot be borrowed from "
- f"the frame it copies. Drop the clone from this row or bake without it")
- return None
- point = points.get(wanted)
- if point is None:
- errors.append(
- f"layers.{name}: element {source.state!r} aligns {role}={wanted!r} but "
- f"{state!r} instance {index} does not declare it")
- return None
- offset.append(point[0])
- offset.append(point[1])
- return (offset[0] - offset[2], offset[1] - offset[3])
-
-
-def _compose_one(run_dir: Path, request: dict[str, Any], curation: dict[str, Any] | None,
- rows_by_state: dict[str, Any], name: str, cell_size: tuple[int, int],
- snap_scale: int | None, errors: list[str]) -> dict[str, Any] | None:
- spec = (request.get("layers") or {})[name]
- stack = resolve_stack(request, name)
- sources: list[_Source] = []
- for element in stack:
- state = str(element["state"])
- row = rows_by_state.get(state)
- if row is None:
- errors.append(
- f"layers.{name}: element state {state!r} has no row in the published "
- f"generation — extract it before composing")
- return None
- sources.append(_resolve_source(run_dir, request, curation, row, state))
-
- # The body element is stack[0] — the validator has already established that,
- # so the composer reads the declaration instead of re-deriving it.
- body = sources[0]
- length = len(body.ordered)
- if length == 0:
- errors.append(
- f"layers.{name}: body row {body.state!r} plays no frames (every instance is "
- f"deleted in curation) — a composite has nothing to stack onto")
- return None
-
- for element, source in zip(stack, sources):
- pin = element.get("revision")
- if pin is not None:
- current = source.revision
- if not (current and list(pin) == list(current[:len(pin)])):
- errors.append(
- f"layers.{name}: element {source.state!r} pins revision {list(pin)} but the "
- f"row is now {current} — the source was re-rolled since its landmarks were "
- f"declared; re-declare them and re-pin (pivots are never re-fitted)")
- if source is body:
- continue
- # A held pose is a row whose POOL is one frame. A row that merely got
- # curated down to fewer instances than the body is a mismatch, not a
- # hold: pairing its shortened sequence with the body's would silently
- # pick which body frames go unaccompanied.
- wanted = 1 if source.total == 1 else length
- if len(source.ordered) != wanted:
- errors.append(
- f"layers.{name}: element {source.state!r} plays {len(source.ordered)} frames "
- f"against a body of {length} — an overlay plays the body's sequence, and only "
- f"a single-frame row holds one pose")
-
- masks: dict[int, Image.Image | None] = {}
- for position, element in enumerate(stack):
- if element.get("mask") is not None:
- masks[position] = _load_mask(run_dir, element["mask"], cell_size,
- f"layers.{name}.stack[{position}]", errors)
- if errors:
- return None
-
- element_reports = [{
- "state": source.state,
- "track": source.track,
- "from": element["from"],
- "to": element["to"],
- "mask": element.get("mask"),
- "allow_clip": bool(element.get("allow_clip")),
- "frame_variant": source.variant,
- "state_revision": source.revision,
- "pool_frames": source.total,
- "played_frames": len(source.ordered),
- "offsets": [],
- "clipped_pixels": 0,
- } for element, source in zip(stack, sources)]
-
- cells: dict[bytes, int] = {}
- order: list[int] = [] # play position -> unique cell index
- unique: list[Image.Image] = []
- for position in range(length):
- cell = Image.new("RGBA", cell_size, (0, 0, 0, 0))
- for slot, (element, source) in enumerate(zip(stack, sources)):
- at = 0 if (source is not body and source.total == 1) else position
- frame = _instance(run_dir, request, curation, source, at, cell_size,
- snap_scale, errors)
- if frame is None:
- continue
- mask = masks.get(slot)
- if mask is not None:
- frame = apply_alpha_mask(frame, mask)
- if source is body:
- offset = (0, 0)
- else:
- offset = _element_offset(request, name, element, body, source,
- body.ordered[position], source.ordered[at], errors)
- if offset is None:
- continue
- element_reports[slot]["offsets"].append(list(offset))
- clipped = _clipped_pixels(frame, offset, cell_size)
- if clipped:
- element_reports[slot]["clipped_pixels"] += clipped
- if not element["allow_clip"]:
- errors.append(
- f"layers.{name} frame {position}: element {source.state!r} offset "
- f"{list(offset)} pushes {clipped} art pixel(s) outside the "
- f"{cell_size[0]}x{cell_size[1]} cell — declare allow_clip to accept "
- f"the loss, or move the landmarks")
- layer = Image.new("RGBA", cell_size, (0, 0, 0, 0))
- layer.paste(frame, offset)
- cell.alpha_composite(layer)
- # Identical cells share one column, exactly like the atlas: the rect list
- # is indexed by play position and repeats (docs/layer-tracks.md B7).
- key = cell.tobytes()
- index = cells.get(key)
- if index is None:
- index = len(unique)
- cells[key] = index
- unique.append(cell)
- order.append(index)
- if errors:
- return None
-
- return {
- "name": name,
- "spec": spec,
- "body": body,
- "sources": sources,
- "elements": element_reports,
- "cells": unique,
- "order": order,
- }
-
-
-def _render(run_dir: Path, request: dict[str, Any], curation: dict[str, Any] | None,
- composed: dict[str, Any], cell_size: tuple[int, int]) -> dict[str, Any]:
- """One composite's payloads + its report entry — rendered, not yet published.
-
- Nothing here touches the run dir: the caller collects every composite's
- payloads and publishes them as one set, so a bake either replaces all the
- sheets it named or none of them.
- """
- name = composed["name"]
- cell_w, cell_h = cell_size
- unique, order = composed["cells"], composed["order"]
- sheet = Image.new("RGBA", (max(1, len(unique)) * cell_w, cell_h), (0, 0, 0, 0))
- for column, cell in enumerate(unique):
- sheet.alpha_composite(cell, (column * cell_w, 0))
- rects = [{"x": index * cell_w, "y": 0, "w": cell_w, "h": cell_h} for index in order]
-
- body_entry = request["states"][composed["body"].state]
- spec = composed["spec"]
- fps = int(spec.get("fps", body_entry.get("fps", 6)))
- loop = bool(spec.get("loop", body_entry.get("loop", True)))
- variants = {source.variant for source in composed["sources"]}
- variant_summary = variants.pop() if len(variants) == 1 else "mixed"
-
- sheet_name = f"{name}.png"
- manifest_name = f"{name}.manifest.json"
- out_dir = run_dir / LAYERS_DIRNAME
-
- frame_layout = {
- "sheetWidth": sheet.width,
- "sheetHeight": sheet.height,
- "cellWidth": cell_w,
- "cellHeight": cell_h,
- "rows": {name: rects},
- }
- duration_ms = max(1, round(1000.0 / (float(fps) or 6.0)))
- manifest = {
- "characterId": request["character"]["id"],
- "engine": "component-row",
- "game_input": sheet_name,
- "degraded_static_fallback": False,
- "curation_applied": curation is not None,
- "frame_variant": variant_summary,
- "sprite_sheet_alpha": sheet_name,
- # The alpha/extraction report of THIS sheet — and a composite has none.
- # The field keeps the base manifest's key set (§5) and states the absence
- # rather than pointing at a document of another kind: `layers.report.json`
- # is the bake's provenance record for every composite, not this sheet's
- # alpha report, so a consumer resolving this field would open the wrong
- # document. The provenance pointer lives in the `layers` block below.
- "sprite_sheet_alpha_report": None,
- "base_image": request["character"].get("base_image"),
- "cell": request["cell"],
- "chroma_key": request.get("chroma_key"),
- "animation": {
- "cellWidth": cell_w,
- "cellHeight": cell_h,
- "columns": len(unique),
- "rows": {name: {
- "row": 0,
- "frames": len(order),
- "fps": fps,
- "durations_ms": [duration_ms] * len(order),
- "loop": loop,
- "frame_variant": variant_summary,
- "track": "composite",
- }},
- },
- "frame_layout": frame_layout,
- # Provenance a runtime can read without the report: what this sheet is a
- # combination of. The runtime still plays it as an ordinary one-row atlas.
- "layers": {
- "name": name,
- "report": REPORT_NAME,
- "stack": [{k: element[k] for k in ("state", "track", "from", "to", "mask",
- "allow_clip", "state_revision")}
- for element in composed["elements"]],
- },
- }
-
- buffer = io.BytesIO()
- sheet.save(buffer, format="PNG")
- return {
- "payloads": {
- out_dir / sheet_name: buffer.getvalue(),
- out_dir / manifest_name: json.dumps(manifest, ensure_ascii=False, indent=2) + "\n",
- },
- "entry": {
- "name": name,
- "sheet": sheet_name,
- "manifest": manifest_name,
- "frames": len(order),
- "cells": len(unique),
- "fps": fps,
- "loop": loop,
- "frame_variant": variant_summary,
- "body": composed["body"].state,
- "elements": composed["elements"],
- "frame_cells": order,
- },
- }
-
-
-def require_distinct_names(names: list[str], *, origin: str) -> None:
- """A selection names each composite at most once. The one place that rule lives.
-
- Both entry forms run it: `parse_names` so a CLI typo is diagnosed before the
- run dir is touched, and `bake` so a direct `bake(names=[...])` call cannot
- reach the bake without it. Both ways of passing over a repeat lie about the
- result — de-duplicating answers a selection nobody asked for, and keeping the
- repeat writes one sheet while `layers.report.json` counts two composites, so
- `composite_count` no longer matches the sheets on disk (§5).
- """
- repeated = sorted({name for name in names if names.count(name) > 1})
- if repeated:
- raise SystemExit(
- f"{origin}: composite(s) {repeated} named more than once; a selection "
- f"names each composite at most once")
-
-
-def bake(run_dir: Path | str, *, names: list[str] | None = None) -> dict[str, Any]:
- """Bake every declared composite (or just `names`) into `<run-dir>/layers/`.
-
- `names`, when given, selects declared composites and names each at most once
- (`require_distinct_names`). Returns the report that was written. Raises
- `SystemExit` listing every violation at once, having written nothing, when any
- composite cannot be baked as declared.
- """
- run_dir = Path(run_dir).expanduser().resolve()
- # Derived-cache self-heal before consuming frames — the same real-time
- # contract compose_atlas follows, and for the same reason: a composite is
- # baked from the current engine's frames or not at all.
- heal_report = heal_run(run_dir)
- for note in heal_report["notes"]:
- print(f"[heal] {note}", file=sys.stderr)
- if heal_report["healed"]:
- print(f"[heal] re-derived stale rows: {', '.join(heal_report['healed'])}", file=sys.stderr)
- acquire_run_dir_lock(run_dir, "compose_layers")
- request = load_request(run_dir)
- if not has_layer_contract(request):
- raise SystemExit(
- f"{run_dir} is not a layer run: sprite-request.json declares no rig / track / "
- f"layers. Nothing was written (docs/layer-tracks.md §1)")
- require_valid_layer_request(request)
-
- declared = request.get("layers") or {}
- if not declared:
- raise SystemExit(
- f"{run_dir}: sprite-request.json declares a rig but no `layers` composite to bake")
- wanted = sorted(declared) if names is None else list(names)
- if not wanted:
- raise SystemExit(f"{run_dir}: no composite selected; declared: {sorted(declared)}")
- require_distinct_names(wanted, origin=f"{run_dir}: names=")
- unknown = [name for name in wanted if name not in declared]
- if unknown:
- raise SystemExit(
- f"{run_dir}: no such composite(s) {unknown}; declared: {sorted(declared)}")
-
- frames_manifest = require_frames_manifest(run_dir)
- rows_by_state = {row["state"]: row for row in frames_manifest.get("rows", [])}
- curation = load_curation(run_dir)
- cell_size = cell_geometry(request["cell"])
- snap_scale = pixel_snap_scale(request)
-
- errors: list[str] = []
- composed = []
- for name in wanted:
- result = _compose_one(run_dir, request, curation, rows_by_state, name, cell_size,
- snap_scale, errors)
- if result is not None:
- composed.append(result)
- if errors:
- raise SystemExit(
- f"layer composition failed in {run_dir} (nothing written):\n - "
- + "\n - ".join(errors))
-
- rendered = [_render(run_dir, request, curation, result, cell_size) for result in composed]
- report = {
- "ok": True,
- "kind": REPORT_KIND,
- "engine": "component-row",
- "curation_applied": curation is not None,
- "cell": request["cell"],
- "rig_profile": (request.get("rig") or {}).get("profile"),
- "composite_count": len(rendered),
- "composites": [item["entry"] for item in rendered],
- }
- # One publish for the whole bake. The report is what says which sheets are
- # current (§5), so it lands with them or not at all — a sheet on disk that no
- # report names is exactly the leftover state this transaction prevents.
- payloads: dict[Path, bytes | str] = {}
- for item in rendered:
- payloads.update(item["payloads"])
- payloads[run_dir / LAYERS_DIRNAME / REPORT_NAME] = (
- json.dumps(report, ensure_ascii=False, indent=2) + "\n")
- (run_dir / LAYERS_DIRNAME).mkdir(parents=True, exist_ok=True)
- atomic_write_set(payloads)
- return report
-
-
-def load_report(run_dir: Path | str) -> dict[str, Any] | None:
- """The composite bake report of a run dir, or `None` when nothing was baked.
-
- `None` means exactly one thing — no report file — so a consumer can treat it
- as "this run has no composites" without guessing. A file that exists but is
- not a layers report is an error, never an empty result.
- """
- path = Path(run_dir) / LAYERS_DIRNAME / REPORT_NAME
- if not path.is_file():
- return None
- report = json.loads(path.read_text(encoding="utf-8"))
- if report.get("kind") != REPORT_KIND:
- raise SystemExit(f"{path} is not a {REPORT_KIND} ({report.get('kind')!r})")
- return report
-
-
-# --- CLI -------------------------------------------------------------------
-# `sprite-gen compose-layers`, `python -m sprite_gen.compose.compose_layers` and
-# `scripts/compose_layers.py` are three entry forms of ONE declaration: the CLI
-# table points at `add_arguments` / `run` below rather than restating the flags,
-# so a new option cannot reach one launch form and miss another.
-
-
-def parse_names(value: str | None) -> list[str] | None:
- """`--names a,b` -> ["a", "b"]; unset -> None (every declared composite).
-
- An empty entry is a typo (`a,,b`, a trailing comma), never "all": silently
- dropping it would bake a different set than the one that was asked for. The
- repeat rule is `require_distinct_names`, run here so a CLI typo fails before
- the run dir is touched — `bake` runs the same check for every other caller.
- """
- if value is None:
- return None
- names = [part.strip() for part in value.split(",")]
- if not names or any(not name for name in names):
- raise SystemExit(
- f"--names expects a comma-separated list of composite names (got {value!r})")
- require_distinct_names(names, origin=f"--names {value!r}")
- return names
-
-
-def add_arguments(p: argparse.ArgumentParser) -> None:
- p.add_argument("--run-dir", required=True, type=Path,
- help="run dir whose sprite-request.json declares rig / track / layers")
- p.add_argument("--names",
- help="comma-separated composite names to bake (default: every declared one)")
-
-
-def run(*, run_dir: Path, names: str | None = None) -> int:
- report = bake(run_dir, names=parse_names(names))
- print(json.dumps({
- "ok": report["ok"],
- "run_dir": str(Path(run_dir).expanduser().resolve()),
- "rig_profile": report["rig_profile"],
- "composites": [{
- "name": entry["name"],
- "sheet": f"{LAYERS_DIRNAME}/{entry['sheet']}",
- "manifest": f"{LAYERS_DIRNAME}/{entry['manifest']}",
- "frames": entry["frames"],
- "cells": entry["cells"],
- "clipped_pixels": sum(element["clipped_pixels"] for element in entry["elements"]),
- } for entry in report["composites"]],
- "report": f"{LAYERS_DIRNAME}/{REPORT_NAME}",
- }, ensure_ascii=False, indent=2))
- return 0
-
-
-def main(argv: list[str] | None = None) -> int:
- utf8_streams()
- parser = argparse.ArgumentParser(
- description="Bake a rig run's declared composite stacks into <run-dir>/layers/.")
- add_arguments(parser)
- return run(**vars(parser.parse_args(argv)))
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/sprite_gen/compose/layers.py b/sprite_gen/compose/layers.py
deleted file mode 100644
index cafe825..0000000
--- a/sprite_gen/compose/layers.py
+++ /dev/null
@@ -1,493 +0,0 @@
-# SPDX-License-Identifier: Apache-2.0
-"""Layer-track contract — rig profiles, track kinds, and composite stack validation.
-
-This module is the declaration half of the optional layer feature: it owns the
-vocabulary (`PROFILES`, `TRACKS`) and validates a `sprite-request.json` that
-declares `rig` / `states.<state>.track` / `layers`. It is filesystem-free and
-deterministic — the same request always produces the same error list, in the same
-order — so both the composer and the CLI can validate before touching a run dir.
-
-Boundary (SoC): everything here is answerable from the request alone. Run-dir
-facts — do the declared frames exist, is a mask file the right size, does an
-aligned element clip — belong to the composer, not here.
-
-Behavior contract: `docs/layer-tracks.md`. A request that declares none of these
-keys is not a layer run and validates trivially, so existing runs are untouched.
-"""
-
-from __future__ import annotations
-
-import re
-from typing import Any
-
-from sprite_gen.spec.layout import state_frame_total
-
-# Character type profiles. `required` landmarks must be declared on every pool
-# frame of every row of a rig run; `reserved` names are the recommended
-# vocabulary for optional landmarks (documentation, not a restriction — any name
-# matching LANDMARK_NAME is accepted, and must then be declared consistently
-# across the whole row).
-#
-# `root` is the composition pivot for EVERY profile. `crown` (정수리) is a
-# humanoid head landmark used for generation/QA framing, never an inferred
-# pivot: no profile derives a pivot from geometry (maintainer decision
-# 2026-07-31 — automatic semantic inference is out of the contract).
-PROFILES: dict[str, dict[str, tuple[str, ...]]] = {
- "humanoid_biped": {
- "required": ("root", "crown"),
- "reserved": ("head", "neck", "hand_l", "hand_r", "foot_l", "foot_r"),
- },
- "quadruped": {
- "required": ("root",),
- "reserved": ("head", "muzzle", "tail", "foot_fl", "foot_fr", "foot_bl", "foot_br"),
- },
- "blob_or_tentacle": {
- "required": ("root",),
- "reserved": ("mouth", "eye_l", "eye_r", "tip_a", "tip_b", "tip_c", "tip_d"),
- },
- "prop": {
- "required": ("root",),
- "reserved": ("grip", "tip", "muzzle"),
- },
-}
-
-# A row's track kind. `base` is the explicit default for an undeclared state, so
-# a non-layer run reads as an all-`base` run rather than as an unknown state.
-TRACKS = ("base", "action_overlay", "prop_effect", "full_body_override")
-# Which tracks may be a stack's single body element. This is a stack-shape rule,
-# not a "draws the character" rule: an `action_overlay` also draws the body, it
-# just may not be the element everything else is aligned onto.
-BODY_TRACKS = ("base", "full_body_override")
-DEFAULT_TRACK = "base"
-
-# A row's required landmarks come from the profile AND the row's track meaning.
-# `prop_effect` art is a prop or an effect, not the character: a watering can has
-# no 정수리, so holding it to `humanoid_biped`'s `crown` demands a landmark
-# nobody can place, and the only way out is to declare a fake one — which turns a
-# required pivot into noise on the row the composer trusts most. A prop row is
-# therefore held to the `prop` profile (its own `root`, plus whatever
-# self-meaning names like `grip` / `tip` it declares), whatever the run's rig
-# profile is. Every body-bearing row — `base`, `action_overlay`,
-# `full_body_override` — keeps the rig profile's full set, so a humanoid run
-# still cannot ship a body frame without a crown.
-TRACK_PROFILE_OVERRIDE: dict[str, str] = {"prop_effect": "prop"}
-
-LANDMARK_NAME = re.compile(r"^[a-z][a-z0-9_]{0,31}$")
-COMPOSITE_NAME = re.compile(r"^[a-z][a-z0-9_]{0,63}$")
-
-# Stack element defaults. `from` is the element's own landmark, `to` is the
-# landmark on the body element it is placed onto; both default to the pivot.
-# `revision` is an optional pin: the source row's `state_revision` segments as
-# they were when the landmarks were declared. The composer checks it (same
-# prefix rule as `curation.anchors`), so a re-rolled row fails the bake instead
-# of aligning new art to old pivots.
-ELEMENT_KEYS = ("state", "from", "to", "mask", "allow_clip", "revision")
-
-# Composite-level keys this contract reads, and the complete set a composite may
-# declare. `stack` is required; `fps` / `loop` default to the body element's state
-# entry. An unknown key is rejected exactly like an unknown stack-element key: the
-# composite spec reaches a runtime manifest, so a typo'd `loops` that is passed
-# over silently ships a composite that plays by defaults nobody asked for.
-COMPOSITE_KEYS = ("stack", "fps", "loop")
-
-
-def has_layer_contract(request: dict[str, Any]) -> bool:
- """Does this request opt into the layer feature at all?
-
- False for every request written before the feature existed, which is what
- keeps the non-layer pipeline byte-identical: no rig, no tracks, no stacks.
- """
- if request.get("rig") or request.get("layers"):
- return True
- return any(
- isinstance(entry, dict) and entry.get("track") is not None
- for entry in (request.get("states") or {}).values()
- )
-
-
-def state_track(request: dict[str, Any], state: str) -> str:
- """The declared track kind of a row — `base` when undeclared (explicit default)."""
- entry = (request.get("states") or {}).get(state)
- if not isinstance(entry, dict):
- return DEFAULT_TRACK
- track = entry.get("track")
- return DEFAULT_TRACK if track is None else str(track)
-
-
-def known_profile(profile: Any) -> str | None:
- """The declared profile this value names, or None for anything else.
-
- The single answer to "is this a known profile" — the validator and
- `required_landmarks` must not disagree about it. `isinstance` comes before
- the membership test on purpose: `rig.profile` is JSON, so it can arrive as a
- list or an object, and `unhashable in dict` raises. A malformed declaration
- has to come back as a reported error like every other one, never as a
- TypeError out of a validator whose whole contract is returning the error list.
- """
- return profile if isinstance(profile, str) and profile in PROFILES else None
-
-
-def required_landmarks(profile: Any, track: str) -> tuple[str, ...]:
- """The landmarks every pool frame of a row on this track must declare.
-
- Profile validity is decided FIRST, the track narrowing
- (`TRACK_PROFILE_OVERRIDE`) only after: an unknown profile requires nothing on
- ANY track, because `rig.profile` is already its own error and a second
- cascade of "missing crown" / "missing root" would bury it. Reading the
- override first would let a `prop_effect` row borrow the `prop` profile out of
- a run that declared no valid profile at all, so the one unknown-profile run
- that still got a landmark error was the one with a prop row in it.
- """
- name = known_profile(profile)
- if name is None:
- return ()
- return tuple(PROFILES[TRACK_PROFILE_OVERRIDE.get(track, name)]["required"])
-
-
-def resolve_element(raw: Any) -> dict[str, Any]:
- """Fill a stack element's defaults. Call only on a validated request."""
- element = dict(raw) if isinstance(raw, dict) else {}
- return {
- "state": element.get("state"),
- "from": element.get("from", "root"),
- "to": element.get("to", "root"),
- "mask": element.get("mask"),
- "allow_clip": bool(element.get("allow_clip", False)),
- "revision": element.get("revision"),
- }
-
-
-def resolve_stack(request: dict[str, Any], name: str) -> list[dict[str, Any]]:
- """The composite's elements with defaults filled, in draw order (bottom first)."""
- stack = ((request.get("layers") or {}).get(name) or {}).get("stack") or []
- return [resolve_element(element) for element in stack]
-
-
-def _pool_size(request: dict[str, Any], state: str) -> int:
- """The row's frame pool size (primary + takes), or 0 for a malformed state entry.
-
- A malformed entry is already a hard error on the extract path; here it only
- has to not raise, so the whole error list still gets reported at once.
- """
- entry = (request.get("states") or {}).get(state)
- if not isinstance(entry, dict):
- return 0
- try:
- return max(0, state_frame_total(request, state))
- except (TypeError, ValueError, KeyError):
- return 0
-
-
-def _landmark_frames(request: dict[str, Any], state: str) -> dict[str, Any]:
- return ((request.get("rig") or {}).get("landmarks") or {}).get(state) or {}
-
-
-def landmark_map(request: dict[str, Any], state: str,
- frame: int) -> dict[str, tuple[int, int]] | None:
- """Every landmark declared on one pool frame, or None when the frame declares none.
-
- None is the honest answer for an instance index nothing was declared for — a
- curated clone instance lives outside the pool (`curation.state_clones`), so it
- has no declaration and the composer fails loud instead of borrowing its
- source frame's pivots for art the clone's own transform has already moved.
- """
- points = _landmark_frames(request, state).get(str(frame))
- if not isinstance(points, dict):
- return None
- resolved = {
- str(name): (int(value[0]), int(value[1]))
- for name, value in sorted(points.items())
- if _is_point(value)
- }
- return resolved or None
-
-
-def landmark(request: dict[str, Any], state: str, frame: int, name: str) -> tuple[int, int] | None:
- """A declared landmark, or None. Never inferred, never interpolated."""
- point = _landmark_frames(request, state).get(str(frame))
- if not isinstance(point, dict):
- return None
- value = point.get(name)
- if not _is_point(value):
- return None
- return (int(value[0]), int(value[1]))
-
-
-def _is_int(value: Any) -> bool:
- # bool is an int subclass; a JSON true must not read as a coordinate.
- return isinstance(value, int) and not isinstance(value, bool)
-
-
-def _is_point(value: Any) -> bool:
- return isinstance(value, (list, tuple)) and len(value) == 2 and all(_is_int(v) for v in value)
-
-
-def _cell_bounds(request: dict[str, Any]) -> tuple[int, int] | None:
- cell = request.get("cell")
- if not isinstance(cell, dict):
- return None
- width = cell.get("width", cell.get("size"))
- height = cell.get("height", cell.get("size"))
- if not _is_int(width) or not _is_int(height) or width <= 0 or height <= 0:
- return None
- return int(width), int(height)
-
-
-def _validate_rig(request: dict[str, Any], errors: list[str]) -> None:
- rig = request.get("rig")
- if rig is None:
- return
- if not isinstance(rig, dict):
- errors.append("rig must be an object")
- return
- profile = rig.get("profile")
- if known_profile(profile) is None:
- errors.append(
- f"rig.profile must be one of {', '.join(sorted(PROFILES))} (got {profile!r})")
- landmarks = rig.get("landmarks", {})
- if not isinstance(landmarks, dict):
- errors.append("rig.landmarks must be an object keyed by state")
- return
- states = request.get("states") or {}
- bounds = _cell_bounds(request)
- for state in sorted(landmarks):
- if state not in states:
- errors.append(f"rig.landmarks declares unknown state {state!r}")
- continue
- track = state_track(request, state)
- _validate_state_landmarks(request, state, landmarks[state],
- required_landmarks(profile, track), track, bounds, errors)
-
-
-def _validate_state_landmarks(request: dict[str, Any], state: str, frames: Any,
- required: tuple[str, ...], track: str,
- bounds: tuple[int, int] | None,
- errors: list[str]) -> None:
- if not isinstance(frames, dict):
- errors.append(f"rig.landmarks.{state} must be an object keyed by frame index")
- return
- total = _pool_size(request, state)
- declared = set()
- for key in sorted(frames):
- if not (isinstance(key, str) and key.isdigit()):
- errors.append(f"rig.landmarks.{state} frame key {key!r} must be a decimal index string")
- continue
- index = int(key)
- if index >= total:
- errors.append(
- f"rig.landmarks.{state} frame {index} is outside the row's frame pool "
- f"(0..{total - 1}) — landmarks are indexed by pool position, takes included")
- continue
- declared.add(index)
- missing = [i for i in range(total) if i not in declared]
- if missing:
- errors.append(
- f"rig.landmarks.{state} is missing frame(s) {missing} — every pool frame needs "
- f"declared landmarks (an undeclared pivot is not guessed)")
- # A landmark must be declared on the WHOLE row: a name that appears on some
- # frames and not others would make a composite silently skip frames.
- per_frame: dict[int, set[str]] = {}
- for key in sorted(frames):
- if not (isinstance(key, str) and key.isdigit()) or int(key) >= total:
- continue
- index = int(key)
- point_map = frames[key]
- if not isinstance(point_map, dict):
- errors.append(f"rig.landmarks.{state}.{key} must be an object of landmark -> [x, y]")
- continue
- names = set()
- for name in sorted(point_map):
- if not LANDMARK_NAME.match(str(name)):
- errors.append(
- f"rig.landmarks.{state}.{key} landmark name {name!r} must match "
- f"{LANDMARK_NAME.pattern}")
- continue
- value = point_map[name]
- if not _is_point(value):
- errors.append(
- f"rig.landmarks.{state}.{key}.{name} must be [x, y] integers "
- f"(pivots are integer cell coordinates)")
- continue
- if bounds and not (0 <= value[0] < bounds[0] and 0 <= value[1] < bounds[1]):
- errors.append(
- f"rig.landmarks.{state}.{key}.{name} {list(value)} is outside the "
- f"{bounds[0]}x{bounds[1]} cell")
- continue
- names.add(str(name))
- per_frame[index] = names
- for name in required:
- absent = sorted(i for i, names in per_frame.items() if name not in names)
- if absent:
- errors.append(
- f"rig.landmarks.{state} frame(s) {absent} miss required landmark {name!r} — "
- f"a {track!r} row requires {', '.join(required)} on every frame")
- if per_frame:
- union: set[str] = set().union(*per_frame.values())
- for name in sorted(union):
- partial = sorted(i for i, names in per_frame.items() if name not in names)
- if partial and len(partial) != len(per_frame):
- errors.append(
- f"rig.landmarks.{state} declares {name!r} on some frames but not "
- f"{partial} — a landmark is declared for the whole row or not at all")
-
-
-def _validate_tracks(request: dict[str, Any], errors: list[str]) -> None:
- for state in sorted(request.get("states") or {}):
- entry = (request["states"] or {})[state]
- if not isinstance(entry, dict) or entry.get("track") is None:
- continue
- if entry["track"] not in TRACKS:
- errors.append(
- f"states.{state}.track must be one of {', '.join(TRACKS)} "
- f"(got {entry['track']!r})")
-
-
-def _validate_layers(request: dict[str, Any], errors: list[str]) -> None:
- composites = request.get("layers")
- if composites is None:
- return
- if not isinstance(composites, dict):
- errors.append("layers must be an object keyed by composite name")
- return
- states = request.get("states") or {}
- for name in sorted(composites):
- if not COMPOSITE_NAME.match(str(name)):
- errors.append(f"layers.{name}: name must match {COMPOSITE_NAME.pattern}")
- if name in states:
- errors.append(
- f"layers.{name}: a composite name must not collide with a request state — "
- f"composites are a separate artifact tree, not extra rows")
- spec = composites[name]
- if not isinstance(spec, dict):
- errors.append(f"layers.{name} must be an object")
- continue
- unknown = sorted(set(spec) - set(COMPOSITE_KEYS))
- if unknown:
- errors.append(
- f"layers.{name} has unknown key(s) {unknown}; "
- f"allowed: {', '.join(COMPOSITE_KEYS)}")
- # `fps` / `loop` reach the composite manifest verbatim, so a string fps
- # would be baked into a runtime contract. Typed here, where the whole
- # declaration is checked before a run dir is touched.
- if "fps" in spec and not (_is_int(spec["fps"]) and spec["fps"] > 0):
- errors.append(
- f"layers.{name}.fps must be a positive integer (got {spec['fps']!r})")
- if "loop" in spec and not isinstance(spec["loop"], bool):
- errors.append(f"layers.{name}.loop must be true or false (got {spec['loop']!r})")
- stack = spec.get("stack")
- if not isinstance(stack, list) or not stack:
- errors.append(f"layers.{name}.stack must be a non-empty list of elements")
- continue
- _validate_stack(request, name, stack, errors)
-
-
-def _validate_stack(request: dict[str, Any], name: str, stack: list[Any],
- errors: list[str]) -> None:
- states = request.get("states") or {}
- resolved: list[dict[str, Any]] = []
- for position, raw in enumerate(stack):
- if not isinstance(raw, dict):
- errors.append(f"layers.{name}.stack[{position}] must be an object")
- continue
- unknown = sorted(set(raw) - set(ELEMENT_KEYS))
- if unknown:
- errors.append(
- f"layers.{name}.stack[{position}] has unknown key(s) {unknown}; "
- f"allowed: {', '.join(ELEMENT_KEYS)}")
- pin = raw.get("revision")
- if pin is not None and not (isinstance(pin, list) and pin
- and all(isinstance(seg, str) for seg in pin)):
- errors.append(
- f"layers.{name}.stack[{position}].revision must be a non-empty list of "
- f"state_revision segment strings (it pins the generation the landmarks "
- f"were declared against)")
- state = raw.get("state")
- if not isinstance(state, str) or state not in states:
- errors.append(
- f"layers.{name}.stack[{position}].state must name a request state "
- f"(got {state!r})")
- continue
- element = resolve_element(raw)
- element["position"] = position
- element["track"] = state_track(request, state)
- resolved.append(element)
- if not resolved:
- return
-
- body = [e for e in resolved if e["track"] in BODY_TRACKS]
- if not body:
- errors.append(
- f"layers.{name}: a stack needs exactly one body element "
- f"({' or '.join(BODY_TRACKS)}); found none")
- return
- if len(body) > 1:
- errors.append(
- f"layers.{name}: a stack has exactly one body element, got "
- f"{[e['state'] for e in body]} — a full_body_override replaces the base "
- f"instead of stacking with it")
- return
- body_element = body[0]
- if body_element["position"] != 0:
- errors.append(
- f"layers.{name}: the body element {body_element['state']!r} must be stack[0]; "
- f"list order is draw order, bottom first")
- if body_element["track"] == "full_body_override":
- overlays = [e["state"] for e in resolved if e["track"] == "action_overlay"]
- if overlays:
- errors.append(
- f"layers.{name}: full_body_override {body_element['state']!r} forbids "
- f"action_overlay element(s) {overlays} — an exception state owns the whole body")
-
- body_total = _pool_size(request, body_element["state"])
- for element in resolved:
- if element is body_element:
- continue
- total = _pool_size(request, element["state"])
- if total not in (1, body_total):
- errors.append(
- f"layers.{name}: element {element['state']!r} has {total} pool frames; "
- f"an overlay runs with the body ({body_total}) or holds a single frame (1)")
- _validate_element_landmarks(request, name, element, body_element, errors)
-
-
-def _validate_element_landmarks(request: dict[str, Any], name: str, element: dict[str, Any],
- body_element: dict[str, Any], errors: list[str]) -> None:
- if request.get("rig") is None:
- errors.append(
- f"layers.{name}: element {element['state']!r} needs a rig block — a composite "
- f"aligns declared landmarks, and there are none")
- return
- for role, state, wanted in (
- ("from", element["state"], element["from"]),
- ("to", body_element["state"], element["to"]),
- ):
- total = _pool_size(request, state)
- absent = [i for i in range(total) if landmark(request, state, i, str(wanted)) is None]
- if absent:
- errors.append(
- f"layers.{name}: element {element['state']!r} aligns {role}={wanted!r} but "
- f"state {state!r} does not declare it on frame(s) {absent}")
-
-
-def validate_layer_request(request: dict[str, Any]) -> list[str]:
- """Every layer-contract violation in this request, deterministically ordered.
-
- Empty list = the request's layer declarations are self-consistent. A request
- with no layer keys always returns []; validation never invents a requirement
- for a run that did not opt in.
- """
- if not has_layer_contract(request):
- return []
- errors: list[str] = []
- _validate_rig(request, errors)
- _validate_tracks(request, errors)
- _validate_layers(request, errors)
- return errors
-
-
-def require_valid_layer_request(request: dict[str, Any]) -> None:
- """Fail loud with every violation at once (No Silent Fallback)."""
- errors = validate_layer_request(request)
- if errors:
- raise SystemExit(
- "invalid layer contract in sprite-request.json:\n - " + "\n - ".join(errors))
diff --git a/sprite_gen/gen/prepare.py b/sprite_gen/gen/prepare.py
index 2ffdfba..129bca7 100644
--- a/sprite_gen/gen/prepare.py
+++ b/sprite_gen/gen/prepare.py
@@ -23,7 +23,6 @@ from sprite_gen.util.cli_kwargs import namespace_from_kwargs
from sprite_gen.util.hexcolor import format_hex, parse_hex
from sprite_gen.curate.anchor import anchor_ref_rel
from sprite_gen.frames.extract import color_distance
-from sprite_gen.compose.layers import require_valid_layer_request
from sprite_gen.spec.layout import TAXONOMY, guide_rel, prompt_rel, raw_rel
from sprite_gen.spec.subject import SUBJECTS
from sprite_gen.video import body_plan as body_mod
@@ -503,12 +502,6 @@ def normalize_states(raw: dict[str, Any] | None, bodies: list[Body] | None = Non
"action": str(entry.get("action") if raw and "action" in entry
else defaults.get(state, DEFAULT_STATES.get(state, {}).get("action", state))),
}
- # A row's track kind is request truth (docs/layer-tracks.md §3.2) and is
- # carried only when declared: an undeclared row IS `base`, and writing
- # that default into every request would turn every new run into a layer
- # run (`has_layer_contract`).
- if entry.get("track") is not None:
- normalized[state]["track"] = entry["track"]
return normalized
@@ -516,17 +509,16 @@ def normalize_states(raw: dict[str, Any] | None, bodies: list[Body] | None = Non
# `sprite-request.json` from these lists rather than passing the request through,
# so anything outside them is dropped — which is how `states.<state>.takes`, a
# documented first-class key, ended up having to be hand-written into the file
-# after the fact (docs/layer-tracks.md §2 B1). The lists are the one place that
-# rule is written down, and `dropped_key_notes` makes every drop observable
-# instead of silent.
+# after the fact. The lists are the one place that rule is written down, and
+# `dropped_key_notes` makes every drop observable instead of silent.
REQUEST_KEYS_CARRIED = ("cell", "states", "style", "subject",
- "directions", "fit", "rig", "layers", "body_plan")
+ "directions", "fit", "body_plan")
# Written by prepare itself, from CLI flags and from measuring the base image. An
# incoming copy is not carried either, but it is restated rather than lost, so the
# note names it separately: `character` comes from --character-id/--description/
# --base-image, `chroma_key` from --chroma-key + the base image.
REQUEST_KEYS_REGENERATED = ("version", "kind", "engine", "character", "chroma_key", "layout")
-STATE_KEYS_CARRIED = ("frames", "fps", "loop", "action", "track")
+STATE_KEYS_CARRIED = ("frames", "fps", "loop", "action")
def dropped_key_notes(raw_request: dict[str, Any]) -> list[str]:
@@ -1059,14 +1051,6 @@ def _run(args: argparse.Namespace):
if directions:
states = ensure_direction_anchors(directions, states)
cell = normalize_cell(dict(raw_request.get("cell", {})), CELL_SIZE_DEFAULT, None)
-
- # Layer keys are carried explicitly (docs/layer-tracks.md §7) and validated
- # before the run dir is touched: the layer validator is filesystem-free, so a
- # malformed rig fails with every violation at once instead of leaving a
- # scaffolded run whose first bake is the thing that reports it.
- layer_keys = {key: raw_request[key] for key in ("rig", "layers")
- if raw_request.get(key) is not None}
- require_valid_layer_request({"cell": cell, "states": states, **layer_keys})
for note in dropped_key_notes(incoming):
print(f"[prepare] {note}", file=sys.stderr)
@@ -1114,9 +1098,6 @@ def _run(args: argparse.Namespace):
fit = dict(raw_request.get("fit", {}))
if fit:
request["fit"] = fit
- # Optional layer declaration, validated above. Absent = a non-layer run whose
- # emitted key set is exactly what it was before the feature existed.
- request.update(layer_keys)
for directory in (out_dir / "references" / "layout-guides", out_dir / "prompts",
out_dir / "raw", out_dir / "frames"):
diff --git a/sprite_gen/spec/migrate_request.py b/sprite_gen/spec/migrate_request.py
index 6b402d3..8304a6e 100644
--- a/sprite_gen/spec/migrate_request.py
+++ b/sprite_gen/spec/migrate_request.py
@@ -1,9 +1,10 @@
# SPDX-License-Identifier: Apache-2.0
-"""은퇴한 `fit` 키를 런의 `sprite-request.json` 에서 현행 키로 옮긴다 (일회성, 명시 실행).
+"""은퇴한 키를 런의 `sprite-request.json` 에서 현행 스키마로 옮긴다 (일회성, 명시 실행).
-`fit.pixel_perfect` 는 2026-07-25 에 `fit.pixel_unfake` 로 교체됐다. 로더
-(`runio.load_request`) 는 은퇴 키를 **메모리에서만** 현행 키로 읽어 기존 런이 무손실로
-계속 돌게 하고, 디스크 스키마를 실제로 바꾸는 일은 이 명령에서만 한다.
+`fit.pixel_perfect` 는 2026-07-25 에 `fit.pixel_unfake` 로 교체됐고, `rig`·`layers`·
+`states.<state>.track` 은 v3.0.0 에서 layer-tracks(`compose-layers`)와 함께 대신하는 키 없이
+은퇴했다. 로더(`runio.load_request`) 는 은퇴 키를 **메모리에서만** 현행 스키마로 읽어(옮기거나
+떼어) 기존 런이 계속 돌게 하고, 디스크 스키마를 실제로 바꾸는 일은 이 명령에서만 한다.
왜 나뉘어 있나: 예전엔 로더가 정규화한 문서를 곧바로 다시 썼고, 그래서 승인된 런에
`state_revision()` 을 부른 것만으로 그 런의 `sprite-request.json` 이 재기록됐다. 조회가
@@ -11,7 +12,8 @@ canonical 런의 바이트를 바꾸면 `run_revision`(request 바이트를 해
그 런의 큐레이션 사이드카가 stale 로 떨어진다. 읽는 쪽은 읽기만 하고, 쓰는 일은 사용자가
부른 명령 안에서만 일어난다 (plan sprite-gen/state-revision-read-mutation).
-이 명령이 바꾸는 것은 키 이름 하나뿐이고 값·의미는 그대로다. 다만 파일 바이트가 바뀌므로
+이 명령이 바꾸는 것은 은퇴 키뿐이다: 이름이 바뀐 키는 값·의미가 그대로고, 걷어 내는 키는
+이미 아무도 읽지 않는다. 다만 파일 바이트가 바뀌므로
`run_revision` 은 바뀐다 — 큐레이션 사이드카는 행별 `revision` 스탬프로 구제되고
(`curation.load_curation_report`), 스탬프가 없는 행은 평소 규칙대로 드롭된다. 그 결과를
쓰기 전에 미리 말한다: 조용히 잃는 것이 없어야 사용자가 실행 시점을 고를 수 있다.
@@ -24,7 +26,7 @@ import json
from pathlib import Path
from sprite_gen.curate.curation import CURATION_FILENAME, run_revision
-from sprite_gen.spec.runio import LEGACY_FIT_KEYS, REQUEST_FILENAME, migrate_request_file
+from sprite_gen.spec.runio import REQUEST_FILENAME, migrate_request_file
def add_arguments(parser: argparse.ArgumentParser) -> None:
@@ -62,18 +64,18 @@ def run(**kwargs: object) -> int:
print(f"migrate-request: {path} 가 없다")
return 1
- moved = ", ".join(f"{legacy} -> {current}" for legacy, current in LEGACY_FIT_KEYS.items())
- if not migrate_request_file(run_dir):
+ moved = migrate_request_file(run_dir)
+ if not moved:
print(f"migrate-request: {path} 는 이미 현행 키뿐이다 — 옮길 것이 없다")
return 0
- print(f"migrate-request: {path} 의 은퇴 fit 키 이관 ({moved})")
+ print(f"migrate-request: {path} 의 은퇴 키 이관 ({', '.join(moved)})")
for line in _curation_impact(run_dir):
print(f" {line}")
if not apply_changes:
print("migrate-request: dry-run. 실제로 쓰려면 --apply")
return 0
migrate_request_file(run_dir, apply=True)
- print(f"migrate-request: {path} 갱신. 값·의미는 그대로고 키 이름만 바뀐다 "
- f"(파일 바이트가 바뀌므로 run_revision 은 움직인다).")
+ print(f"migrate-request: {path} 갱신. 이름이 바뀐 키는 값·의미가 그대로고, 걷어 낸 키는 "
+ f"이미 읽히지 않던 것이다 (파일 바이트가 바뀌므로 run_revision 은 움직인다).")
return 0
diff --git a/sprite_gen/spec/runio.py b/sprite_gen/spec/runio.py
index 37aa74e..a17155a 100644
--- a/sprite_gen/spec/runio.py
+++ b/sprite_gen/spec/runio.py
@@ -402,29 +402,53 @@ REQUEST_FILENAME = "sprite-request.json"
# domains/tools/spritefusion-pixel-snapper.md 용어 각주).
LEGACY_FIT_KEYS = {"pixel_perfect": "pixel_unfake"}
-
-def normalize_retired_fit_keys(request: dict, where: str) -> bool:
- """은퇴 키를 현행 키로 옮긴다 (**메모리 in-place**, 디스크는 손대지 않는다). 옮겼으면 True.
-
- 두 키가 동시에 있으면 **hard fail** — 어느 쪽이 진실인지 코드가 고를 수 없고, 고르는
- 순간 그게 조용한 폴백이다. 이건 읽기 정규화이지 이관이 아니다: 디스크 스키마를 바꾸는
- 쪽은 `migrate_request_file` 하나뿐이고, 이 함수는 그 writer 도 같이 쓴다 (키 매핑이
- 두 벌 생기지 않게)."""
+# 대신하는 키 없이 은퇴한 키. v3.0.0 에서 layer-tracks(`compose-layers`)가 빠지면서 최상위
+# `rig`·`layers` 와 행마다의 `states.<state>.track` 을 읽는 코드가 없어졌다. 옛 런 파일에는
+# 남아 있을 수 있어서 이름이 바뀐 키와 같은 길을 탄다: 읽기는 메모리에서 떼고 한 번 알리며,
+# 파일에서 걷어 내는 것은 `migrate_request_file` 하나다.
+RETIRED_REQUEST_KEYS = ("rig", "layers")
+RETIRED_STATE_KEYS = ("track",)
+
+
+def normalize_retired_keys(request: dict, where: str) -> list[str]:
+ """은퇴 키를 현행 스키마로 옮긴다 (**메모리 in-place**, 디스크는 손대지 않는다).
+
+ 이름이 바뀐 키(`LEGACY_FIT_KEYS`)는 현행 키로 옮기고, 대신하는 키가 없는 키
+ (`RETIRED_REQUEST_KEYS`, `RETIRED_STATE_KEYS`)는 뗀다. 옮긴 것을 한 줄씩 돌려준다
+ (`fit.pixel_perfect -> fit.pixel_unfake`, `rig (not read)`, `states.walk.track (not read)`);
+ 빈 목록이면 은퇴 키가 없었다.
+
+ 같은 설정의 은퇴 키와 현행 키가 동시에 있으면 **hard fail** — 어느 쪽이 진실인지 코드가
+ 고를 수 없고, 고르는 순간 그게 조용한 폴백이다. 이건 읽기 정규화이지 이관이 아니다: 디스크
+ 스키마를 바꾸는 쪽은 `migrate_request_file` 하나뿐이고, 이 함수는 그 writer 도 같이 쓴다
+ (키 매핑이 두 벌 생기지 않게)."""
+ moved: list[str] = []
fit = request.get("fit")
- if not isinstance(fit, dict):
- return False
- moved = False
- for legacy, current in LEGACY_FIT_KEYS.items():
- if legacy not in fit:
- continue
- if current in fit:
- raise SystemExit(
- f"{where}: both `fit.{legacy}` (retired) and "
- f"`fit.{current}` are present — two truths for one setting. Delete the "
- f"`fit.{legacy}` line (its value was {fit[legacy]!r}); the current key is "
- f"`fit.{current}` = {fit[current]!r}.")
- fit[current] = fit.pop(legacy)
- moved = True
+ if isinstance(fit, dict):
+ for legacy, current in LEGACY_FIT_KEYS.items():
+ if legacy not in fit:
+ continue
+ if current in fit:
+ raise SystemExit(
+ f"{where}: both `fit.{legacy}` (retired) and "
+ f"`fit.{current}` are present — two truths for one setting. Delete the "
+ f"`fit.{legacy}` line (its value was {fit[legacy]!r}); the current key is "
+ f"`fit.{current}` = {fit[current]!r}.")
+ fit[current] = fit.pop(legacy)
+ moved.append(f"fit.{legacy} -> fit.{current}")
+ for key in RETIRED_REQUEST_KEYS:
+ if key in request:
+ del request[key]
+ moved.append(f"{key} (not read)")
+ states = request.get("states")
+ if isinstance(states, dict):
+ for state, entry in states.items():
+ if not isinstance(entry, dict):
+ continue
+ for key in RETIRED_STATE_KEYS:
+ if key in entry:
+ del entry[key]
+ moved.append(f"states.{state}.{key} (not read)")
return moved
@@ -434,8 +458,8 @@ def normalize_retired_fit_keys(request: dict, where: str) -> bool:
_RETIRED_KEY_NOTICED: set[str] = set()
-def _read_request_document(run_dir: Path) -> tuple[Path, dict, bool]:
- """`sprite-request.json` 을 읽어 (경로, 정규화된 문서, 은퇴 키가 있었나) 를 돌려준다.
+def _read_request_document(run_dir: Path) -> tuple[Path, dict, list[str]]:
+ """`sprite-request.json` 을 읽어 (경로, 정규화된 문서, 옮긴 은퇴 키) 를 돌려준다.
request 파일을 실제로 여는 곳은 여기 하나다 — 읽기 게이트와 이관 writer 가 같은 판독
(두 키 hard fail 포함)을 쓰게 하려면 파싱이 한 벌이어야 한다."""
@@ -443,14 +467,15 @@ def _read_request_document(run_dir: Path) -> tuple[Path, dict, bool]:
if not path.is_file():
raise SystemExit(f"not a sprite-gen run dir (no {REQUEST_FILENAME}): {run_dir}")
request = json.loads(path.read_text(encoding="utf-8"))
- return path, request, normalize_retired_fit_keys(request, str(path))
+ return path, request, normalize_retired_keys(request, str(path))
def load_request(run_dir: Path) -> dict:
"""런의 numeric SSoT (`sprite-request.json`) 를 읽는 **유일한 게이트**. 읽기만 한다.
- 은퇴한 키(`fit.pixel_perfect`)는 현행 키(`fit.pixel_unfake`)로 **메모리에서만** 정규화
- 되고 파일은 바이트 그대로 남는다. 두 키가 동시에 있으면 hard fail.
+ 은퇴한 키(`fit.pixel_perfect`)는 현행 키(`fit.pixel_unfake`)로, 대신하는 키가 없는 은퇴 키
+ (`rig`, `layers`, `states.<state>.track`)는 떼어 **메모리에서만** 정규화되고 파일은 바이트
+ 그대로 남는다. 은퇴 키와 현행 키가 동시에 있으면 hard fail.
합성 회귀는 이 함수가 정규화한 문서를 디스크에 다시 쓰면 조회만으로
`sprite-request.json` 과 `run_revision` 이 움직여 큐레이션 사이드카를 stale 로
@@ -458,21 +483,21 @@ def load_request(run_dir: Path) -> dict:
디스크 스키마 이관은 사용자가 명시적으로 부르는 단일 writer 에서만 원자적으로 한다:
`migrate_request_file()` / `sprite-gen migrate-request <run-dir> --apply`."""
- path, request, had_retired = _read_request_document(run_dir)
- if had_retired and str(path) not in _RETIRED_KEY_NOTICED:
+ path, request, retired = _read_request_document(run_dir)
+ if retired and str(path) not in _RETIRED_KEY_NOTICED:
_RETIRED_KEY_NOTICED.add(str(path))
- print(f"[request] retired fit key(s) "
- f"{', '.join(f'{k} -> {v}' for k, v in LEGACY_FIT_KEYS.items())} read as the "
- f"current key(s); the file is unchanged. Run `sprite-gen migrate-request "
- f"{run_dir} --apply` to move the schema on disk: {path}", file=sys.stderr)
+ print(f"[request] retired key(s) in {path}: {', '.join(retired)}. They are read as "
+ f"the current schema in memory and the file is unchanged; `sprite-gen "
+ f"migrate-request {run_dir} --apply` moves the schema on disk.", file=sys.stderr)
return request
-def migrate_request_file(run_dir: Path, *, apply: bool = False) -> bool:
- """은퇴한 `fit` 키를 디스크에서 현행 키로 옮긴다 — request 스키마의 **유일한 이관 writer**.
+def migrate_request_file(run_dir: Path, *, apply: bool = False) -> list[str]:
+ """은퇴 키를 디스크에서 현행 스키마로 옮긴다 — request 스키마의 **유일한 이관 writer**.
- Returns True 면 옮길 것이 있었다는 뜻이다 (`apply=False` 인 dry run 에서도 True).
- 이미 현행 키뿐이면 False (멱등 — 두 번째 실행은 아무것도 쓰지 않는다).
+ 이름이 바뀐 키는 현행 키로 옮기고 대신하는 키가 없는 키는 걷어 낸다
+ (`normalize_retired_keys`). 옮긴 것(또는 `apply=False` 인 dry run 에서 옮길 것)을 그 함수의
+ 줄로 돌려준다. 이미 현행 키뿐이면 빈 목록 (멱등 — 두 번째 실행은 아무것도 쓰지 않는다).
Isolation: `sprite-request.json` 의 read-modify-write 는 **편집 writer 와 같은 격리
도메인**(`publish_guard` 배타락) 안에서만 일어난다 — 락 획득 **후** fresh 재독하고
@@ -496,30 +521,32 @@ def migrate_request_file(run_dir: Path, *, apply: bool = False) -> bool:
with publish_guard(run_dir):
# 락 안 fresh 재독 — 여기서 읽은 문서와 아래 원자 교체 사이에 다른 writer 가 낄 수
# 없다는 것이 이 함수의 lost-update 계약이다 (편집 writer 와 같은 배타락).
- path, request, had_retired = _read_request_document(run_dir)
- if not had_retired:
- return False
+ path, request, retired = _read_request_document(run_dir)
+ if not retired:
+ return []
atomic_write_text(path, json.dumps(request, ensure_ascii=False, indent=2) + "\n")
_RETIRED_KEY_NOTICED.discard(str(path))
- return True
+ return retired
def write_request(run_dir: Path, request: dict) -> None:
"""편집한 request 를 원자적으로 다시 쓴다 — **디스크의 키 형태를 보존한다**.
take 기록·fps 편집처럼 스키마와 무관한 편집도 로더가 정규화해 준 문서를 통째로 되쓴다.
- 그대로 쓰면 그 편집이 은퇴 키를 조용히 현행 키로 바꿔, 스키마 이관이 다시 "아무 명령이나
- 하는 김에 하는 일" 이 된다. 로더가 메모리에서 편 것을 쓰기 직전에 되접으면, 디스크
- 스키마를 바꾸는 곳은 `migrate_request_file` 하나로 남는다.
+ 그대로 쓰면 그 편집이 은퇴 키를 조용히 현행 키로 바꾸거나 떼어 내, 스키마 이관이 다시
+ "아무 명령이나 하는 김에 하는 일" 이 된다. 로더가 메모리에서 편 것을 쓰기 직전에 되접으면
+ (이름이 바뀐 키는 옛 이름으로, 뗀 키는 디스크의 값 그대로), 디스크 스키마를 바꾸는 곳은
+ `migrate_request_file` 하나로 남는다.
호출부의 dict 는 건드리지 않는다 (쓴 뒤에도 현행 키로 계속 쓰인다)."""
path = Path(run_dir) / REQUEST_FILENAME
- on_disk_fit: dict = {}
try:
on_disk = json.loads(path.read_text(encoding="utf-8"))
- on_disk_fit = on_disk.get("fit") if isinstance(on_disk.get("fit"), dict) else {}
except (OSError, ValueError):
- on_disk_fit = {} # 첫 발행이거나 읽을 수 없다 — 되접을 형태가 없으니 그대로 쓴다
+ on_disk = {} # 첫 발행이거나 읽을 수 없다 — 되접을 형태가 없으니 그대로 쓴다
+ if not isinstance(on_disk, dict):
+ on_disk = {}
+ on_disk_fit = on_disk.get("fit") if isinstance(on_disk.get("fit"), dict) else {}
fit = request.get("fit")
if isinstance(fit, dict):
restore = {current: legacy for legacy, current in LEGACY_FIT_KEYS.items()
@@ -531,4 +558,23 @@ def write_request(run_dir: Path, request: dict) -> None:
# `{logical_height, pixel_perfect}` 로 쓰인다 (이름은 보존, 자리는 이동).
request = {**request, "fit": {restore.get(key, key): value
for key, value in fit.items()}}
+ # 뗀 키는 디스크에 있던 값을 그대로 되돌린다 (자리는 끝으로 간다). 아무 코드도 쓰지 않는
+ # 키라 이 편집의 값이 있을 수 없다 — 디스크에 있으면 그게 유일한 값이다.
+ kept = {key: on_disk[key] for key in RETIRED_REQUEST_KEYS
+ if key in on_disk and key not in request}
+ if kept:
+ request = {**request, **kept}
+ states, disk_states = request.get("states"), on_disk.get("states")
+ if isinstance(states, dict) and isinstance(disk_states, dict):
+ kept_states = {}
+ for state, entry in states.items():
+ disk_entry = disk_states.get(state)
+ if not (isinstance(entry, dict) and isinstance(disk_entry, dict)):
+ continue
+ kept_keys = {key: disk_entry[key] for key in RETIRED_STATE_KEYS
+ if key in disk_entry and key not in entry}
+ if kept_keys:
+ kept_states[state] = {**entry, **kept_keys}
+ if kept_states:
+ request = {**request, "states": {**states, **kept_states}}
atomic_write_text(path, json.dumps(request, ensure_ascii=False, indent=2) + "\n")
diff --git a/tests/compose/test_layer_compose.py b/tests/compose/test_layer_compose.py
deleted file mode 100644
index 1998a24..0000000
--- a/tests/compose/test_layer_compose.py
+++ /dev/null
@@ -1,660 +0,0 @@
-# SPDX-License-Identifier: Apache-2.0
-"""Composite bake — deterministic stacking, run-dir diagnostics, and what it must not touch.
-
-`sprite_gen.compose.layers` answers what a request may declare; this file covers what only
-the run dir can answer (`docs/layer-tracks.md` §4/§5):
-
-1. the bake itself — integer pivot translation, arbitrary alpha masks, cell reuse,
- and the same bytes on every run;
-2. the diagnostics — a missing frame, an unusable mask, a clipped element, a
- re-rolled source row, a curated clone with no declared pivot;
-3. the boundaries — nothing is written when a bake fails, and a non-layer run is
- refused rather than half-composed;
-4. the published CLI (`sprite-gen compose-layers`, §7) — exit code, summary, and
- the same guarantees across a process boundary.
-"""
-
-from __future__ import annotations
-
-import hashlib
-import json
-from pathlib import Path
-
-import pytest
-from PIL import Image, ImageDraw
-
-from sprite_gen.compose import compose_layers
-from sprite_gen.curate.curation import empty_curation, write_curation_atomic
-
-from conftest import run_script
-
-MAGENTA = (255, 0, 255)
-CELL = 96
-
-# Declared pivots. Values are in-cell integers; the bake never infers one, so the
-# only thing that matters here is that the same names exist on every pool frame.
-# `can` is a `prop_effect` row, so it declares its own `root` / `grip` and no
-# `crown`: required landmarks follow profile AND track (`layer-tracks.md` §3.1).
-LANDMARKS = {
- "walk": {
- "0": {"root": [48, 60], "crown": [48, 30], "hand_r": [60, 50]},
- "1": {"root": [48, 61], "crown": [48, 40], "hand_r": [62, 52]},
- },
- "hold": {
- "0": {"root": [48, 60], "crown": [48, 30], "hand_r": [58, 50]},
- "1": {"root": [48, 60], "crown": [48, 30], "hand_r": [58, 50]},
- },
- "can": {"0": {"root": [48, 72], "grip": [48, 72]}},
-}
-
-
-def _strip(shapes: list[tuple[tuple[int, int, int, int], tuple[int, int, int]]],
- frames: int) -> Image.Image:
- """A magenta row strip whose shapes sit inside the cell safe area."""
- strip = Image.new("RGB", (frames * CELL, CELL), MAGENTA)
- draw = ImageDraw.Draw(strip)
- for box, fill in shapes:
- draw.rectangle(box, fill=fill)
- return strip
-
-
-def _request(**overrides) -> dict:
- request = {
- "version": 1,
- "kind": "sprite-gen-request",
- "engine": "component-row",
- "character": {"id": "rigbot", "description": "layer bake fixture", "base_image": None},
- "cell": {"shape": "square", "width": CELL, "height": CELL, "safe_margin_x": 8,
- "safe_margin_y": 8, "size": CELL, "safe_margin": 8},
- "chroma_key": {"name": "magenta", "hex": "#FF00FF", "rgb": [255, 0, 255],
- "selection": "fallback"},
- "states": {
- "walk": {"frames": 2, "fps": 8, "loop": True, "action": "walk", "track": "base"},
- "hold": {"frames": 2, "fps": 8, "loop": True, "action": "hold", "track": "base"},
- "can": {"frames": 1, "fps": 8, "loop": False, "action": "prop",
- "track": "prop_effect"},
- },
- "style": "flat solid shapes on magenta",
- "rig": {"profile": "humanoid_biped", "landmarks": json.loads(json.dumps(LANDMARKS))},
- "layers": {
- "walk_with_can": {"stack": [
- {"state": "walk"},
- {"state": "can", "from": "grip", "to": "hand_r"},
- ]},
- },
- }
- request.update(overrides)
- return request
-
-
-def _write_request(run_dir: Path, request: dict) -> None:
- (run_dir / "sprite-request.json").write_text(
- json.dumps(request, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
-
-
-def _build_run(tmp_path: Path, request: dict | None = None, *, extract: bool = True) -> Path:
- run_dir = tmp_path / "run"
- (run_dir / "raw").mkdir(parents=True)
- _strip([((12, 20, 51, 79), (40, 180, 60)),
- ((108, 30, 157, 79), (60, 160, 80))], 2).save(run_dir / "raw" / "walk.png")
- # two identical poses: their composite cells are byte identical, so the sheet
- # must share one column between them (atlas cell-reuse rule, §2 B7).
- _strip([((12, 20, 51, 79), (30, 140, 90)),
- ((108, 20, 147, 79), (30, 140, 90))], 2).save(run_dir / "raw" / "hold.png")
- _strip([((30, 30, 61, 61), (200, 120, 60))], 1).save(run_dir / "raw" / "can.png")
- _write_request(run_dir, request if request is not None else _request())
- if extract:
- result = run_script("extract_sprite_row_frames.py", "--run-dir", str(run_dir))
- assert result.returncode == 0, result.stdout + result.stderr
- return run_dir
-
-
-def _mask(run_dir: Path, rel: str, value: int, size: tuple[int, int] = (CELL, CELL)) -> str:
- path = run_dir / rel
- path.parent.mkdir(parents=True, exist_ok=True)
- Image.new("L", size, value).save(path)
- return rel
-
-
-def _curate(run_dir: Path, states: dict) -> None:
- write_curation_atomic(run_dir, {**empty_curation(), "states": states})
-
-
-def _rows(run_dir: Path) -> dict[str, dict]:
- manifest = json.loads((run_dir / "frames" / "frames-manifest.json").read_text(encoding="utf-8"))
- return {row["state"]: row for row in manifest["rows"]}
-
-
-def _frame(run_dir: Path, state: str, index: int) -> Image.Image:
- return Image.open(run_dir / _rows(run_dir)[state]["files"][index]).convert("RGBA")
-
-
-def _cell_of(sheet: Image.Image, rect: dict) -> Image.Image:
- return sheet.crop((rect["x"], rect["y"], rect["x"] + rect["w"], rect["y"] + rect["h"]))
-
-
-def _digest(path: Path) -> str:
- return hashlib.sha256(path.read_bytes()).hexdigest()
-
-
-def _layers_dir(run_dir: Path) -> Path:
- return run_dir / compose_layers.LAYERS_DIRNAME
-
-
-# ------------------------------------------------------------------ 1. the bake
-
-
-def test_element_is_placed_at_the_declared_integer_pivot_offset(tmp_path: Path) -> None:
- """`to - from`, composed onto the body — recomputed here from the frames on disk."""
- run_dir = _build_run(tmp_path)
-
- report = compose_layers.bake(run_dir)
- sheet = Image.open(_layers_dir(run_dir) / "walk_with_can.png").convert("RGBA")
- manifest = json.loads(
- (_layers_dir(run_dir) / "walk_with_can.manifest.json").read_text(encoding="utf-8"))
-
- for position in range(2):
- offset = (LANDMARKS["walk"][str(position)]["hand_r"][0] - LANDMARKS["can"]["0"]["grip"][0],
- LANDMARKS["walk"][str(position)]["hand_r"][1] - LANDMARKS["can"]["0"]["grip"][1])
- expected = Image.new("RGBA", (CELL, CELL), (0, 0, 0, 0))
- expected.alpha_composite(_frame(run_dir, "walk", position))
- placed = Image.new("RGBA", (CELL, CELL), (0, 0, 0, 0))
- placed.paste(_frame(run_dir, "can", 0), offset)
- expected.alpha_composite(placed)
-
- rect = manifest["frame_layout"]["rows"]["walk_with_can"][position]
- assert _cell_of(sheet, rect).tobytes() == expected.tobytes(), f"frame {position}"
-
- element = report["composites"][0]["elements"][1]
- assert element["offsets"] == [[12, -22], [14, -20]]
- assert element["clipped_pixels"] == 0
-
-
[email protected]("value", [0, 128, 255])
-def test_mask_alpha_arithmetic_is_the_published_formula(value: int) -> None:
- """Every (alpha, mask) pair, not just the opaque ones.
-
- Fully opaque art cannot tell `(a * m + 127) // 255` from `(a * m) // 255` —
- they agree for a = 255 at every m — so the rounding clause is pinned here,
- across the whole alpha range, instead of through a baked sheet.
- """
- frame = Image.new("RGBA", (256, 1), (10, 20, 30, 255))
- frame.putalpha(Image.frombytes("L", (256, 1), bytes(range(256))))
-
- masked = compose_layers.apply_alpha_mask(frame, Image.new("L", (256, 1), value))
-
- assert masked.getchannel("A").tobytes() == bytes((a * value + 127) // 255 for a in range(256))
- assert masked.convert("RGB").tobytes() == frame.convert("RGB").tobytes()
-
-
-def test_mask_multiplies_alpha_with_documented_integer_rounding(tmp_path: Path) -> None:
- """`a' = (a * m + 127) // 255` on an arbitrary mask, no resampling anywhere."""
- request = _request()
- rel = "references/masks/can.png"
- request["layers"]["walk_with_can"]["stack"][1]["mask"] = rel
- run_dir = _build_run(tmp_path, request)
- _mask(run_dir, rel, 128)
-
- compose_layers.bake(run_dir)
- sheet = Image.open(_layers_dir(run_dir) / "walk_with_can.png").convert("RGBA")
- manifest = json.loads(
- (_layers_dir(run_dir) / "walk_with_can.manifest.json").read_text(encoding="utf-8"))
-
- can = _frame(run_dir, "can", 0)
- masked = can.copy()
- masked.putalpha(can.getchannel("A").point(lambda a: (a * 128 + 127) // 255))
- expected = Image.new("RGBA", (CELL, CELL), (0, 0, 0, 0))
- expected.alpha_composite(_frame(run_dir, "walk", 0))
- placed = Image.new("RGBA", (CELL, CELL), (0, 0, 0, 0))
- placed.paste(masked, (12, -22))
- expected.alpha_composite(placed)
-
- rect = manifest["frame_layout"]["rows"]["walk_with_can"][0]
- assert _cell_of(sheet, rect).tobytes() == expected.tobytes()
-
-
-def test_a_fully_transparent_mask_removes_the_element_entirely(tmp_path: Path) -> None:
- request = _request()
- request["layers"]["body_only"] = {"stack": [{"state": "walk"}]}
- request["layers"]["walk_with_can"]["stack"][1]["mask"] = "references/masks/none.png"
- run_dir = _build_run(tmp_path, request)
- _mask(run_dir, "references/masks/none.png", 0)
-
- compose_layers.bake(run_dir)
- assert (_digest(_layers_dir(run_dir) / "walk_with_can.png")
- == _digest(_layers_dir(run_dir) / "body_only.png"))
-
-
-def test_identical_composite_cells_share_one_column(tmp_path: Path) -> None:
- request = _request()
- request["layers"] = {"hold_with_can": {"stack": [
- {"state": "hold"},
- {"state": "can", "from": "grip", "to": "hand_r"},
- ]}}
- run_dir = _build_run(tmp_path, request)
-
- report = compose_layers.bake(run_dir)
- manifest = json.loads(
- (_layers_dir(run_dir) / "hold_with_can.manifest.json").read_text(encoding="utf-8"))
- sheet = Image.open(_layers_dir(run_dir) / "hold_with_can.png")
-
- assert report["composites"][0] == {**report["composites"][0], "frames": 2, "cells": 1}
- assert sheet.size == (CELL, CELL)
- rects = manifest["frame_layout"]["rows"]["hold_with_can"]
- assert len(rects) == 2 and rects[0] == rects[1]
-
-
-def test_composite_manifest_keeps_the_runtime_manifest_shape(tmp_path: Path) -> None:
- """A runtime reads a composite with the code it already has, plus provenance.
-
- The base manifest gains `rig` and `track` only for a rig run: landmarks reach the
- runtime as atlas-absolute integers, one per play position.
-
- `sprite_sheet_alpha_report` names THIS sheet's alpha report — a composite has none.
- The key stays (key-set parity) but resolves to nothing, because
- `layers.report.json` is the bake's provenance record for every composite and
- not this sheet's alpha report: a consumer that opened it through this field
- would be reading a different kind of document. The provenance pointer has its
- own name inside the `layers` block (`docs/layer-tracks.md` §5).
- """
- run_dir = _build_run(tmp_path)
- assert run_script("compose_sprite_atlas.py", "--run-dir", str(run_dir)).returncode == 0
- base = json.loads((run_dir / "manifest.json").read_text(encoding="utf-8"))
- base_report = json.loads(
- (run_dir / base["sprite_sheet_alpha_report"]).read_text(encoding="utf-8"))
-
- assert base["rig"]["profile"] == "humanoid_biped"
- for state in ("walk", "hold", "can"):
- rects = base["frame_layout"]["rows"][state]
- entries = base["rig"]["landmarks"][state]
- assert len(entries) == len(rects), state
- for index, (rect, entry) in enumerate(zip(rects, entries)):
- declared = LANDMARKS[state][str(index)]
- assert entry == {name: [rect["x"] + point[0], rect["y"] + point[1]]
- for name, point in declared.items()}
- assert base["animation"]["rows"]["can"]["track"] == "prop_effect"
- assert base["animation"]["rows"]["walk"]["track"] == "base"
-
- compose_layers.bake(run_dir)
- manifest = json.loads(
- (_layers_dir(run_dir) / "walk_with_can.manifest.json").read_text(encoding="utf-8"))
- provenance = json.loads(
- (_layers_dir(run_dir) / manifest["layers"]["report"]).read_text(encoding="utf-8"))
-
- assert set(manifest) == (set(base) - {"rig"}) | {"layers"}
- assert manifest["game_input"] == "walk_with_can.png"
- assert manifest["animation"]["rows"]["walk_with_can"]["frames"] == 2
- assert manifest["animation"]["rows"]["walk_with_can"]["track"] == "composite"
- assert [element["state"] for element in manifest["layers"]["stack"]] == ["walk", "can"]
- assert manifest["layers"]["stack"][1]["track"] == "prop_effect"
-
- assert manifest["sprite_sheet_alpha_report"] is None
- assert manifest["layers"]["report"] == compose_layers.REPORT_NAME
- assert provenance["kind"] == compose_layers.REPORT_KIND
- # The two documents are not interchangeable, which is the whole reason the
- # field could not keep pointing at the provenance record.
- assert "kind" not in base_report
- assert set(provenance) != set(base_report)
-
-
-def test_a_bake_publishes_its_whole_set_in_one_transaction(tmp_path: Path,
- monkeypatch) -> None:
- """Sheets, manifests and the report land together or not at all (§5).
-
- A write that fails partway through must not leave a sheet published with no
- report naming it, so the bake hands every payload to one publish call. Here
- that call fails: the previous bake's bytes must still be exactly what is on
- disk, and the second composite must not exist at all.
- """
- request = _request()
- request["layers"]["walk_alone"] = {"stack": [{"state": "walk"}]}
- run_dir = _build_run(tmp_path, request)
-
- compose_layers.bake(run_dir, names=["walk_with_can"])
- before = {path.name: _digest(path) for path in sorted(_layers_dir(run_dir).iterdir())}
-
- seen: list[list[str]] = []
-
- def explode(payloads):
- seen.append([path.name for path in payloads])
- raise OSError(28, "No space left on device")
-
- monkeypatch.setattr(compose_layers, "atomic_write_set", explode)
- with pytest.raises(OSError):
- compose_layers.bake(run_dir)
-
- assert seen == [["walk_alone.png", "walk_alone.manifest.json",
- "walk_with_can.png", "walk_with_can.manifest.json",
- "layers.report.json"]], "the bake published in more than one call"
- after = {path.name: _digest(path) for path in sorted(_layers_dir(run_dir).iterdir())}
- assert after == before
-
-
-# ---------------------------------------------------------- 2. the diagnostics
-
-
-def test_clipping_fails_loud_and_allow_clip_records_the_loss(tmp_path: Path) -> None:
- request = _request()
- request["rig"]["landmarks"]["walk"]["0"]["hand_r"] = [95, 95]
- request["rig"]["landmarks"]["walk"]["1"]["hand_r"] = [95, 95]
- run_dir = _build_run(tmp_path, request)
-
- with pytest.raises(SystemExit) as excinfo:
- compose_layers.bake(run_dir)
- assert "outside the 96x96 cell" in str(excinfo.value)
- assert "allow_clip" in str(excinfo.value)
- assert not _layers_dir(run_dir).exists()
-
- request["layers"]["walk_with_can"]["stack"][1]["allow_clip"] = True
- _write_request(run_dir, request)
- report = compose_layers.bake(run_dir)
- assert report["composites"][0]["elements"][1]["clipped_pixels"] > 0
-
-
-def test_a_missing_source_frame_is_reported_against_the_published_generation(tmp_path: Path) -> None:
- run_dir = _build_run(tmp_path)
- (run_dir / _rows(run_dir)["can"]["files"][0]).unlink()
-
- with pytest.raises(SystemExit) as excinfo:
- compose_layers.bake(run_dir)
- assert "missing frame" in str(excinfo.value)
-
-
[email protected]("size,expected", [((48, 48), "expected the run's 96x96 cell"),
- (None, "not found")])
-def test_an_unusable_mask_is_a_hard_error(tmp_path: Path, size, expected: str) -> None:
- request = _request()
- request["layers"]["walk_with_can"]["stack"][1]["mask"] = "references/masks/can.png"
- run_dir = _build_run(tmp_path, request)
- if size is not None:
- _mask(run_dir, "references/masks/can.png", 255, size)
-
- with pytest.raises(SystemExit) as excinfo:
- compose_layers.bake(run_dir)
- assert expected in str(excinfo.value)
-
-
-def test_a_mask_outside_the_run_dir_is_refused(tmp_path: Path) -> None:
- request = _request()
- request["layers"]["walk_with_can"]["stack"][1]["mask"] = "../escape.png"
- run_dir = _build_run(tmp_path, request)
- Image.new("L", (CELL, CELL), 255).save(tmp_path / "escape.png")
-
- with pytest.raises(SystemExit) as excinfo:
- compose_layers.bake(run_dir)
- assert "must stay inside the run dir" in str(excinfo.value)
-
-
-def test_a_re_rolled_source_row_fails_a_pinned_element(tmp_path: Path) -> None:
- """The pin is the same mechanism as `curation.anchors`: prove it, or fail loud."""
- request = _request()
- request["layers"]["walk_with_can"]["stack"][1]["revision"] = ["deadbeefcafe"]
- run_dir = _build_run(tmp_path, request)
-
- with pytest.raises(SystemExit) as excinfo:
- compose_layers.bake(run_dir)
- assert "pins revision" in str(excinfo.value)
- assert "re-rolled" in str(excinfo.value)
-
-
-def test_a_pinned_element_bakes_when_the_pin_matches(tmp_path: Path) -> None:
- run_dir = _build_run(tmp_path)
- report = compose_layers.bake(run_dir)
- pin = report["composites"][0]["elements"][1]["state_revision"]
- assert pin, "an extracted row must have a provable revision"
-
- request = _request()
- request["layers"]["walk_with_can"]["stack"][1]["revision"] = pin
- _write_request(run_dir, request)
-
- assert compose_layers.bake(run_dir)["composites"][0]["elements"][1]["state_revision"] == pin
-
-
-def test_a_curated_clone_instance_has_no_declared_pivot(tmp_path: Path) -> None:
- """A clone lives outside the landmark pool and carries its own transform."""
- run_dir = _build_run(tmp_path)
- _curate(run_dir, {"walk": {
- "clones": {"2": 0},
- "selected": [0, 1, 2],
- "transforms": {"2": {"dx": 6, "dy": 0, "scale": 1.0, "rotate": 0.0, "shear": 0.0}},
- }})
-
- with pytest.raises(SystemExit) as excinfo:
- compose_layers.bake(run_dir)
- assert "declares no landmarks" in str(excinfo.value)
- assert "clone" in str(excinfo.value)
-
-
-def test_the_atlas_refuses_to_publish_landmarks_it_cannot_prove(tmp_path: Path) -> None:
- """The same clone rule on the base manifest: no pivot is invented for the runtime."""
- run_dir = _build_run(tmp_path)
- _curate(run_dir, {"walk": {"clones": {"2": 0}, "selected": [0, 1, 2]}})
-
- result = run_script("compose_sprite_atlas.py", "--run-dir", str(run_dir))
-
- assert result.returncode == 1, result.stdout + result.stderr
- report = json.loads((run_dir / "sprite-sheet-alpha.report.json").read_text(encoding="utf-8"))
- assert any("declares no rig landmarks" in error for error in report["errors"])
- assert not (run_dir / "manifest.json").exists()
-
-
-def test_an_invalid_rig_stops_the_atlas_before_it_bakes(tmp_path: Path) -> None:
- request = _request()
- request["rig"]["profile"] = "mecha"
- run_dir = _build_run(tmp_path, request)
-
- result = run_script("compose_sprite_atlas.py", "--run-dir", str(run_dir))
-
- assert result.returncode != 0
- assert "invalid layer contract" in result.stderr
- assert not (run_dir / "sprite-sheet-alpha.png").exists()
-
-
-def test_a_deleted_body_row_has_nothing_to_stack_onto(tmp_path: Path) -> None:
- run_dir = _build_run(tmp_path)
- _curate(run_dir, {"walk": {"deleted": [0, 1]}})
-
- with pytest.raises(SystemExit) as excinfo:
- compose_layers.bake(run_dir)
- assert "plays no frames" in str(excinfo.value)
-
-
-def test_an_element_that_plays_a_different_length_is_rejected(tmp_path: Path) -> None:
- """Pool sizes match by declaration; curation can still cut one sequence short."""
- run_dir = _build_run(tmp_path)
- request = _request()
- request["layers"]["walk_and_hold"] = {"stack": [
- {"state": "walk"},
- {"state": "hold", "from": "root", "to": "root"},
- ]}
- request["states"]["hold"]["track"] = "action_overlay"
- _write_request(run_dir, request)
- _curate(run_dir, {"hold": {"deleted": [1]}})
-
- with pytest.raises(SystemExit) as excinfo:
- compose_layers.bake(run_dir)
- assert "plays 1 frames against a body of 2" in str(excinfo.value)
- assert "only a single-frame row holds one pose" in str(excinfo.value)
-
-
-# ----------------------------------------------------------- 3. the boundaries
-
-
-def test_nothing_is_written_when_any_composite_fails(tmp_path: Path) -> None:
- """Atomicity: a good composite is not published beside a failed one."""
- request = _request()
- request["layers"]["broken"] = {"stack": [
- {"state": "walk"},
- {"state": "can", "from": "grip", "to": "hand_r", "mask": "references/masks/gone.png"},
- ]}
- run_dir = _build_run(tmp_path, request)
-
- with pytest.raises(SystemExit):
- compose_layers.bake(run_dir)
- assert not _layers_dir(run_dir).exists()
-
-
-def test_a_non_layer_run_is_refused_not_composed(tmp_path: Path) -> None:
- request = _request()
- del request["rig"]
- del request["layers"]
- for entry in request["states"].values():
- entry.pop("track")
- run_dir = _build_run(tmp_path, request)
-
- with pytest.raises(SystemExit) as excinfo:
- compose_layers.bake(run_dir)
- assert "not a layer run" in str(excinfo.value)
- assert not _layers_dir(run_dir).exists()
-
-
-def test_an_invalid_declaration_fails_before_the_run_dir_is_touched(tmp_path: Path) -> None:
- request = _request()
- request["rig"]["landmarks"]["walk"]["1"].pop("crown")
- run_dir = _build_run(tmp_path, request)
-
- with pytest.raises(SystemExit) as excinfo:
- compose_layers.bake(run_dir)
- assert "invalid layer contract" in str(excinfo.value)
- assert not _layers_dir(run_dir).exists()
-
-
-def test_an_unknown_composite_name_is_refused(tmp_path: Path) -> None:
- run_dir = _build_run(tmp_path)
-
- with pytest.raises(SystemExit) as excinfo:
- compose_layers.bake(run_dir, names=["nope"])
- assert "no such composite" in str(excinfo.value)
-
-
-def test_a_repeated_name_is_refused_at_the_python_entry_point(tmp_path: Path) -> None:
- """The CLI string is not the only door into the selection.
-
- `parse_names` diagnoses a `--names a,a` typo early, but the invariant belongs
- to the bake: a repeat that got through would write one sheet while the report
- counted two composites, so `composite_count` and `layers/` would disagree —
- the same defect, reached by the library form.
- """
- run_dir = _build_run(tmp_path)
-
- with pytest.raises(SystemExit) as excinfo:
- compose_layers.bake(run_dir, names=["walk_with_can", "walk_with_can"])
- assert "named more than once" in str(excinfo.value)
- assert not _layers_dir(run_dir).exists()
-
-
-def test_load_report_distinguishes_absent_from_foreign(tmp_path: Path) -> None:
- run_dir = _build_run(tmp_path)
- assert compose_layers.load_report(run_dir) is None
-
- compose_layers.bake(run_dir)
- assert compose_layers.load_report(run_dir)["composite_count"] == 1
-
- path = _layers_dir(run_dir) / compose_layers.REPORT_NAME
- path.write_text(json.dumps({"kind": "sprite-gen-recolor-report"}), encoding="utf-8")
- with pytest.raises(SystemExit):
- compose_layers.load_report(run_dir)
-
-
-# ------------------------------------------------------------------- 4. the CLI
-#
-# The library form is covered above; these run the published command as an agent
-# runs it, so the process boundary (exit code, stdout summary, stderr diagnostic)
-# is part of the contract and not an implementation detail.
-
-
-def _cli(run_dir: Path, *args: str):
- return run_script("compose_layers.py", "--run-dir", str(run_dir), *args)
-
-
-def test_the_cli_bakes_and_summarizes_the_declared_composites(tmp_path: Path) -> None:
- run_dir = _build_run(tmp_path)
-
- result = _cli(run_dir)
-
- assert result.returncode == 0, result.stdout + result.stderr
- summary = json.loads(result.stdout)
- assert summary["ok"] is True
- assert summary["rig_profile"] == "humanoid_biped"
- assert summary["report"] == "layers/layers.report.json"
- assert summary["composites"] == [{
- "name": "walk_with_can",
- "sheet": "layers/walk_with_can.png",
- "manifest": "layers/walk_with_can.manifest.json",
- "frames": 2,
- "cells": 2,
- "clipped_pixels": 0,
- }]
- for rel in (entry for composite in summary["composites"]
- for entry in (composite["sheet"], composite["manifest"])):
- assert (run_dir / rel).is_file(), rel
-
-
-def test_two_cli_bakes_in_separate_processes_are_byte_identical(tmp_path: Path) -> None:
- """Same run, same bytes — the determinism claim the whole feature rests on.
-
- Across the process boundary, not just inside one interpreter."""
- run_dir = _build_run(tmp_path)
-
- assert _cli(run_dir).returncode == 0
- first = {path.name: _digest(path) for path in sorted(_layers_dir(run_dir).iterdir())}
- assert _cli(run_dir).returncode == 0
- second = {path.name: _digest(path) for path in sorted(_layers_dir(run_dir).iterdir())}
-
- assert set(first) == {"walk_with_can.png", "walk_with_can.manifest.json",
- "layers.report.json"}
- assert first == second
-
-
-def test_the_cli_bakes_only_the_named_composites(tmp_path: Path) -> None:
- request = _request()
- request["layers"]["walk_alone"] = {"stack": [{"state": "walk"}]}
- run_dir = _build_run(tmp_path, request)
-
- assert _cli(run_dir).returncode == 0
- assert _cli(run_dir, "--names", "walk_alone").returncode == 0
-
- # The other sheet stays (a subset bake leaves it alone), but the report — the
- # record of what the last bake produced — names only what was baked (§5).
- assert (_layers_dir(run_dir) / "walk_with_can.png").is_file()
- report = compose_layers.load_report(run_dir)
- assert [entry["name"] for entry in report["composites"]] == ["walk_alone"]
-
-
-def test_the_cli_refuses_a_malformed_names_list(tmp_path: Path) -> None:
- """An empty entry is a typo, never "all" — silently dropping it bakes another set.
-
- One shape is enough: an empty list, a trailing comma and a blank all split into an
- empty entry and reach the same `any(not name)` refusal."""
- run_dir = _build_run(tmp_path)
-
- result = _cli(run_dir, "--names", "a,,b")
-
- assert result.returncode != 0
- assert "--names expects a comma-separated list" in result.stderr
- assert not _layers_dir(run_dir).exists()
-
-
-def test_the_cli_refuses_a_repeated_name(tmp_path: Path) -> None:
- """Same class as an empty entry: the selection is the caller's to fix, not ours to guess."""
- run_dir = _build_run(tmp_path)
-
- result = _cli(run_dir, "--names", "walk_with_can,walk_with_can")
-
- assert result.returncode != 0
- assert "named more than once" in result.stderr
- assert not _layers_dir(run_dir).exists()
-
-
-def test_the_cli_reports_every_violation_at_once_and_writes_nothing(tmp_path: Path) -> None:
- request = _request()
- request["rig"]["landmarks"]["walk"]["1"].pop("crown")
- request["layers"]["walk_with_can"]["fps"] = "8"
- run_dir = _build_run(tmp_path, request)
-
- result = _cli(run_dir)
-
- assert result.returncode != 0
- assert "miss required landmark 'crown'" in result.stderr
- assert "layers.walk_with_can.fps must be a positive integer" in result.stderr
- assert not _layers_dir(run_dir).exists()
diff --git a/tests/compose/test_layer_contract.py b/tests/compose/test_layer_contract.py
deleted file mode 100644
index e40774d..0000000
--- a/tests/compose/test_layer_contract.py
+++ /dev/null
@@ -1,591 +0,0 @@
-# SPDX-License-Identifier: Apache-2.0
-"""Layer-track contract: declaration validation + the compatibility boundaries it must not cross.
-
-Three groups:
-
-1. `sprite_gen.compose.layers` — the request-level contract (profiles, tracks, stacks).
-2. Compatibility pins — the request / curation / manifest surfaces the layer feature
- is allowed to extend but never to change for a run that does not opt in.
-3. Doc surface — `docs/layer-tracks.md` is the published SSoT and must stay linked.
-
-Boundary evidence behind the pins lives in `docs/layer-tracks.md` §2.
-"""
-
-from __future__ import annotations
-
-import json
-import re
-from pathlib import Path
-
-import pytest
-
-from sprite_gen.compose import layers
-from sprite_gen.gen import prepare
-from sprite_gen.curate.curation import empty_curation
-
-from conftest import run_script
-
-ROOT = Path(__file__).resolve().parents[2]
-
-
-def _request(**overrides) -> dict:
- """A minimal humanoid rig request: `walk` (base, 2 frames) + `can` (prop, 1 frame).
-
- The prop row declares `root` and `grip` and no `crown` — a watering can has no
- 정수리, and the contract judges required landmarks by profile *and* track
- (§3.1). It is the documented example, so the whole file exercises that rule.
- """
- request = {
- "version": 1,
- "kind": "sprite-gen-request",
- "engine": "component-row",
- "character": {"id": "rigbot"},
- "cell": {"shape": "square", "width": 64, "height": 64, "size": 64},
- "states": {
- "walk": {"frames": 2, "fps": 8, "loop": True, "action": "walk", "track": "base"},
- "can": {"frames": 1, "fps": 8, "loop": False, "action": "prop", "track": "prop_effect"},
- },
- "rig": {
- "profile": "humanoid_biped",
- "landmarks": {
- "walk": {
- "0": {"root": [32, 40], "crown": [32, 8], "hand_r": [40, 30]},
- "1": {"root": [32, 41], "crown": [32, 9], "hand_r": [41, 31]},
- },
- "can": {"0": {"root": [10, 10], "grip": [8, 12]}},
- },
- },
- "layers": {
- "walk_with_can": {
- "stack": [
- {"state": "walk"},
- {"state": "can", "from": "grip", "to": "hand_r"},
- ]
- }
- },
- }
- request.update(overrides)
- return request
-
-
-# ---------------------------------------------------------------- 1. contract
-
-
-def test_validation_is_idempotent() -> None:
- request = _request()
- request["states"]["walk"]["track"] = "nonsense"
- first = layers.validate_layer_request(request)
- assert first == layers.validate_layer_request(request)
-
-
-def test_request_without_layer_keys_is_not_a_layer_run() -> None:
- plain = json.loads((ROOT / "tests" / "fixtures" / "run" / "sprite-request.json").read_text(encoding="utf-8"))
-
- assert layers.has_layer_contract(plain) is False
- assert layers.validate_layer_request(plain) == []
- # An undeclared row is an explicit `base`, not an unknown kind.
- assert layers.state_track(plain, "idle") == "base"
-
-
[email protected]("profile", ["quadruped", "blob_or_tentacle", "prop"])
-def test_non_humanoid_profiles_do_not_require_crown(profile: str) -> None:
- request = _request()
- request["rig"]["profile"] = profile
- for frames in request["rig"]["landmarks"].values():
- for point_map in frames.values():
- point_map.pop("crown", None)
-
- assert layers.validate_layer_request(request) == []
-
-
-def test_a_prop_row_in_a_humanoid_run_is_not_held_to_the_body_requirement() -> None:
- """A watering can has no 정수리 (§3.1).
-
- The rig profile answers "what is this character", the track answers "what does
- this row draw" — and `crown` is a body landmark. Requiring it on a
- `prop_effect` row leaves one way out: declare a fake crown on the can, which
- puts a made-up coordinate on the row the composer aligns against. The
- requirement is judged by profile AND track so that way out is never needed.
- """
- request = _request()
- assert "crown" not in request["rig"]["landmarks"]["can"]["0"]
-
- assert layers.validate_layer_request(request) == []
-
-
[email protected]("track", ["base", "action_overlay", "full_body_override"])
-def test_a_body_bearing_row_keeps_the_profile_requirement(track: str) -> None:
- """The narrowing is `prop_effect` only — every row that draws the body keeps `crown`."""
- request = _request()
- request["states"]["can"]["track"] = track
-
- errors = layers.validate_layer_request(request)
- assert any("miss required landmark 'crown'" in e and "rig.landmarks.can" in e
- for e in errors), errors
-
-
-def test_a_prop_row_still_requires_its_own_root() -> None:
- """Narrowed, not exempt: a prop is held to the `prop` profile, which needs `root`."""
- request = _request()
- del request["rig"]["landmarks"]["can"]["0"]["root"]
-
- errors = layers.validate_layer_request(request)
- assert any("miss required landmark 'root'" in e and "rig.landmarks.can" in e
- for e in errors), errors
-
-
-def test_required_landmarks_reads_profile_and_track_together() -> None:
- # One non-humanoid profile is enough: the override is one `.get(track, name)` line,
- # and for the other tracks this compares PROFILES with itself.
- profile = "quadruped"
- for track in layers.TRACKS:
- expected = ("root",) if track == "prop_effect" else layers.PROFILES[profile]["required"]
- assert layers.required_landmarks(profile, track) == expected
-
-
-# An unknown `rig.profile` owns exactly one error. The three tests below pin that
-# from both sides — the helper and the whole validator — because the requirement
-# is an ORDER: profile validity is judged before the track narrowing, so a
-# `prop_effect` row can never borrow the `prop` profile out of a run that
-# declared no valid profile at all.
-
-# One string outside PROFILES and one unhashable JSON shape: `known_profile` is
-# `isinstance(str) and in PROFILES`, so null, numbers, bools and objects take the
-# same two branches.
-UNKNOWN_PROFILES = [
- pytest.param("mecha", id="unknown-string"),
- pytest.param(["humanoid_biped"], id="list-unhashable"),
-]
-
-
[email protected]("profile", UNKNOWN_PROFILES)
-def test_an_unknown_profile_requires_nothing_on_every_track(profile) -> None:
- """Including `prop_effect`, which is the track that has an override to fall back to.
-
- A list or an object is a JSON shape `rig.profile` can really arrive as, and
- an unhashable value must come back as "requires nothing" rather than as a
- TypeError from the dict lookup.
- """
- for track in layers.TRACKS:
- assert layers.required_landmarks(profile, track) == ()
- assert layers.known_profile(profile) is None
-
-
[email protected]("profile", UNKNOWN_PROFILES)
-def test_an_unknown_profile_is_the_only_error_it_causes(profile) -> None:
- """The regression: the run's prop row must not also be told it is missing `root`.
-
- Judging the track override first made `required_landmarks(<unknown>,
- 'prop_effect')` return the `prop` profile's `('root',)`, so an unknown-profile
- run that happened to contain a prop row got a second, derived error next to
- the real one — and a malformed (unhashable) profile crashed the validator
- outright instead of being reported.
- """
- request = _request()
- request["rig"]["profile"] = profile
- # Strip what a prop row would be held to under the override, so a leaked
- # requirement shows up as an error instead of being silently satisfied.
- del request["rig"]["landmarks"]["can"]["0"]["root"]
-
- errors = layers.validate_layer_request(request)
- assert [e for e in errors if e.startswith("rig.profile must be one of")], errors
- assert not [e for e in errors if "required landmark" in e], errors
-
-
-def test_a_valid_profile_still_owns_its_requirements() -> None:
- """The guard narrows nothing for a declared profile — the §3.1 rules stand."""
- request = _request()
- del request["rig"]["landmarks"]["walk"]["0"]["crown"]
- del request["rig"]["landmarks"]["can"]["0"]["root"]
-
- errors = layers.validate_layer_request(request)
- assert not [e for e in errors if e.startswith("rig.profile must be one of")], errors
- assert any("miss required landmark 'crown'" in e and "rig.landmarks.walk" in e
- for e in errors), errors
- assert any("miss required landmark 'root'" in e and "rig.landmarks.can" in e
- for e in errors), errors
- assert layers.known_profile("humanoid_biped") == "humanoid_biped"
-
-
-def test_root_is_required_by_every_profile() -> None:
- request = _request()
- request["rig"]["profile"] = "blob_or_tentacle"
- del request["rig"]["landmarks"]["walk"]["0"]["root"]
-
- errors = layers.validate_layer_request(request)
- assert any("'root'" in e for e in errors)
-
-
-def test_landmark_must_cover_the_whole_frame_pool_including_takes() -> None:
- request = _request()
- request["states"]["walk"]["takes"] = [{"label": "blink", "frames": 1}]
-
- errors = layers.validate_layer_request(request)
- assert any("missing frame(s) [2]" in e for e in errors)
-
-
-def test_landmark_declared_on_some_frames_only_is_rejected() -> None:
- request = _request()
- request["rig"]["landmarks"]["walk"]["1"].pop("hand_r")
- # `to=hand_r` now resolves on frame 0 but not frame 1 — a half-declared row.
- errors = layers.validate_layer_request(request)
- assert any("whole row" in e for e in errors)
-
-
-def test_non_integer_and_out_of_cell_landmarks_are_rejected() -> None:
- request = _request()
- request["rig"]["landmarks"]["walk"]["0"]["root"] = [32.5, 40]
- request["rig"]["landmarks"]["walk"]["1"]["crown"] = [32, 999]
-
- errors = layers.validate_layer_request(request)
- assert any("integers" in e for e in errors)
- assert any("outside the 64x64 cell" in e for e in errors)
-
-
-def test_boolean_landmark_coordinates_are_rejected() -> None:
- """JSON `true` is not the integer 1 here.
-
- `bool` is an `int` subclass in Python, so a coordinate check written as
- `isinstance(value, int)` accepts `[true, 8]` and silently composes at x=1.
- The contract says integers, never booleans (§3), and this is the test that
- holds that line — the float and out-of-cell cases cannot, because they fail
- on a different branch.
- """
- request = _request()
- request["rig"]["landmarks"]["walk"]["0"]["crown"] = [True, 8]
-
- errors = layers.validate_layer_request(request)
- assert any("crown" in e and "integers" in e for e in errors), errors
-
-
-def test_stack_needs_exactly_one_body_element() -> None:
- request = _request()
- request["states"]["can"]["track"] = "base"
-
- errors = layers.validate_layer_request(request)
- assert any("exactly one body element" in e for e in errors)
-
-
-def test_full_body_override_forbids_action_overlay() -> None:
- request = _request()
- request["states"]["walk"]["track"] = "full_body_override"
- request["states"]["can"]["track"] = "action_overlay"
- request["states"]["can"]["frames"] = 2
- request["rig"]["landmarks"]["can"]["1"] = dict(request["rig"]["landmarks"]["can"]["0"])
-
- errors = layers.validate_layer_request(request)
- assert any("forbids" in e and "action_overlay" in e for e in errors)
-
-
-def test_body_element_must_be_first_in_draw_order() -> None:
- request = _request()
- request["layers"]["walk_with_can"]["stack"].reverse()
-
- errors = layers.validate_layer_request(request)
- assert any("must be stack[0]" in e for e in errors)
-
-
-def test_overlay_frame_count_must_match_body_or_be_one() -> None:
- request = _request()
- request["states"]["can"]["frames"] = 3
- for index in ("1", "2"):
- request["rig"]["landmarks"]["can"][index] = dict(request["rig"]["landmarks"]["can"]["0"])
-
- errors = layers.validate_layer_request(request)
- assert any("holds a single frame" in e for e in errors)
-
-
-def test_alignment_landmark_must_exist_on_both_sides() -> None:
- request = _request()
- request["layers"]["walk_with_can"]["stack"][1]["to"] = "hand_l"
-
- errors = layers.validate_layer_request(request)
- assert any("aligns to='hand_l'" in e for e in errors)
-
-
-def test_unknown_stack_element_key_is_rejected() -> None:
- request = _request()
- request["layers"]["walk_with_can"]["stack"][1]["rotate"] = 15
-
- errors = layers.validate_layer_request(request)
- assert any("unknown key(s) ['rotate']" in e for e in errors)
-
-
-def test_unknown_composite_key_is_rejected() -> None:
- """The composite spec has an owner, so a typo is a violation and not a silent default.
-
- `layers.<name>` used to pass over an unknown top-level key while a stack
- element rejected one — the asymmetry the CLI step closes. `loops: false` must
- not ship a composite that loops because nothing read the key.
- """
- request = _request()
- request["layers"]["walk_with_can"]["loops"] = False
-
- errors = layers.validate_layer_request(request)
- assert any("layers.walk_with_can has unknown key(s) ['loops']" in e for e in errors)
- assert any("allowed: stack, fps, loop" in e for e in errors)
-
-
-def test_composite_name_must_not_collide_with_a_request_state() -> None:
- request = _request()
- request["layers"]["walk"] = request["layers"].pop("walk_with_can")
-
- errors = layers.validate_layer_request(request)
- assert any("must not collide with a request state" in e for e in errors)
-
-
-def test_stack_without_a_rig_is_rejected() -> None:
- request = _request()
- del request["rig"]
-
- errors = layers.validate_layer_request(request)
- assert any("needs a rig block" in e for e in errors)
-
-
-def test_require_valid_layer_request_reports_every_violation_at_once() -> None:
- request = _request()
- request["states"]["walk"]["track"] = "torso_only"
- request["rig"]["profile"] = "mecha"
-
- with pytest.raises(SystemExit) as excinfo:
- layers.require_valid_layer_request(request)
- message = str(excinfo.value)
- assert "rig.profile" in message and "states.walk.track" in message
-
-
-def test_resolved_stack_fills_pivot_defaults() -> None:
- resolved = layers.resolve_stack(_request(), "walk_with_can")
-
- assert resolved[0] == {"state": "walk", "from": "root", "to": "root",
- "mask": None, "allow_clip": False, "revision": None}
- assert resolved[1]["from"] == "grip" and resolved[1]["to"] == "hand_r"
-
-
-def test_an_element_may_pin_the_generation_its_landmarks_were_declared_against() -> None:
- request = _request()
- request["layers"]["walk_with_can"]["stack"][1]["revision"] = ["a1b2c3d4e5f6"]
-
- assert layers.validate_layer_request(request) == []
- assert layers.resolve_stack(request, "walk_with_can")[1]["revision"] == ["a1b2c3d4e5f6"]
-
-
[email protected]("pin", ["a1b2c3d4e5f6", [], [7]])
-def test_a_malformed_revision_pin_is_rejected(pin) -> None:
- request = _request()
- request["layers"]["walk_with_can"]["stack"][1]["revision"] = pin
-
- assert any("revision" in e for e in layers.validate_layer_request(request))
-
-
[email protected]("key,value", [("fps", "8"), ("fps", 0), ("fps", True), ("loop", 1)])
-def test_composite_playback_keys_are_typed(key: str, value) -> None:
- """`fps` / `loop` are copied into the composite manifest, so they are typed here."""
- request = _request()
- request["layers"]["walk_with_can"][key] = value
-
- assert any(f"layers.walk_with_can.{key}" in e for e in layers.validate_layer_request(request))
-
-
-def test_landmark_map_reads_a_whole_frame_and_never_invents_one() -> None:
- request = _request()
-
- assert layers.landmark_map(request, "can", 0) == {"root": (10, 10), "grip": (8, 12)}
- # A curated clone instance lives outside the declared pool: no map, no guess.
- assert layers.landmark_map(request, "can", 7) is None
-
-
-# --------------------------------------------------- 2. compatibility pins
-
-
-NON_LAYER_REQUEST_KEYS = {
- "version", "kind", "engine", "character", "cell", "chroma_key",
- "states", "style", "layout",
-}
-
-NON_LAYER_MANIFEST_KEYS = {
- "characterId", "engine", "game_input", "degraded_static_fallback",
- "curation_applied", "frame_variant", "sprite_sheet_alpha",
- "sprite_sheet_alpha_report", "base_image", "cell", "chroma_key",
- "animation", "frame_layout",
-}
-
-
-def _prepare(tmp_path: Path, request: dict, *args: str):
- out_dir = tmp_path / "run"
- result = run_script("prepare_sprite_run.py", "--out-dir", str(out_dir),
- "--character-id", "rigbot", "--request-json", json.dumps(request), *args)
- return out_dir, result
-
-
-def test_prepare_carries_the_layer_keys_into_the_request(tmp_path: Path) -> None:
- """The explicit-carry rule (`docs/layer-tracks.md` §7), formerly a canary.
-
- `prepare` rebuilds the request from a whitelist, so `rig` / `layers` /
- `states.<state>.track` reach `sprite-request.json` only because they are in
- the carried set by name — never by passthrough.
- """
- rig = {"profile": "humanoid_biped",
- "landmarks": {"idle": {"0": {"root": [10, 20], "crown": [10, 4]},
- "1": {"root": [11, 20], "crown": [11, 4]}}}}
- composites = {"idle_only": {"stack": [{"state": "idle"}], "fps": 8, "loop": True}}
- out_dir, result = _prepare(tmp_path, {
- "rig": rig,
- "layers": composites,
- "cell": {"width": 64, "height": 64},
- "states": {"idle": {"frames": 2, "track": "base"}},
- })
- assert result.returncode == 0, result.stdout + result.stderr
-
- request = json.loads((out_dir / "sprite-request.json").read_text(encoding="utf-8"))
- assert request["rig"] == rig
- assert request["layers"] == composites
- assert request["states"]["idle"]["track"] == "base"
- assert layers.has_layer_contract(request) is True
- assert layers.validate_layer_request(request) == []
-
-
-def test_prepare_writes_no_track_for_an_undeclared_row(tmp_path: Path) -> None:
- """An undeclared row IS `base`; writing that default would make every run a layer run."""
- out_dir, result = _prepare(tmp_path, {"states": {"idle": {"frames": 2}}})
- assert result.returncode == 0, result.stdout + result.stderr
-
- request = json.loads((out_dir / "sprite-request.json").read_text(encoding="utf-8"))
- assert set(request) == NON_LAYER_REQUEST_KEYS
- assert "track" not in request["states"]["idle"]
- assert layers.has_layer_contract(request) is False
-
-
-def test_prepare_names_every_key_it_drops(tmp_path: Path) -> None:
- """The whitelist drop is observable — that is what ends the `takes` class of loss.
-
- `states.<state>.takes` is a documented first-class key (`run-contract.md` §2)
- that has to be written into `sprite-request.json` after the fact; it went
- missing without a word for as long as `prepare` said nothing about it.
- """
- out_dir, result = _prepare(tmp_path, {
- "states": {"idle": {"frames": 2, "takes": [{"label": "blink", "frames": 1}],
- "breathe": {"depth": 0.06}}},
- "notes": "hand-written",
- "character": {"id": "someone-else"},
- })
- assert result.returncode == 0, result.stdout + result.stderr
-
- assert "dropped top-level request key(s) ['notes']" in result.stderr
- assert "ignored incoming ['character']" in result.stderr
- assert "dropped states.idle key(s) ['breathe', 'takes']" in result.stderr
- request = json.loads((out_dir / "sprite-request.json").read_text(encoding="utf-8"))
- assert "takes" not in request["states"]["idle"]
- assert request["character"]["id"] == "rigbot"
-
-
-def test_prepare_says_nothing_when_the_request_is_carried_whole(tmp_path: Path) -> None:
- """A note that fires on every run is a note nobody reads."""
- _out_dir, result = _prepare(tmp_path, {
- "cell": {"width": 64, "height": 64},
- "states": {"idle": {"frames": 2, "fps": 4, "loop": True, "action": "idle"}},
- "style": "flat",
- })
-
- assert result.returncode == 0, result.stdout + result.stderr
- assert "[prepare]" not in result.stderr
-
-
-def test_prepare_rejects_an_invalid_rig_before_scaffolding_the_run(tmp_path: Path) -> None:
- """Filesystem-free validation, so a bad declaration never leaves a half-made run."""
- out_dir, result = _prepare(tmp_path, {
- "cell": {"width": 64, "height": 64},
- "states": {"idle": {"frames": 2, "track": "hover"}},
- "rig": {"profile": "mecha", "landmarks": {"idle": {"0": {"root": [10, 20]}}}},
- })
-
- assert result.returncode != 0
- assert "invalid layer contract" in result.stderr
- assert "rig.profile must be one of" in result.stderr
- assert "states.idle.track must be one of" in result.stderr
- assert not out_dir.exists()
-
-
-def test_non_layer_run_manifest_surface_is_unchanged(fixture_run_dir: Path) -> None:
- extract = run_script("extract_sprite_row_frames.py", "--run-dir", str(fixture_run_dir))
- assert extract.returncode == 0, extract.stdout + extract.stderr
- compose = run_script("compose_sprite_atlas.py", "--run-dir", str(fixture_run_dir))
- assert compose.returncode == 0, compose.stdout + compose.stderr
-
- manifest = json.loads((fixture_run_dir / "manifest.json").read_text(encoding="utf-8"))
- assert set(manifest) == NON_LAYER_MANIFEST_KEYS
- for row in manifest["animation"]["rows"].values():
- assert "track" not in row
-
-
-def test_layer_data_never_enters_the_curation_sidecar() -> None:
- """The sidecar is human-edit truth, generation-stamped and droppable on re-extract.
-
- Layer declarations are machine-read request truth, so they must not appear in
- `curation.json` — otherwise a re-extract could silently drop a rig.
- """
- assert set(empty_curation()) == {"version", "kind", "states"}
- schema_doc = (ROOT / "sprite_gen" / "curate" / "curation.py").read_text(encoding="utf-8")
- header = schema_doc.split("SCHEMA_VERSION")[0]
- for reserved in ("\"rig\"", "\"tracks\"", "\"landmarks\""):
- assert reserved not in header
-
-
-# ------------------------------------------------------------- 3. doc surface
-
-FORBIDDEN_PATTERNS = (
- (re.compile(r"/(?:Users|home)/[A-Za-z0-9._-]+"), "an absolute personal home path"),
- (re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}"), "an e-mail address"),
-)
-
-
-def _read(rel: str) -> str:
- return (ROOT / rel).read_text(encoding="utf-8")
-
-
-def test_layer_doc_declares_the_whole_vocabulary() -> None:
- text = _read("docs/layer-tracks.md")
-
- for profile in layers.PROFILES:
- assert profile in text, f"docs/layer-tracks.md does not name profile {profile}"
- for track in layers.TRACKS:
- assert track in text, f"docs/layer-tracks.md does not name track {track}"
- for key in ("rig.landmarks", "layers", "allow_clip", "full_body_override"):
- assert key in text
- assert "sprite_gen/compose/layers.py" in text
-
-
-def test_layer_doc_is_publishable() -> None:
- text = _read("docs/layer-tracks.md")
-
- for pattern, why in FORBIDDEN_PATTERNS:
- assert not pattern.search(text), f"docs/layer-tracks.md leaks {why}"
-
-
-def test_layer_doc_is_linked_from_the_hub_and_the_contracts() -> None:
- assert "docs/layer-tracks.md" in _read("SKILL.md")
- assert "layer-tracks.md" in _read("docs/run-contract.md")
- assert "layer-tracks.md" in _read("docs/architecture.md")
-
-
-def test_the_bake_command_is_documented_where_an_agent_looks() -> None:
- """A CLI nobody can find is a library. The hub names it; the doc explains it."""
- skill = _read("SKILL.md")
- doc = _read("docs/layer-tracks.md")
-
- assert "sprite-gen compose-layers" in skill
- assert "scripts/compose_layers.py" in skill, "the script map's required_scripts list"
- for clause in ("sprite-gen compose-layers", "--names", "sprite_gen/compose/compose_layers.py"):
- assert clause in doc, f"docs/layer-tracks.md does not document {clause}"
-
-
-def test_the_doc_owns_the_prepare_carry_and_drop_rule() -> None:
- """The whitelist and its stderr note are contract text, not an implementation detail."""
- doc = _read("docs/layer-tracks.md")
-
- assert "[prepare] dropped" in doc
- assert "states.<state>.takes" in doc
- for key in ("rig", "layers", "track"):
- assert key in doc, f"docs/layer-tracks.md does not name carried key {key}"
- # The per-state rebuild list is quoted in the doc's example note; a change to
- # the carried set has to reach the doc, not just the code.
- assert str(list(prepare.STATE_KEYS_CARRIED)) in doc
diff --git a/tests/curate/test_pixel_unfake_migration.py b/tests/curate/test_pixel_unfake_migration.py
index 4d1008a..91248a4 100644
--- a/tests/curate/test_pixel_unfake_migration.py
+++ b/tests/curate/test_pixel_unfake_migration.py
@@ -57,15 +57,15 @@ def test_explicit_migration_rewrites_the_request(tmp_path, capsys) -> None:
(run_dir / "sprite-request.json").read_text(encoding="utf-8"))["fit"]
# dry run 은 옮길 것이 있다고만 답한다
- assert migrate_request_file(run_dir) is True
+ assert migrate_request_file(run_dir) == ["fit.pixel_perfect -> fit.pixel_unfake"]
assert "pixel_perfect" in json.loads(
(run_dir / "sprite-request.json").read_text(encoding="utf-8"))["fit"]
- assert migrate_request_file(run_dir, apply=True) is True
+ assert migrate_request_file(run_dir, apply=True) == ["fit.pixel_perfect -> fit.pixel_unfake"]
on_disk = json.loads((run_dir / "sprite-request.json").read_text(encoding="utf-8"))
assert on_disk["fit"] == {"pixel_unfake": True, "logical_height": 48}
# 멱등: 두 번째 이관은 옮길 것이 없다
- assert migrate_request_file(run_dir, apply=True) is False
+ assert migrate_request_file(run_dir, apply=True) == []
def test_both_request_keys_present_fails_loud(tmp_path) -> None:
diff --git a/tests/packaging/test_layer_cli_entrypoint.py b/tests/packaging/test_layer_cli_entrypoint.py
deleted file mode 100644
index 17b7bbb..0000000
--- a/tests/packaging/test_layer_cli_entrypoint.py
+++ /dev/null
@@ -1,56 +0,0 @@
-# SPDX-License-Identifier: Apache-2.0
-"""`sprite-gen compose-layers` is the same program as its two other launch forms.
-
-Three entry forms reach one declaration — the console subcommand, `-m
-sprite_gen.compose.compose_layers`, and the `scripts/` wrapper the SKILL.md script map
-lists. A copied flag list would pass on the day it was written and drift on the
-next option, so the wiring itself is pinned (same rule as
-`test_recolor_cli_entrypoint.py`).
-"""
-
-from __future__ import annotations
-
-from pathlib import Path
-
-import pytest
-
-from conftest import help_options as _help_options
-from sprite_gen import cli
-from sprite_gen.compose import compose_layers
-
-ROOT = Path(__file__).resolve().parents[2]
-
-EXPECTED_FLAGS = {"--run-dir", "--names", "--help"}
-
-def test_compose_layers_subcommand_reuses_module_declaration() -> None:
- _description, add_args, run_fn = cli.COMMANDS["compose-layers"]
-
- assert add_args is compose_layers.add_arguments
- assert run_fn is compose_layers.run
-
-
-def test_compose_layers_launch_forms_expose_the_same_flags() -> None:
- subcommand = _help_options("-m", "sprite_gen.cli", "compose-layers")
- module = _help_options("-m", "sprite_gen.compose.compose_layers")
- wrapper = _help_options(str(ROOT / "scripts" / "compose_layers.py"))
-
- assert subcommand == EXPECTED_FLAGS
- assert module == EXPECTED_FLAGS
- assert wrapper == EXPECTED_FLAGS
-
-
[email protected]("value,expected", [
- (None, None),
- ("one", ["one"]),
- ("one,two", ["one", "two"]),
- (" one , two ", ["one", "two"]),
-])
-def test_parse_names_reads_a_subset_selection(value, expected) -> None:
- assert compose_layers.parse_names(value) == expected
-
-
[email protected]("value", ["", ",", "one,", ",one", "one,,two", " "])
-def test_parse_names_rejects_an_empty_entry(value: str) -> None:
- """An empty entry is a typo, not a request to bake everything."""
- with pytest.raises(SystemExit):
- compose_layers.parse_names(value)
diff --git a/tests/packaging/test_numpy_dependency_gate.py b/tests/packaging/test_numpy_dependency_gate.py
index 1638261..117c034 100644
--- a/tests/packaging/test_numpy_dependency_gate.py
+++ b/tests/packaging/test_numpy_dependency_gate.py
@@ -145,7 +145,6 @@ _LAUNCHED_ELSEWHERE = {
"run_correction_loop.py",
"unpack_atlas_run.py",
"serve_curation.py",
- "compose_layers.py",
"recolor.py",
}
diff --git a/tests/packaging/test_package_surface.py b/tests/packaging/test_package_surface.py
index 7263c05..ff6d5c6 100644
--- a/tests/packaging/test_package_surface.py
+++ b/tests/packaging/test_package_surface.py
@@ -21,7 +21,6 @@ PACKAGE_RUN_MODULES = [
"compose_atlas",
"compose_cycle",
"compose_gif",
- "compose_layers",
"correction_loop",
"export_aseprite",
"export_pngs",
diff --git a/tests/spec/test_request_read_no_mutation.py b/tests/spec/test_request_read_no_mutation.py
index 75108f1..ad91e4f 100644
--- a/tests/spec/test_request_read_no_mutation.py
+++ b/tests/spec/test_request_read_no_mutation.py
@@ -144,7 +144,7 @@ def test_loader_holds_no_writer_call(synthetic_fixture_a_run: Path) -> None:
import sprite_gen.spec.runio as _runio_mod
source = Path(_runio_mod.__file__).read_text(encoding="utf-8")
tree = ast.parse(source)
- read_path = {"load_request", "normalize_retired_fit_keys", "_read_request_document"}
+ read_path = {"load_request", "normalize_retired_keys", "_read_request_document"}
offenders: list[str] = []
for node in ast.walk(tree):
if not isinstance(node, ast.FunctionDef) or node.name not in read_path:
diff --git a/tests/spec/test_request_write_isolation.py b/tests/spec/test_request_write_isolation.py
index 12d026f..1389772 100644
--- a/tests/spec/test_request_write_isolation.py
+++ b/tests/spec/test_request_write_isolation.py
@@ -145,7 +145,7 @@ def test_migration_does_not_take_the_pipeline_writer_lock(tmp_path) -> None:
(run_dir / LOCK_FILENAME).write_text(
json.dumps({"owner": "extract", "pid": 1, "started": 0}), encoding="utf-8")
- assert migrate_request_file(run_dir, apply=True) is True
+ assert migrate_request_file(run_dir, apply=True) == ["fit.pixel_perfect -> fit.pixel_unfake"]
assert json.loads((run_dir / REQUEST_FILENAME).read_text(
encoding="utf-8"))["fit"] == {"pixel_unfake": True}
# 남의 락을 소비하지도 않는다 (파일은 그대로)