Skip to content

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

feat(workflow): guide generation requests and save user defaults

Soohong Kim5b00a14bc022
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5893ec1..a8c72f9 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,14 @@
All notable public changes to `sprite-gen` are recorded here. Versions track the `version:` field in `SKILL.md` and `pyproject.toml`.
+## v2.1.0 - Guided requests and saved defaults
+
+- Added two user journeys: sprites (base-image provider, then GPT rows or Grok video) and ordinary images (provider). The read-only `workflow` command checks credentials, resolves request choices over saved defaults and returns the next questions and existing engine route.
+- Added `defaults show|save|clear` with separate sprite/image preferences. Saves require the observed revision, use the existing cross-platform file lock and publish atomically. A stale concurrent writer is rejected; one-off requests and reads never change defaults.
+- Results are delivered before optional curation. The first completed selection can be saved for future requests; saved curation choices skip repeat questions. Subscription and quota remain unknown when not independently verified, and configured video API-credit billing requires its own explicit choice.
+- Simplified the skill entry point, separated conversation and row execution contracts, refreshed all six README entry pages, and removed the retired PR-specific subject-profile proof script. Existing pipeline and utility commands remain available.
+- Removed stick-pose motion guides and obsolete rendering-style bans from generated prompts. Fixed GIF inspection to read each frame's metadata before advancing the decoder.
+
## v2.0.3 - One standing height
- `video-loop` checks that `img2webp` actually supports `-exact` (libwebp >= 1.5; Ubuntu 24.04 ships 1.3.x) and fails by name otherwise instead of writing WebP with rewritten RGB under alpha; CI installs `ffmpeg` and the official libwebp 1.6.0 binaries so the video tests run there, and those tests skip cleanly where support is absent.
diff --git a/README.es.md b/README.es.md
index 14d7afd..db1152d 100644
--- a/README.es.md
+++ b/README.es.md
@@ -25,6 +25,10 @@ Pídele a un modelo de imagen una "sprite sheet" y ya sabes lo que obtienes: un
`sprite-gen` es una skill de Codex/Claude y una CLI de Python que cierra esa brecha. Dale **una imagen base**: dirige la generación fila por fila, fija la identidad del personaje, convierte el fondo croma en alfa real, extrae cada pose como un fotograma transparente limpio y hornea un atlas de runtime **con un `manifest.json.frame_layout` legible por máquina**. Pasa el mismo fotograma a un modelo de vídeo y recibes un bucle transparente sin costura por cada estado de movimiento. Para el último 10 % que la generación nunca acierta, una **webview de curación** te deja comparar, descartar, ajustar y ver el bucle en vivo antes de hornear.
+## Empezar con una petición
+
+Pide **sprites** o **una imagen**. El agente comprueba el acceso, pregunta solo por las opciones que faltan y entrega los archivos mediante el proceso existente. La vista de selección es opcional. Puedes guardar valores predeterminados separados para cada uso; una elección puntual no los modifica. [Flujo y preferencias](docs/user-workflow.md).
+
## Cuatro pipelines, una CLI
Cada verbo funciona solo o como etapa de un pipeline. `sprite-gen --help` imprime este mismo mapa con cada verbo agrupado por dominio.
@@ -33,7 +37,9 @@ Cada verbo funciona solo o como etapa de un pipeline. `sprite-gen --help` imprim
flowchart LR
subgraph A["A · atlas rows"]
direction LR
- a1[prepare] --> a2["gen · gen-set"] --> a3[extract] --> a4[curation] --> a5[compose-atlas]
+ a1[prepare] --> a2["gen · gen-set"] --> a3[extract] --> a5[compose-atlas]
+ a5 -.-> a4["curation (optional)"]
+ a4 --> a5
end
subgraph B["B · video → loop"]
direction LR
diff --git a/README.fr.md b/README.fr.md
index 4ce1516..947f8d7 100644
--- a/README.fr.md
+++ b/README.fr.md
@@ -25,6 +25,10 @@ Demandez une « sprite sheet » à un modèle d'image et vous savez ce que vous
`sprite-gen` est une skill Codex/Claude et une CLI Python qui comble cet écart. Donnez-lui **une image de base** : elle pilote la génération ligne par ligne, verrouille l'identité du personnage, retire le fond chroma en vrai alpha, extrait chaque pose en une image transparente propre et cuit un atlas d'exécution **avec un `manifest.json.frame_layout` lisible par machine**. Passez la même image fixe à un modèle vidéo et vous recevez une boucle transparente sans raccord par état de mouvement. Pour les 10 % que la génération ne réussit jamais, une **webview de curation** permet de comparer, rejeter, ajuster et regarder la boucle en direct avant de cuire.
+## Commencer par une demande
+
+Demandez des **sprites** ou **une image**. L'agent vérifie l'accès, demande seulement les choix manquants et livre les fichiers avec le pipeline existant. La vue de sélection est facultative. Enregistrez des préférences distinctes pour chaque usage ; un choix ponctuel ne les remplace pas. [Parcours et préférences](docs/user-workflow.md).
+
## Quatre pipelines, une CLI
Chaque verbe fonctionne seul ou comme étape d'un pipeline. `sprite-gen --help` affiche cette même carte, chaque verbe groupé par domaine.
@@ -33,7 +37,9 @@ Chaque verbe fonctionne seul ou comme étape d'un pipeline. `sprite-gen --help`
flowchart LR
subgraph A["A · atlas rows"]
direction LR
- a1[prepare] --> a2["gen · gen-set"] --> a3[extract] --> a4[curation] --> a5[compose-atlas]
+ a1[prepare] --> a2["gen · gen-set"] --> a3[extract] --> a5[compose-atlas]
+ a5 -.-> a4["curation (optional)"]
+ a4 --> a5
end
subgraph B["B · video → loop"]
direction LR
diff --git a/README.ja.md b/README.ja.md
index f45a5ba..9febb32 100644
--- a/README.ja.md
+++ b/README.ja.md
@@ -25,6 +25,10 @@
`sprite-gen` はその隙間を埋める Codex/Claude スキルであり Python CLI だ。**ベース画像一枚**を渡すと、行ごとに生成を進め、キャラの identity を固定し、クロマ背景を本物のアルファに剥がし、ポーズごとに綺麗な透明フレームを取り出し、**機械可読な `manifest.json.frame_layout`** 付きのランタイムアトラスを焼く。同じ静止画を動画モデルに渡せば、モーション状態ごとに継ぎ目のない透明ループが返ってくる。生成が最後まで合わせられない 10% は**キュレーション Webview** で比較・除外・微調整し、ループを実再生で確かめてから焼く。
+## リクエストから始める
+
+**スプライト作成**または**画像作成**を依頼してください。利用状態を確認し、未指定の生成ツールと動作方式だけを質問して、既存のパイプラインで結果を渡します。キュレーション画面は任意です。用途別の既定値を保存でき、今回だけの指定では保存値を変更しません。[リクエストと既定値](docs/user-workflow.md)。
+
## 4 本のパイプライン、1 つの CLI
どの verb も単独でも、パイプラインの一段としても使える。`sprite-gen --help` が同じ地図をドメイン別 verb で表示する。
@@ -33,7 +37,9 @@
flowchart LR
subgraph A["A · atlas rows"]
direction LR
- a1[prepare] --> a2["gen · gen-set"] --> a3[extract] --> a4[curation] --> a5[compose-atlas]
+ a1[prepare] --> a2["gen · gen-set"] --> a3[extract] --> a5[compose-atlas]
+ a5 -.-> a4["curation (optional)"]
+ a4 --> a5
end
subgraph B["B · video → loop"]
direction LR
diff --git a/README.ko.md b/README.ko.md
index 2643bbd..99b1711 100644
--- a/README.ko.md
+++ b/README.ko.md
@@ -25,6 +25,10 @@
`sprite-gen` 은 그 간극을 메우는 Codex/Claude 스킬이자 파이썬 CLI 다. **베이스 이미지 한 장**을 주면 행 단위로 생성을 몰고, 캐릭터 identity 를 고정하고, 크로마 배경을 진짜 알파로 벗기고, 포즈마다 깨끗한 투명 프레임을 뽑아 **기계가 읽는 `manifest.json.frame_layout`** 이 딸린 런타임 아틀라스를 굽는다. 같은 스틸을 영상 모델에 넘기면 모션 상태별로 이음새 없는 투명 루프가 돌아온다. 생성이 끝내 못 맞추는 마지막 10% 는 **큐레이션 웹뷰**에서 비교·거부·미세조정하고 루프를 실재생으로 본 뒤 굽는다.
+## 요청으로 시작하기
+
+**스프라이트 만들기** 또는 **이미지 만들기**를 요청하세요. 이용 상태를 확인하고 생성 도구와 동작 방식 중 빠진 선택만 물어본 뒤 기존 파이프라인으로 결과를 전달합니다. 큐레이션뷰는 선택 사항입니다. 두 요청의 기본 설정을 따로 저장할 수 있고, 이번 요청의 선택은 저장값을 바꾸지 않습니다. [요청 흐름과 기본 설정](docs/user-workflow.md).
+
## 파이프라인 4종, CLI 하나
모든 verb 는 단독으로도, 파이프라인 단계로도 쓴다. `sprite-gen --help` 가 같은 지도를 도메인별 verb 로 출력한다.
@@ -33,7 +37,9 @@
flowchart LR
subgraph A["A · atlas rows"]
direction LR
- a1[prepare] --> a2["gen · gen-set"] --> a3[extract] --> a4[curation] --> a5[compose-atlas]
+ a1[prepare] --> a2["gen · gen-set"] --> a3[extract] --> a5[compose-atlas]
+ a5 -.-> a4["curation (optional)"]
+ a4 --> a5
end
subgraph B["B · video → loop"]
direction LR
diff --git a/README.md b/README.md
index 38d50ef..14f0b81 100644
--- a/README.md
+++ b/README.md
@@ -24,6 +24,10 @@ Ask an image model for a "sprite sheet" and you know what you get: a character w
`sprite-gen` is a Codex/Claude skill and a Python CLI that closes that gap. Give it **one base image** — it drives generation row by row, locks the character's identity, strips the chroma background to real alpha, extracts each pose as a clean transparent frame, and bakes a runtime atlas **with a machine-readable `manifest.json.frame_layout`**. Or hand the same still to a video model and get back a seamless, transparent loop per motion state. For the last 10% that generation never gets right, a **curation webview** lets you compare, reject, nudge and watch the loop live before you bake.
+## Start with a request
+
+Ask for **sprites** or **an image**. The agent checks access, asks only for missing provider/motion choices, runs the existing pipeline, and delivers the files. The curation view is optional. Save your choices once to reuse separate sprite and image defaults; a one-off request does not overwrite them. [User workflow and defaults](docs/user-workflow.md).
+
## Four pipelines, one CLI
Every verb works alone or as a pipeline stage. `sprite-gen --help` prints this same map, with every verb grouped by domain.
@@ -32,7 +36,9 @@ Every verb works alone or as a pipeline stage. `sprite-gen --help` prints this s
flowchart LR
subgraph A["A · atlas rows"]
direction LR
- a1[prepare] --> a2["gen · gen-set"] --> a3[extract] --> a4[curation] --> a5[compose-atlas]
+ a1[prepare] --> a2["gen · gen-set"] --> a3[extract] --> a5[compose-atlas]
+ a5 -.-> a4["curation (optional)"]
+ a4 --> a5
end
subgraph B["B · video → loop"]
direction LR
@@ -82,8 +88,8 @@ sprite-gen --help
sprite-gen prepare --out-dir <run> --character-id <id> --base-image base.png # request, guides, prompts
sprite-gen gen-set --run-dir <run> --provider codex # every state row, 4 at a time
sprite-gen extract --run-dir <run> # chroma → transparent frames
-sprite-gen curation --run-dir <run> # (optional) pick, nudge, breathe
sprite-gen compose-atlas --run-dir <run> # sprite-sheet-alpha.png + manifest.json
+sprite-gen curation --run-dir <run> # (optional) pick, nudge, breathe
```
**B · video → loop** — one still to transparent loops (needs `ffmpeg`, `img2webp`, and your own `grok` login or `XAI_API_KEY`).
diff --git a/README.zh-Hans.md b/README.zh-Hans.md
index 3a5745c..5bb2a30 100644
--- a/README.zh-Hans.md
+++ b/README.zh-Hans.md
@@ -25,6 +25,10 @@
`sprite-gen` 是补上这道缺口的 Codex/Claude 技能兼 Python CLI。给它**一张基础图**——它逐行驱动生成、锁定角色 identity、把色键背景剥成真正的 alpha、把每个姿势提取为干净的透明帧,并烘焙出带**机器可读 `manifest.json.frame_layout`** 的运行时图集。把同一张静止图交给视频模型,就能得到每个动作状态一段无缝透明循环。生成永远做不对的最后 10%,交给**策展 Webview**:对比、剔除、微调,实时观看循环后再烘焙。
+## 从请求开始
+
+请求**制作精灵图**或**生成图片**。代理检查使用状态,只询问尚未指定的生成工具和动作方式,再通过现有流程交付结果。筛选视图可选。两种用途可分别保存默认设置;单次请求不会覆盖已保存的设置。[请求流程与默认设置](docs/user-workflow.md)。
+
## 四条流水线,一个 CLI
每个 verb 既能单独使用,也能作为流水线的一环。`sprite-gen --help` 会按领域分组打印同一张地图。
@@ -33,7 +37,9 @@
flowchart LR
subgraph A["A · atlas rows"]
direction LR
- a1[prepare] --> a2["gen · gen-set"] --> a3[extract] --> a4[curation] --> a5[compose-atlas]
+ a1[prepare] --> a2["gen · gen-set"] --> a3[extract] --> a5[compose-atlas]
+ a5 -.-> a4["curation (optional)"]
+ a4 --> a5
end
subgraph B["B · video → loop"]
direction LR
diff --git a/SKILL.md b/SKILL.md
index 162fe1e..c05c448 100644
--- a/SKILL.md
+++ b/SKILL.md
@@ -1,7 +1,7 @@
---
name: sprite-gen
-version: 2.0.3
-description: "Generate clean 2D game sprites and animation atlases with a component-row pipeline: base identity, numeric sprite-request SSoT, per-state layout guides, image-gen row strips, chroma-key alpha cleanup, connected-component frame extraction, cell-based atlas composition, QA reports, and runtime manifest frame_layout. Its curation webview also serves ANY image-candidate set (icons, logos, generated drafts) — agent chat can't render images, this can: unpack_atlas_run --pngs-dir import, then serve_curation side-by-side compare/pick. Palette-swap bake (`sprite-gen recolor`) turns a base sheet + palette map into N colourway sheets; the curation view blink-compares and adopts a pick into curation.json.recolor.picked. Curation triggers (KR/EN): 큐레이션, 큐레이션뷰, 큐레이션 해줘, 이미지 후보 보여줘/안 보임, 나란히 비교, 골라볼게 띄워줘, curation view, show image candidates side by side, let me pick. Recolor triggers (KR/EN): 팔레트 스왑, 팔레트 베이크, 리컬러, 색깔 바꾸기, 컬러웨이, 색 변형, 팔레트 맵, 색갈이, palette swap, recolor, colourway, colorway, bake variants, palette map."
+version: 2.1.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, chroma removal, animation atlases, video loops, 큐레이션뷰, image candidates, 팔레트 스왑, palette swap, recolor, rig layers and engine exports."
license: Apache-2.0
depends_on:
required_bins:
@@ -44,185 +44,41 @@ modes:
# Sprite Gen
-One still → clean 2D game sprites. Three routes, one engine (`sprite_gen/`), one interpreter.
+Two user entry points: **make sprites** or **make an image**. Existing generation, extraction and export tools do the work; the user chooses the result and provider.
-## 라우트 — 무엇을 원하나 → 어디로
+## Start every generation request here
-| 원하는 것 | 명령 | 계약 |
-|---|---|---|
-| PNG 스틸 1장 (투명 포함) — 아이콘·초상·컨셉·베이스 | `sprite-gen gen` (codex 기본 / grok) | [`docs/gen.md`](docs/gen.md) — 투명은 프로바이더 전략(codex native · grok chroma) |
-| **애니메이션 아틀라스** — 행 파이프라인 (`component-row`) | `prepare` → `gen` → `extract` → `curation` → `compose-atlas` (아래 Workflow) | [`docs/run-contract.md`](docs/run-contract.md), [`docs/architecture.md`](docs/architecture.md) |
-| **영상 → 투명 루프 세트** — 상태별 GIF/WebP/스트립 | `video-canvas` → `video` → `video-frames` → `video-loop`, 배치는 `video-set` | [`docs/video-pipeline.md`](docs/video-pipeline.md), [`docs/video.md`](docs/video.md) |
-| 이미지 후보 비교·선택 (스프라이트 아님) | `unpack-atlas --pngs-dir` → `curation` | [`docs/curation.md`](docs/curation.md) |
-| 가져온 이미지 배경 제거 / 그리드 시트 슬라이스 | `cutout` / `slice-sheet` | Script Map · [`docs/sheet-slicing.md`](docs/sheet-slicing.md) |
-| 완성 시트 팔레트 스왑 (컬러웨이) | `recolor-palette` → `recolor` (Workflow 4.5) | [`docs/recolor.md`](docs/recolor.md) |
-| 리그 런 레이어 합성 | `compose-layers` (Workflow 4.6) | [`docs/layer-tracks.md`](docs/layer-tracks.md) |
-
-행 파이프라인의 모양:
-
-```text
-sprite-request.json -> layout guides + prompts -> image-gen state rows
--> chroma alpha -> connected components -> transparent cells
--> sprite-sheet-alpha.png + manifest.json.frame_layout
-```
-
-Use only the `component-row` pipeline for atlases. One-shot master sheets, fixed-grid atlas cutting, local drawing, or static fallback are not a sprite result.
-
-## 실행 인터프리터 (BLOCKING)
-
-모든 명령은 **레포 루트 venv 의 인터프리터**로 실행한다 — 전역 `python3` 는 이 스킬의 인터프리터가 아니다:
+Read [user-workflow](docs/user-workflow.md), then run the appropriate read-only guide:
```bash
-export SPRITE_GEN_ROOT=/path/to/sprite-gen
-$SPRITE_GEN_ROOT/.venv/bin/python <script.py> ... # 래퍼 스크립트
-$SPRITE_GEN_ROOT/.venv/bin/sprite-gen <tool> ... # 콘솔 스크립트 (동치)
+$SPRITE_GEN_ROOT/.venv/bin/sprite-gen workflow --kind sprite
+$SPRITE_GEN_ROOT/.venv/bin/sprite-gen workflow --kind image
```
-- 부트스트랩은 README quickstart·CI 와 같은 한 줄: `python3 -m venv .venv && .venv/bin/pip install -e .`. `.venv` 가 없으면 만든다.
-- **폴백 금지**: "`.venv` 있으면 그거, 없으면 `python3`" 같은 해석은 없다 — 없으면 만들거나 요란하게 실패한다(원칙 6).
-- **NumPy 가 없는 인터프리터에서는 아무것도 시작하지 않는다**: 진입점이 패키지 import 시점에 멈추고 실행한 인터프리터 경로와 부트스트랩 명령을 찍는다. 순수 파이썬 폴백은 없다(추출 경로는 바이트 동일 계약).
-- `SKILL.md`·`docs/*.md` 안에서는 절대경로 형식만 쓴다(활성화 없는 셸에서 읽힌다). 자식 프로세스는 `sys.executable` 을 상속하므로 띄우는 순간 한 곳만 옳으면 된다.
-- 근거·함정·레지스터 상세: [`docs/interpreter.md`](docs/interpreter.md).
-
-## 필수 게이트 — AI raw 는 최종 에셋이 아니다 (BLOCKING)
+Pass choices already stated in the request. The guide checks access, combines explicit choices with saved defaults, and returns only missing questions. Follow its start and finish stages. Always pass the resolved provider explicitly to generation tools. Deliver checked files before offering the curation view; save defaults only when the user agrees. The complete conversation and settings contract is owned by the linked document, not duplicated in individual pipeline docs.
-- [ ] **AI 개입은 raw 생성 한 곳뿐이다.** `raw/<state>.png` 는 중간 산출물이고 최종 에셋은 결정론 변환(`extract_sprite_row_frames.py`: 크로마 제거 → 컴포넌트 분리 → 피치 검출/그리드 스냅 → kCentroid → 공유 팔레트 → 셀 배치)을 거친다. 같은 입력 = 같은 출력인 코드 경로만 픽셀 언페이크다.
-- [ ] **단순 다운스케일 쇼트컷 금지.** raw 를 `resize()` 한 줄로 줄여 최종 경로에 놓지 않는다 — 낱장이라도 run dir 를 만들어 같은 추출 경로를 태운다.
-- [ ] **베이스/앵커가 스타일 SSoT 다.** 이미지 모델은 첨부 레퍼런스를 프롬프트보다 강하게 따른다. `fit.pixel_unfake` 런이면 베이스부터 진짜 도트(균일 블록 피치 실측, AA 가장자리 없음)여야 한다 — 프롬프트 문구로 베이스 스타일을 이기려 하지 마라.
-- [ ] **크로마 키는 소재색을 먼저 보고 고른다.** 핑크/보라/자주 소재 → 그린 `#00FF00`, 녹색/청록 → 마젠타 `#FF00FF`. 분기표: [`docs/chroma-alpha.md`](docs/chroma-alpha.md). 변환 후 소재색이 빠졌으면 로컬 보정이 아니라 키를 바꿔 재생성한다.
-- [ ] **어휘/키 리네임은 일괄 치환으로 시작하지 않는다** — 층위 순서와 mutant 검증: [`docs/rename-gate.md`](docs/rename-gate.md).
+## Execution routes
-## Base Lock Gate (Stage 0, BLOCKING)
-
-```text
-identity truth = accepted idle anchor
-motion truth = layout guide + paired/basis row when needed
-base truth = used only to create idle anchors, then removed from row inputs
-```
-
-Before any row generation answer `y`/`n`: **is there an image good enough to lock as the canonical base idle?** It locks only when all hold — full body uncropped · final proportions/style already correct (SD 비율, 도트 look, 외곽선 두께 — rows never "fix it later") · pixel-art run ⇒ true pixel art with a measurable grid · identity matches the reference · one clear idle pose facing the intended camera, readable small · flat chroma-ready background. `n` ⇒ iterate base candidates and re-gate; **do not run `prepare_sprite_run.py` until locked.** The locked file becomes the direction's idle anchor and is not re-attached after the anchors replace it. Reference-ownership flow: [`docs/architecture.md`](docs/architecture.md) §5.
-
-## Script Map
-
-One job each, all under `scripts/` (wrappers) ↔ `sprite_gen/<domain>/` (impl). Stage detail: [`docs/architecture.md`](docs/architecture.md) §2.
-
-| Script / verb | Job | Doc |
+| Task | Entry | Contract |
|---|---|---|
-| `prepare_sprite_run.py` | request → `sprite-request.json`, layout guides, prompts, empty `raw/`+`frames/` | run-contract §2 |
-| `generate_sprite_image.py` (`gen`) | one still via codex `image_gen` / grok Imagine → verified PNG (+ transparent strategy) | [`docs/gen.md`](docs/gen.md) |
-| `gen_set.py` (`gen-set`) | every state row of a prepared run, N at a time — identity ref from the run (base or accepted anchor), one report per row, `table.md`, non-zero exit on any failure | [`docs/gen.md`](docs/gen.md) |
-| `generate_sprite_video.py` (`video`) | one still → verified mp4 via Grok Imagine, user's own login / `XAI_API_KEY` | [`docs/video.md`](docs/video.md) |
-| `video_canvas.py` · `video_frames.py` · `video_loop.py` · `video_set.py` | state canvas (jump tall / attack wide / else square) · ffmpeg + keying · true-period cycle → strip/GIF/WebP · directions × states batch | [`docs/video-pipeline.md`](docs/video-pipeline.md) |
-| `extract_sprite_row_frames.py` (`extract`) | `raw/<state>.png` → chroma removal → components → transparent cells + `frames/frames-manifest.json` | run-contract · [`docs/pixel-unfake.md`](docs/pixel-unfake.md) |
-| `interpolate_frames.py` | generative in-between (codex/grok) recorded as a take | [`docs/frame-interpolation.md`](docs/frame-interpolation.md) |
-| `compose_sprite_atlas.py` (`compose-atlas`) | `sprite-sheet-alpha.png` + runtime `manifest.json.frame_layout` (breathing baked as a post-process layer) | run-contract · [`docs/breathing.md`](docs/breathing.md) |
-| `compose_sprite_gif.py` · `compose_selected_cycle.py` · `preview_animation.py` | clean transparent GIFs · selected-cycle manifest · QA contact sheets/GIFs | [`docs/locomotion-curation.md`](docs/locomotion-curation.md), [`docs/qa-motion.md`](docs/qa-motion.md) |
-| `export_aseprite.py` (`export-aseprite`) | Aseprite-compatible JSON for Phaser / Flame | [`docs/engine-export.md`](docs/engine-export.md) |
-| `inspect_sprite_run.py` · `score_sprite_run.py` · `run_correction_loop.py` | deterministic row inspection → 0-100 score → bounded correction loop (explicit provider command; no silent generator) | QA below |
-| `curation.py` · `serve_curation.py` (`curation`) · `sprite_gen/curate/anchor.py` (`anchor`) | sidecar SSoT + stamping writer · webview · direction-anchor SSoT and `references/anchors/<dir>-anchor-x8.png` | [`docs/curation.md`](docs/curation.md), [`docs/directional-anchor-workflow.md`](docs/directional-anchor-workflow.md) |
-| `runio.py` | single-writer lock (`.sprite-gen.lock`) + atomic writes; parallel agents never interleave one character folder | run-contract |
-| `recolor.py` (`recolor` / `recolor-palette`) | deterministic palette-swap bake → `variants/` + report (exact match; opt-in tolerance) | [`docs/recolor.md`](docs/recolor.md) |
-| `compose_layers.py` (`sprite-gen compose-layers`) | rig runs only: curated rows stacked by integer pivots + masks → `layers/` (all-or-nothing) | [`docs/layer-tracks.md`](docs/layer-tracks.md) |
-| `unpack_atlas_run.py` (`unpack-atlas`) · `export_curated_pngs.py` (`export-pngs`) | finished sheet / PNG folder → curator-ready run · curated frames → named PNGs (`curated/`) | [`docs/curation.md`](docs/curation.md) |
-| `cutout` · `slice_sheet_cells.py` (`slice-sheet`) · `dev/check_visible_magenta.py` | imported-image background removal (white matte / chroma engine) · multi-figure sheet → per-cell cuts · screenshot chroma-leak guard | [`docs/sheet-slicing.md`](docs/sheet-slicing.md) |
-
-Breathing (idle) and static-pose rows are a **post-process layer** declared in `curation.json` (`states.<state>.breathe`) and baked by compose — never a script step; the contract (anatomy detection, editor, rigid boundary, `migrate-breathe`) is [`docs/breathing.md`](docs/breathing.md) and [`docs/breathing.md`](docs/breathing.md) "정지 자세 행 레시피".
-
-## Workflow (atlas route)
-
-0. Pass the **Base Lock Gate**.
-
-1. Prepare the run:
-
-```bash
-$SPRITE_GEN_ROOT/.venv/bin/python $SPRITE_GEN_ROOT/scripts/prepare_sprite_run.py \
- --out-dir <target>/assets/generated/sprites/<character-id> \
- --character-id <character-id> --base-image /absolute/path/to/base.png \
- --description "<short identity note>" --force
-```
-
-Hatch-pet-style locomotion adds the cell gate (`--cell-width 192 --cell-height 208`). Directional characters declare the direction contract (`--directions down,side,up --mirror left=side`); files then follow the taxonomy `raw/<dir>/<pose>.png`, `frames/<dir>/<pose>/` (path resolver SSoT `sprite_gen/layout.py`, frame paths SSoT = frames-manifest `row.files`) and `prepare` records the generation chain in `references/generation-plan.json` — [`docs/directional-anchor-workflow.md`](docs/directional-anchor-workflow.md). Writes `sprite-request.json`, `base-source.<ext>`, `references/layout-guides/<state>.png`, `prompts/<state>.txt`, `raw/`, `frames/`.
-
-2. Generate the rows (the one AI step; the `image-gen` skill is a thin shuttle over this). The batch form is the default — `$SPRITE_GEN_ROOT/.venv/bin/sprite-gen gen-set --run-dir <run>` generates every non-mirrored state 6 at a time with the run's own identity ref and writes `reports/gen-set/table.md`; one row by hand:
-
-```bash
-$SPRITE_GEN_ROOT/.venv/bin/python $SPRITE_GEN_ROOT/scripts/generate_sprite_image.py \
- --provider codex --prompt-file <run>/prompts/<state>.txt --out <run>/raw/<state>.png \
- --ref <run>/base-source.<ext> --ref <run>/references/layout-guides/<state>.png
-```
-
-- `--provider` is optional: default codex (`SPRITE_GEN_DEFAULT_PROVIDER` overrides; observable grok fallback only if codex is unavailable). Rows keep the request chroma key and are generated **without** `--transparent`; standalone stills use `--transparent` (codex native alpha first, grok chroma) — [`docs/gen.md`](docs/gen.md).
-- References: default states attach exactly two — `base-source.<ext>` + the state layout guide. Direction-anchor mode attaches the accepted anchor instead of the base: **never pick the anchor crop by hand**, ask `$SPRITE_GEN_ROOT/.venv/bin/python -m sprite_gen.cli anchor --run-dir <run> --for-state <state>` right before each generation (derived cache, re-run every time; the human pins which frame). Extra motion references only when recorded in `qa-notes.md`.
-- **Concurrency (lead-verified 2026-08, no throttling at 6)**: multi-row batches run **6 at a time** — that is `gen-set`'s default `--concurrency`; serial one-by-one is an anti-pattern. `runio.py` locks make parallel `raw/<state>.png` writes safe. Providers are engine backends, not agents — no worker surface is spawned ([`docs/gen.md`](docs/gen.md#provider-topology)).
-
-3. Extract frames — chroma removal, connected components, one transparent request-sized cell per pose, `frames/<state>/frame-N.png` + `frames/frames-manifest.json`:
-
-```bash
-$SPRITE_GEN_ROOT/.venv/bin/python $SPRITE_GEN_ROOT/scripts/extract_sprite_row_frames.py --run-dir <run>
-```
-
-3.5. (Optional) Curate in the webview — compare, select/reject, reorder, non-destructive transforms in `curation.json` (originals never rewritten): `$SPRITE_GEN_ROOT/.venv/bin/sprite-gen curation --run-dir <run>` — [`docs/curation.md`](docs/curation.md).
-
-4. Compose the runtime atlas — `sprite-sheet-alpha.png`, `sprite-sheet-alpha.report.json`, `manifest.json` (`frame_layout` is the runtime SSoT; game code consumes rectangles, never recovers them from alpha):
-
-```bash
-$SPRITE_GEN_ROOT/.venv/bin/python $SPRITE_GEN_ROOT/scripts/compose_sprite_atlas.py --run-dir <run>
-```
-
-4.5. (Optional) Colourways: `$SPRITE_GEN_ROOT/.venv/bin/sprite-gen recolor-palette --base <run>/sprite-sheet-alpha.png --out <run>/palette.draft.json` then `$SPRITE_GEN_ROOT/.venv/bin/sprite-gen recolor --run-dir <run> --spec <run>/recolor.spec.json` — exact RGB by default, opt-in tolerance, every unused/unmapped colour named in the report — [`docs/recolor.md`](docs/recolor.md).
-
-4.6. (Optional, rig runs only) `$SPRITE_GEN_ROOT/.venv/bin/sprite-gen compose-layers --run-dir <run>` bakes the declared stacks into `layers/`; `--names a,b` bakes a subset — [`docs/layer-tracks.md`](docs/layer-tracks.md).
-
-5. Close by launching the webview in the background and reporting its URL (`… sprite-gen curation --run-dir <run> &`) — finishing a run means handing the human the open view, not file paths. Multi-agent launch rules (free port, one view per run, `--no-open` headless): [`docs/curation.md`](docs/curation.md). Skip only for an explicitly unattended batch.
-
-## Video → loop route
-
-```bash
-$SPRITE_GEN_ROOT/.venv/bin/sprite-gen video-set \
- --base side=<still.png> --states idle,walk,run,jump,attack --out-dir <set-dir> \
- --character "<subject phrase>"
-```
-
-Per item: `video-canvas` (the still padded into the state's canvas — the API ignores `aspect_ratio`, the input frame decides) → `video` (in-place, evenly paced, returns-to-start prompt) → `video-frames` (ffmpeg + cutout keying; edge contact fails loud) → `video-loop` (global period first, then best seam; for `jump`/`attack` a clip that performs the action once gets a recorded one-shot cut, `cycle.kind` in the report; strip + `body_h` meta, 1-bit GIF, `img2webp -exact` WebP, seam gate). Starts are staggered for the 2 req/s team quota, a 429 retries once or twice, every item reports and `table.md` lists failures by name. Render strips at 24 fps (one cell per frame). Contract and the measurements behind each rule: [`docs/video-pipeline.md`](docs/video-pipeline.md).
+| GPT image sprites | `prepare`, `gen-set --provider codex`, `extract`, compose and QA | [atlas-workflow](docs/atlas-workflow.md) |
+| Grok video sprites | `video-set` | [video-pipeline](docs/video-pipeline.md) |
+| Ordinary image or edit | `gen --provider codex` or `gen --provider grok` | [gen](docs/gen.md) |
+| Base and direction anchors | `anchor` | [directional-anchor-workflow](docs/directional-anchor-workflow.md) |
+| 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 | curation choice, baked by compose | [breathing](docs/breathing.md) |
+| Engine exports | `export-aseprite`, `export-pngs` | [engine-export](docs/engine-export.md) |
+| Defaults | `defaults show`, `defaults save`, `defaults clear` | [user-workflow](docs/user-workflow.md#one-settings-owner) |
-## SSoT
+Use existing automatic pipeline stages for background removal, extraction, alignment and export. Do not ask users to select each script. For a direct utility request, run that utility; no unrelated generation questions are needed. Preserve the row pipeline and component extraction for image sprites. One-shot grid generation and fixed cell cutting are not an alternative sprite-generation route.
-Every atlas run starts with `sprite-request.json` — it owns the numeric recipe prompts and scripts read (`cell` size/shape/safe margin, `chroma_key`, `states.<state>.{frames,fps,loop,action}`, optional `takes`, optional `fit`). `256` is a default variable; change it in the request and regenerate guides, prompts, extraction and atlas from the same request. Default `safe_margin` is proportional (9.4 % of the cell, floored). Rectangular cells (`"shape": "rect"`) are allowed; runtime never assumes square. `frames/` is a derived cache of (raw + request + engine) healed on entry (`heal_run`), so "re-extract" is never a separate instruction. Schema, takes, revisions: [`docs/run-contract.md`](docs/run-contract.md) §2; states and frame counts: [`docs/states-and-frames.md`](docs/states-and-frames.md); `fit` / `pixel_unfake`: [`docs/pixel-unfake.md`](docs/pixel-unfake.md).
-
-## Prompt Contract
-
-The row prompt comes from `prompts/<state>.txt` — never hand-write frame counts elsewhere. It carries the exact frame count, one full-body pose per invisible request-sized slot, the safe margin, the locked anchor identity, motion-only responsibility, the flat chroma-key background, and the ban on shadows/glows/smears/speed lines/scenery/text/UI/guide boxes/detached effects. Guide boxes, labels, overlaps, backgrounds, cropped bodies or identity drift ⇒ **regenerate the row**; never repair generation by drawing or tiling locally.
-
-## Output Contract
-
-**Install from `curated/`, never from `frames/`** — picks, pixel edits and transforms live in `curation.json` and are applied downstream (stills → `export_curated_pngs.py`; animation → atlas + manifest). One worker owns one character folder; the canonical run-dir tree is [`docs/run-contract.md`](docs/run-contract.md) §2, the sidecar schema [`docs/curation.md`](docs/curation.md).
-
-## Runtime Contract
-
-`manifest.json` carries `game_input: "sprite-sheet-alpha.png"`, `degraded_static_fallback: false`, `animation.rows.<state>` (`frames`, `fps`, `durations_ms`, `loop`) and `frame_layout.rows.<state>[i]` absolute rectangles. Runtime samples only the active rectangle. `frame_layout` is in playback order and duplicate instances **repeat the same rect**; `durations_ms[i]` is the per-frame timing SSoT (holds = rect reuse or a longer duration). Static fallback is explicit survival output only — it never creates `sprite-sheet-alpha.png`.
-
-## QA
-
-All must pass before reporting done: `frames/frames-manifest.json.ok` · `sprite-sheet-alpha.report.json.ok` · declared frame count per state · no empty or near-opaque-background frame · no excessive edge/chroma-adjacent pixels · `scripts/check_visible_magenta.py` on game screenshots when used.
-
-Correction loop dry run: `$SPRITE_GEN_ROOT/.venv/bin/python $SPRITE_GEN_ROOT/scripts/run_correction_loop.py --run-dir <run> --states <state> --dry-run` (writes `correction-loop.report.json`, per-attempt `inspect.json` / `score.json` / `correction-hints.txt`; a live loop needs an explicit provider command, `--min-attempts 2` forces one regeneration).
-
-### Motion Continuity (BLOCKING)
-
-Static identity QA is not enough. Build previews (`$SPRITE_GEN_ROOT/.venv/bin/python $SPRITE_GEN_ROOT/scripts/preview_animation.py --run-dir <run>`) and judge motion **as motion** by [`docs/qa-motion.md`](docs/qa-motion.md); a failing row is regenerated, never re-timed locally. Record the per-state verdict in `qa-notes.md`.
-
-Report:
-
-```text
-sprite_gen_done=<character-id>
-folder=<absolute folder path>
-engine=component-row
-files=sprite-request,raw,frames,atlas,manifest
-qa_note=<one sentence>
-```
+## 실행 인터프리터
-## Docs Topology
+`SPRITE_GEN_ROOT` is the absolute installed repository path. Use `$SPRITE_GEN_ROOT/.venv/bin/sprite-gen` or `$SPRITE_GEN_ROOT/.venv/bin/python`; do not assume an activated shell. **폴백 금지**: create a missing venv or report the failure, never use an arbitrary global Python. **NumPy 가 없는 인터프리터** fails at package import. Setup and diagnosis: [interpreter](docs/interpreter.md).
-The documentation index is [`docs/README.md`](docs/README.md): every leaf doc once, under the four pipelines (A atlas rows · B video → loop · C utilities · D post-processing) and the taxonomy branches, each with a one-line owner. Leaf docs are one link deep; each owns its tables and this hub only points. Architecture with the domain and pipeline diagrams: [`docs/architecture.md`](docs/architecture.md).
+## Contracts and advanced tools
-Concept ownership: `sprite-request.json`/cell/states/takes → run-contract §2 · states-and-frames; `run_revision`/salvage/`curation.stale-*.json` and every `curation.json` field (`selected`/`order`/`deleted`/`transforms`/`pixels`/`clones`/`pixel_unfake`/`revision`/`recolor.picked`) → curation.md; frame **clones** → curation.md + compose; `frame_layout` runtime contract → run-contract + "Runtime Contract" above; `fit`/pixel-unfake twins → pixel-unfake.md; recolor spec/report/`variants/` → recolor.md; `rig`/`track`/`layers` → layer-tracks.md; video canvas/period/seam/strip meta → video-pipeline.md; webview interactions → `sprite_gen/curator/` described in curation.md + recolor.md.
+[run-contract](docs/run-contract.md) owns numeric requests, run layout, atomic publication and curated exports. [architecture](docs/architecture.md) explains domain ownership. [docs index](docs/README.md) lists every specialized feature and QA procedure. `sprite-gen --help` derives the command map from the package catalog. Never replace canonical extraction with temporary crop scripts while presenting the result as a pipeline output.
diff --git a/docs/README.md b/docs/README.md
index 8734284..8baf173 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -8,7 +8,9 @@ pipeline you are running, then follow its contract doc.
flowchart LR
subgraph A["A · atlas rows"]
direction LR
- a1[prepare] --> a2["gen · gen-set"] --> a3[extract] --> a4[curation] --> a5[compose-atlas]
+ a1[prepare] --> a2["gen · gen-set"] --> a3[extract] --> a5[compose-atlas]
+ a5 -.-> a4["curation (optional)"]
+ a4 --> a5
end
subgraph B["B · video → loop"]
direction LR
@@ -27,7 +29,7 @@ flowchart LR
| Pipeline | Entry doc | Verbs |
|---|---|---|
-| **A · atlas rows** — one still becomes a runtime sprite sheet | [run-contract.md](run-contract.md) | `prepare` → `gen` / `gen-set` → `extract` → `curation` → `compose-atlas` |
+| **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` → `video-frames` → `video-loop`, `video-set` |
| **C · utilities** — imported images in, clean cuts out | [sheet-slicing.md](sheet-slicing.md) | `cutout`, `slice-sheet`, `unpack-atlas` |
| **D · post-processing** — finished sheets, refined | [recolor.md](recolor.md) | `recolor`, `recolor-palette`, `compose-layers`, breathing (compose), `export-pngs`, `export-aseprite` |
@@ -35,6 +37,13 @@ flowchart LR
`sprite-gen --help` prints the same four pipelines and every verb grouped by domain; the
grouping is derived from `sprite_gen/_modules.py`, the one taxonomy table.
+## User requests
+
+| Doc | Owns |
+|---|---|
+| [user-workflow.md](user-workflow.md) | Two conversation flows, access checks, optional curation and saved defaults |
+| [atlas-workflow.md](atlas-workflow.md) | Execution of GPT row sprites through the existing extraction pipeline |
+
## Contract & structure
| Doc | Owns |
diff --git a/docs/atlas-workflow.md b/docs/atlas-workflow.md
new file mode 100644
index 0000000..4c3a071
--- /dev/null
+++ b/docs/atlas-workflow.md
@@ -0,0 +1,27 @@
+# Execute the existing row sprite pipeline
+
+This page owns the agent's row execution procedure. Start and finish conversation choices belong to [user-workflow](user-workflow.md). Stage data, numeric settings and output ownership belong to [run-contract](run-contract.md).
+
+## Lock the base before preparing a run
+
+Use one accepted, uncropped, full-body idle image with the intended proportions, style, orientation and identity. A pixel-art run needs a measurable pixel grid in the base; changing prompt wording later cannot correct its style. If no suitable base exists, generate it with the chosen image provider and establish it as the reference before motion generation. Directional anchors replace the base in later row inputs; [directional-anchor-workflow](directional-anchor-workflow.md) owns that sequence and the `anchor` resolver.
+
+## Execute
+
+1. **Prepare.** Put numeric choices in `sprite-request.json`: cell dimensions and margins, chroma key, states, frame counts, fps and fit. Choose the key against the subject's actual colors using [chroma-alpha](chroma-alpha.md). Prepare generates prompts and empty layout guides from that request; do not hand-copy frame counts elsewhere. [states-and-frames](states-and-frames.md) owns frame recommendations. Layout guides carry geometry only.
+2. **Generate rows.** Use `gen-set --provider codex` for the GPT image-sprite route. The provider that made the base is an independent choice. Attach the resolved identity reference and that state's generated layout guide. Extra motion references must be recorded in `qa-notes.md`. Independent rows use the existing batch concurrency; [gen](gen.md) owns its execution and reports.
+3. **Extract.** Run the canonical extractor for every raw row. It removes chroma, separates characters, applies the requested pixel processing and places transparent frames. Never replace this with equal-width cuts or a one-line resize for a preview. A character crossing an imaginary slot can still be extracted intact when the poses are separable. Actual missing/occluded pixels are not restored by cropping. Choose sufficient output dimensions to preserve the desired scale; [pixel-unfake](pixel-unfake.md) owns fit options.
+4. **Compose and verify.** Produce the atlas, runtime manifest and animation preview with existing compose tools. Inspect the frame manifest and output reports; reject empty frames, unwanted edge/chroma remnants and identity defects. Review motion as motion using [qa-motion](qa-motion.md). Do not hide failed motion by timing changes or silently replacing poses. A user's explicit slow preview request changes display speed, not the QA verdict.
+5. **Deliver.** Send the checked files, then follow the finish stage in the user workflow. Curation display is optional. After curation edits, exports come from the curated result, not the unedited frame cache.
+
+```bash
+$SPRITE_GEN_ROOT/.venv/bin/sprite-gen prepare --out-dir /absolute/run \
+ --character-id example --base-image /absolute/base.png --request /absolute/request.json
+$SPRITE_GEN_ROOT/.venv/bin/sprite-gen gen-set --run-dir /absolute/run --provider codex
+$SPRITE_GEN_ROOT/.venv/bin/sprite-gen extract --run-dir /absolute/run
+$SPRITE_GEN_ROOT/.venv/bin/sprite-gen compose-atlas --run-dir /absolute/run
+$SPRITE_GEN_ROOT/.venv/bin/sprite-gen compose-gif --run-dir /absolute/run --out-dir /absolute/run/previews
+$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.
diff --git a/docs/curation.md b/docs/curation.md
index 44a0a24..96a8d26 100644
--- a/docs/curation.md
+++ b/docs/curation.md
@@ -8,7 +8,7 @@
- [Isometric ground grid](#isometric-ground-grid)
- [Languages](#languages)
- [Standalone Curation View (이미지 후보 큐레이션 — 스프라이트 아님)](#standalone-curation-view-이미지-후보-큐레이션-스프라이트-아님)
-- [Curation Webview (파이프라인 스텝 3.5) — 캐릭터 검수의 정식 뷰](#curation-webview-파이프라인-스텝-35-캐릭터-검수의-정식-뷰)
+- [Curation Webview](#curation-webview)
- [Colourway (recolor) compare and pick](#colourway-recolor-compare-and-pick)
- [생성 트리거 관용구 (SSoT = `src/gen-trigger.js`)](#생성-트리거-관용구-ssot-srcgen-triggerjs)
- [Editing a finished sprite sheet (no `frames/` source)](#editing-a-finished-sprite-sheet-no-frames-source)
@@ -44,7 +44,7 @@ The webview ships with English and Korean. Pass `--lang en|ko` when launching, o
python3 sprite-gen curation --run-dir <run-dir> --lang en # or ko
```
-> `SKILL.md` 허브에서 분리한 시나리오 상세. 큐레이션뷰를 띄우거나(파이프라인 스텝 3.5 / 클로징 스텝 5), 임의 이미지 후보군을 비교·선택하거나, 완성된 시트를 다시 편집하거나, `curation.json` 스키마를 다뤄야 할 때 이 문서를 따른다.
+> 큐레이션뷰의 실행과 데이터 계약. 생성 완료 후 열기 선택과 저장된 기본값은 [user-workflow](user-workflow.md)가 소유한다.
## Standalone Curation View (이미지 후보 큐레이션 — 스프라이트 아님)
@@ -76,12 +76,12 @@ curl -s -o /dev/null -w "%{http_code}" "http://127.0.0.1:$PORT/" # 200 = posit
게임이 행 전체를 돌리는데 한 장만 보여주면 검수 대상이 왜곡된다. 아틀라스 시트 통짜·raw
멀티프레임 row 이미지·비교용 합성 시트를 그대로 붓는 것도 금지 (셀 크기 폭발 + 선택 단위 흐림).
파이프라인 산출물 검수는 이 standalone 경로가 아니라 run dir 를 직접 서빙하는 파이프라인
- 큐레이션(아래 스텝 3.5)이 우선이다.
+ 큐레이션(아래 Curation Webview)이 우선이다.
- 사용자 로컬이면 브라우저 자동 오픈이 기본, headless/원격이면 `--no-open` + URL 전달.
- 선택 회수는 `"$STAGE/run/curation.json"` 의 `selected` 인덱스를 파일명으로 역매핑. 비어 있으면 다시 묻는다 — 추측 진행 금지.
-- 결정 후 서버 kill + `$STAGE` 정리. 후보가 1장이면 큐레이션이 아니다 — 경로만 보고하고 끝.
+- 큐레이션을 열기로 선택했다면 이미지가 한 장이어도 이 뷰에서 확인할 수 있다. 필요한 편집 결과를 내보낸 뒤 이 작업이 시작한 서버를 종료하고 임시 `$STAGE`를 정리한다.
-## Curation Webview (파이프라인 스텝 3.5) — 캐릭터 검수의 정식 뷰
+## Curation Webview
**캐릭터/스프라이트 검수의 정식 뷰 = run dir 를 직접 서빙하는 이 파이프라인 뷰다** (maintainer 채택 2026-07-12).
이 뷰의 네 표시 요소(베이스 참조 줄 · 생성 재료 ref 칩 · 픽셀 격자 · 원본 화질 토글)와 그것을
@@ -272,7 +272,8 @@ The chosen layout source is always reported (`manifest` / `grid-explicit` / `aut
## Related
-- [`../SKILL.md`](../SKILL.md) — canonical behavior contract (Workflow 스텝 3.5/4.5/5)
+- [`user-workflow.md`](user-workflow.md) - request choices, optional curation and saved defaults
+- [`atlas-workflow.md`](atlas-workflow.md) - row execution and delivery
- [`architecture.md`](architecture.md) — 큐레이션 사이드카가 파이프라인에서 소비되는 위치
- [`recolor.md`](recolor.md) — palette-swap bake CLI, report schema, colourway adopt
- [`locomotion-curation.md`](locomotion-curation.md) — 수동 selected-cycle, 클린 GIF export
diff --git a/docs/run-contract.md b/docs/run-contract.md
index 5501a49..383b9fd 100644
--- a/docs/run-contract.md
+++ b/docs/run-contract.md
@@ -8,14 +8,14 @@
> generation-material chips, the pixel grid, and the original-quality toggle.
>
> Precedence (no overlap, so no contradiction):
-> - [`../SKILL.md`](../SKILL.md) owns the **behavior** contract — what the agent does, step by step.
+> - [`user-workflow.md`](user-workflow.md) owns the conversation; [`atlas-workflow.md`](atlas-workflow.md) owns row execution.
> - **This doc** owns the **structural** contract — the stage I/O table, the run-dir
> folder tree, the curation-view display payload, and the import-run source rule.
> These are the parts the scripts enforce.
> - [`architecture.md`](architecture.md) explains **how** the code realizes both; it is
> always description, never contract.
>
-> If the three ever disagree: behavior → SKILL.md wins; structure/display → this
+> If the three ever disagree: behavior → the workflow docs win; structure/display → this
> doc wins; architecture.md is the bug.
## Contents
@@ -57,8 +57,7 @@ canonical files, not hidden imports.
| Export stills | `export_curated_pngs.py` | curated `frames/` | named PNGs under `curated/` |
| Chroma guard | `scripts/dev/check_visible_magenta.py` | screenshot | leakage warning |
-The happy path is `prepare → gen → extract → (curate) → compose`, with a curation
-webview opened as the closing step. Stage internals (chroma removal, connected
+The happy path is `prepare -> gen -> extract -> compose`, followed by delivery and an optional curation view. Curation is opened only when requested or enabled in saved defaults; edits are composed again for export. Stage internals (chroma removal, connected
components, pixel-unfake path, the `.sprite-gen.lock` single-writer rule, the
inspect/score/loop split) are described in
[`architecture.md`](architecture.md) §2, §6 — this table is the contract, that doc
diff --git a/docs/user-workflow.md b/docs/user-workflow.md
new file mode 100644
index 0000000..0dee5e9
--- /dev/null
+++ b/docs/user-workflow.md
@@ -0,0 +1,69 @@
+# Image and sprite requests
+
+This document owns the conversation flow. `sprite_gen/workflow/catalog.py` owns the two journeys and their choices; `workflow` derives questions and engine steps from it. Commands in this document assume `SPRITE_GEN_ROOT` is the absolute installed repository path.
+
+## Start with the user's request
+
+| Request | Choices |
+|---|---|
+| Make sprites | Base image provider (GPT or Grok), then motion method (Grok video or GPT image rows) |
+| Make an image | Image provider (GPT or Grok) |
+
+Inspect the request before asking anything. Pass choices already named by the user as explicit arguments. An existing sprite base image skips base-image generation and its provider question. An image request may still attach references to `gen --ref` for editing.
+
+```bash
+$SPRITE_GEN_ROOT/.venv/bin/sprite-gen workflow --kind sprite
+$SPRITE_GEN_ROOT/.venv/bin/sprite-gen workflow --kind image
+```
+
+The command is read-only: it checks available credentials, reads defaults and returns JSON. `status` is `ready`, `needs-input` or `blocked`; exit 0 means ready and exit 2 means read the questions or blockers. It never generates images, launches a browser, changes authentication or saves defaults.
+
+1. Check the returned access state and explain only what needs the user's attention.
+2. Ask the missing generation choices in `questions`, using their labels rather than CLI identifiers. For sprites, explain that the first provider creates the base drawing, while the motion method animates it.
+3. Run `workflow` again with the answers. Request choices override saved values without modifying them. When choices came from saved defaults, briefly announce them and do not ask again.
+4. Gather only missing creative inputs: subject, style, requested motions and output needs. Lock the base before motion generation.
+5. Only when the start stage returns `status: ready`, run the returned pipeline through the existing tools. A populated `pipeline` is a proposal, not permission to ignore unresolved questions or blockers. Always pass its explicit provider to `gen`/`gen-set`; do not rely on the low-level CLI's omitted-provider resolution. GPT rows use `codex` even when Grok made the base. No availability-driven provider switch is allowed in this workflow.
+6. Complete the pipeline's QA and deliver the output files. Chroma removal, extraction, placement and export are automatic stages, not user choices. Raw images are evidence, not replacements for extracted sprite frames. Follow [atlas-workflow](atlas-workflow.md), [video-pipeline](video-pipeline.md) or [gen](gen.md), as returned by the guide.
+
+```bash
+$SPRITE_GEN_ROOT/.venv/bin/sprite-gen workflow --kind sprite \
+ --base-image /absolute/base.png --motion-method gpt-rows --confirmed-access codex
+```
+
+## Authentication and subscriptions
+
+Login, subscription and quota are separate facts. Codex uses `codex login status`; Grok uses the existing video's credential reader, without rewriting its auth file. Neither probe proves the current media entitlement or remaining quota: those fields remain `unknown`. When access has not independently been established for the current account and request, ask the user once and pass `--confirmed-access codex` or `--confirmed-access grok`. An explicit account/access statement already in the conversation can answer this question; never manufacture confirmation from a saved provider preference. Known failed/missing credentials remain blocked even with confirmation. A successful generation is not a permanent entitlement cache.
+
+For Grok video, the existing resolver can select `XAI_API_KEY` when configured. The guide names the separate API-credit billing and requires `--confirm-api-billing` from an explicit user choice before that route becomes ready. It never silently switches from subscription use to API credit. No keys, tokens, account IDs or subscription assertions are saved as preferences, and provider diagnostics do not echo raw credential output.
+
+The documented login commands are [Codex CLI login status](https://developers.openai.com/codex/cli/reference) and [Grok CLI login](https://docs.x.ai/build/cli/reference). These are authentication contracts, not subscription-verification endpoints. Native token parsing and video credential priority stay owned by [video](video.md).
+
+## Finish after delivering files
+
+Call the finish stage with the actual generation choices, including the existing base when one was used, and an existing result path. Finish does not repeat authentication probes or generation.
+
+```bash
+$SPRITE_GEN_ROOT/.venv/bin/sprite-gen workflow --kind image --stage finish \
+ --image-provider codex --result /absolute/output.png
+```
+
+Ask whether to open the curation view only when `curation` is not already selected or saved. Apply `open` or `skip`, then call finish again with `--curation open|skip`. Use [curation](curation.md) to open the correct result: sprite run, video-derived frames, or a standalone image candidate set. Deliver files before opening the view; skipping it is a valid completed request. If the user edits their picks, export from the updated curation state.
+
+When the profile has no saved defaults, finish then offers: "이번 선택을 다음 작업에도 기본으로 사용할까요?" Save only after an affirmative answer. Once a profile exists, ordinary one-off overrides do not prompt to replace it; changing defaults requires the user's explicit request. Creative content, prompts, paths and one-off actions are never part of defaults.
+
+## One settings owner
+
+`preferences.json` in `~/.config/sprite-gen/` owns the `sprite` and `image` profiles separately. `SPRITE_GEN_CONFIG_DIR` explicitly relocates that directory. A profile may be partial, for example saving only motion and curation when an existing base skipped image-provider selection. Missing fields prompt when needed. This storage is independent of a project or run; a run's numeric recipe and curation edits keep their existing owners.
+
+```bash
+$SPRITE_GEN_ROOT/.venv/bin/sprite-gen defaults show
+$SPRITE_GEN_ROOT/.venv/bin/sprite-gen defaults save --kind sprite \
+ --image-provider codex --motion-method grok-video --curation open \
+ --expected-revision REVISION_FROM_SHOW
+$SPRITE_GEN_ROOT/.venv/bin/sprite-gen defaults clear --kind image \
+ --expected-revision REVISION_FROM_SHOW
+```
+
+Use the exact `settings_revision` from the guide, or `revision` from show (`missing` for no file). Save merges only supplied fields in the selected profile; clear removes only that profile. Both are explicit mutations. Reads never create or rewrite settings. Corrupt or unknown settings fail with a named error instead of resetting silently.
+
+Writes use the package's cross-platform exclusive file lock, compare the observed revision under that lock, then atomically replace the complete JSON file. Two writers with the same revision cannot overwrite each other: the first committed write wins; the second fails and must reread/reconfirm. A repeated save with the current revision and identical values leaves bytes and mtime unchanged. Atomic replacement lets read-only queries see a complete old or new snapshot without creating a lock file.
diff --git a/pyproject.toml b/pyproject.toml
index 7f8e4c7..5338c9c 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.0.3"
+version = "2.1.0"
description = "Component-row pipeline for clean 2D game sprites and animation atlases"
readme = "README.md"
license = "Apache-2.0"
diff --git a/scripts/dev/README.md b/scripts/dev/README.md
index 9fb96ba..ff8e155 100644
--- a/scripts/dev/README.md
+++ b/scripts/dev/README.md
@@ -7,7 +7,6 @@ measurement or a proof that fed a rule now living in the package or its docs:
|---|---|
| `breathe_mutation_battery.py` | plants each breathe-contract mutation in the source and checks the tests bite (exit 0 = every net bites) |
| `measure_align_sigma.py` | per-frame horizontal jitter σ of `fit.align_x` variants on a source run's raw strips |
-| `validate_pr6_subject_profile.py` | same-raw A/B proof for the subject-specific sparse floor (PR #6) |
| `check_visible_magenta.py` | chroma-leak guard for screenshots (`sprite_gen.frames.check_visible_magenta`) |
Run them with the project interpreter (`.venv/bin/python scripts/dev/<name>.py`).
diff --git a/scripts/dev/validate_pr6_subject_profile.py b/scripts/dev/validate_pr6_subject_profile.py
deleted file mode 100644
index 599139b..0000000
--- a/scripts/dev/validate_pr6_subject_profile.py
+++ /dev/null
@@ -1,210 +0,0 @@
-#!/usr/bin/env python3
-"""Build a same-raw A/B proof for PR #6's subject-specific sparse floor."""
-
-from __future__ import annotations
-
-import argparse
-import hashlib
-import json
-import shutil
-import subprocess
-import sys
-from pathlib import Path
-
-from PIL import Image, ImageDraw, ImageFont
-
-
-ROOT = Path(__file__).resolve().parents[2]
-PYTHON = Path(sys.executable)
-EXTRACT = ROOT / "scripts" / "extract_sprite_row_frames.py"
-COMPOSE = ROOT / "scripts" / "compose_sprite_atlas.py"
-MAGENTA = (255, 0, 255)
-
-
-def _sha256(path: Path) -> str:
- return hashlib.sha256(path.read_bytes()).hexdigest()
-
-
-def _request(subject: str | None) -> dict[str, object]:
- doc: dict[str, object] = {
- "version": 1,
- "kind": "sprite-gen-request",
- "engine": "component-row",
- "character": {"id": "pr6-proof", "description": "small spell shards", "base_image": None},
- "cell": {
- "shape": "square",
- "width": 64,
- "height": 64,
- "size": 64,
- "safe_margin_x": 6,
- "safe_margin_y": 6,
- "safe_margin": 6,
- },
- "chroma_key": {"name": "magenta", "hex": "#FF00FF", "rgb": [255, 0, 255], "selection": "explicit"},
- "states": {"burst": {"frames": 3, "fps": 6, "loop": True}},
- "style": "same raw A/B proof",
- "layout": "taxonomy/v1",
- }
- if subject is not None:
- doc["subject"] = subject
- return doc
-
-
-def _make_raw(path: Path, *, debris: bool) -> None:
- strip = Image.new("RGB", (64 * 3, 64), MAGENTA)
- draw = ImageDraw.Draw(strip)
- if debris:
- for frame in range(3):
- x = frame * 64 + 30
- draw.rectangle((x, 30, x + 3, 33), fill=(88, 226, 255))
- else:
- colors = ((94, 228, 255), (135, 112, 255), (73, 255, 187))
- for frame, color in enumerate(colors):
- ox = frame * 64
- draw.rectangle((ox + 29, 29, ox + 34, 34), fill=color)
- path.parent.mkdir(parents=True, exist_ok=True)
- strip.save(path)
-
-
-def _run_case(root: Path, name: str, raw: Path, subject: str | None) -> dict[str, object]:
- run_dir = root / name
- (run_dir / "raw").mkdir(parents=True, exist_ok=True)
- (run_dir / "sprite-request.json").write_text(
- json.dumps(_request(subject), indent=2) + "\n", encoding="utf-8"
- )
- shutil.copy2(raw, run_dir / "raw" / "burst.png")
- extract = subprocess.run(
- [str(PYTHON), str(EXTRACT), "--run-dir", str(run_dir)],
- text=True,
- capture_output=True,
- check=False,
- )
- manifest_path = run_dir / "frames" / "frames-manifest.json"
- failure_path = run_dir / "extract-failure.json"
- result_path = manifest_path if manifest_path.is_file() else failure_path
- result = json.loads(result_path.read_text(encoding="utf-8"))
- records = []
- for row in result.get("rows", []):
- records.extend(row.get("frame_records", []))
- if not records:
- for state in result.get("states", {}).values():
- records.extend(state.get("frame_records", []))
- counts = [int(record["nontransparent_pixels"]) for record in records]
- compose_rc = None
- if extract.returncode == 0:
- compose = subprocess.run(
- [str(PYTHON), str(COMPOSE), "--run-dir", str(run_dir)],
- text=True,
- capture_output=True,
- check=False,
- )
- compose_rc = compose.returncode
- return {
- "name": name,
- "subject": subject or "character (field absent)",
- "raw_sha256": _sha256(run_dir / "raw" / "burst.png"),
- "extract_rc": extract.returncode,
- "compose_rc": compose_rc,
- "ok": bool(result.get("ok")),
- "opaque_pixels": counts,
- "errors": result.get("errors", []),
- "run_dir": str(run_dir),
- }
-
-
-def _font(size: int) -> ImageFont.ImageFont:
- candidates = (
- "/System/Library/Fonts/AppleSDGothicNeo.ttc",
- "/System/Library/Fonts/Supplemental/Arial.ttf",
- )
- for candidate in candidates:
- if Path(candidate).is_file():
- return ImageFont.truetype(candidate, size)
- return ImageFont.load_default()
-
-
-def _panel(raw: Image.Image, title: str, verdict: str, details: list[str], color: tuple[int, int, int]) -> Image.Image:
- panel = Image.new("RGB", (640, 420), (250, 250, 248))
- draw = ImageDraw.Draw(panel)
- draw.rounded_rectangle((20, 20, 620, 400), radius=18, fill=(255, 255, 255), outline=(215, 217, 220), width=2)
- draw.text((46, 44), title, font=_font(25), fill=(28, 31, 36))
- draw.rounded_rectangle((46, 88, 594, 150), radius=12, fill=tuple(min(255, c + 205) for c in color), outline=color, width=2)
- draw.text((66, 103), verdict, font=_font(22), fill=color)
- preview = raw.resize((384, 128), Image.Resampling.NEAREST)
- panel.paste(preview, (128, 174))
- for index, line in enumerate(details):
- draw.text((46, 318 + index * 27), line, font=_font(17), fill=(70, 74, 82))
- return panel
-
-
-def _render_compare(out: Path, raw: Path, character: dict[str, object], effect: dict[str, object], debris: dict[str, object]) -> None:
- canvas = Image.new("RGB", (1320, 1030), (244, 245, 247))
- draw = ImageDraw.Draw(canvas)
- draw.text((42, 34), "PR #6 same-raw A/B: subject profile changes validation, not the artwork", font=_font(31), fill=(25, 28, 33))
- draw.text((42, 80), "Both upper panels use byte-identical raw/burst.png. Only sprite-request.json subject differs.", font=_font(20), fill=(83, 88, 98))
- raw_img = Image.open(raw).convert("RGB")
- left = _panel(
- raw_img,
- "Resolution formula: character floor = 64 px/frame",
- "REJECTED as too sparse",
- [f"opaque pixels: {character['opaque_pixels']}", "raw sha256: identical"],
- (165, 47, 47),
- )
- right = _panel(
- raw_img,
- "Resolution formula: effect floor = 32 px/frame",
- "ACCEPTED and atlas composed",
- [f"opaque pixels: {effect['opaque_pixels']}", "raw sha256: identical"],
- (35, 122, 72),
- )
- canvas.paste(left, (20, 120))
- canvas.paste(right, (660, 120))
- debris_img = Image.open(Path(debris["run_dir"]) / "raw" / "burst.png").convert("RGB")
- guard = _panel(
- debris_img,
- "Debris control: effect profile still keeps the guard",
- "REJECTED below 32 px/frame",
- [f"opaque pixels: {debris['opaque_pixels']}", "the guard is scoped, not disabled"],
- (151, 96, 24),
- )
- canvas.paste(guard, (340, 560))
- draw.text((42, 997), "Conclusion: #6 rescues legitimate small effects during extract/compose. It does not improve image-generation beauty or change curation UI.", font=_font(18), fill=(45, 49, 56))
- out.parent.mkdir(parents=True, exist_ok=True)
- canvas.save(out)
-
-
-def main() -> int:
- parser = argparse.ArgumentParser(description=__doc__)
- parser.add_argument("--out-dir", required=True, type=Path)
- args = parser.parse_args()
- out_dir = args.out_dir.expanduser().resolve()
- if out_dir.exists():
- shutil.rmtree(out_dir)
- out_dir.mkdir(parents=True)
- legitimate = out_dir / "inputs" / "legitimate-small-effect.png"
- debris_raw = out_dir / "inputs" / "debris-control.png"
- _make_raw(legitimate, debris=False)
- _make_raw(debris_raw, debris=True)
- runs = out_dir / "runs"
- character = _run_case(runs, "character", legitimate, None)
- effect = _run_case(runs, "effect", legitimate, "effect")
- debris = _run_case(runs, "effect-debris", debris_raw, "effect")
- report = {"character": character, "effect": effect, "effect_debris": debris}
- same_raw = character["raw_sha256"] == effect["raw_sha256"]
- report["assertions"] = {
- "same_raw_sha256": same_raw,
- "character_rejects": character["extract_rc"] != 0,
- "effect_accepts": effect["extract_rc"] == 0 and effect["compose_rc"] == 0,
- "effect_still_rejects_debris": debris["extract_rc"] != 0,
- }
- if not all(report["assertions"].values()):
- print(json.dumps(report, indent=2), file=sys.stderr)
- return 1
- (out_dir / "pr6-validation-report.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
- _render_compare(out_dir / "pr6-subject-profile-ab.png", legitimate, character, effect, debris)
- print(out_dir / "pr6-subject-profile-ab.png")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/sprite_gen/_modules.py b/sprite_gen/_modules.py
index 06edf3c..23b633c 100644
--- a/sprite_gen/_modules.py
+++ b/sprite_gen/_modules.py
@@ -6,6 +6,8 @@ the reorg tooling. Keep in sync with the physical folder layout.
"""
MODULE_DOMAIN = {
+ 'guide': 'workflow',
+ 'preferences': 'workflow',
'runio': 'spec',
'layout': 'spec',
'migrate_request': 'spec',
@@ -53,6 +55,7 @@ MODULE_DOMAIN = {
# tested against the file set). Adding a module to MODULE_DOMAIN puts it in its group;
# nothing else needs a hand edit.
DOMAINS: list[tuple[str, str]] = [
+ ("workflow", "Start here — image or sprite choices, access checks, saved defaults"),
("gen", "Generation — prepare a run, generate stills / rows / clips"),
("video", "Video → loop — canvas, keyed frames, seamless cycle, batch"),
("frames", "Frames — chroma/white removal, row extraction, sheet slicing, atlas unpacking"),
@@ -71,8 +74,8 @@ DOMAIN_TITLE = dict(DOMAINS)
# The four pipelines — first-class objects. The CLI help, the docs index and the README
# pipeline table are checked against THIS list; a verb named here must exist as a verb.
PIPELINES: list[dict[str, object]] = [
- {"key": "A", "name": "atlas rows", "verbs": ["prepare", "gen", "gen-set", "extract", "curation", "compose-atlas"],
- "chain": "prepare → gen (or gen-set) → extract → curation → compose-atlas", "doc": "docs/run-contract.md"},
+ {"key": "A", "name": "atlas rows", "verbs": ["prepare", "gen", "gen-set", "extract", "compose-atlas", "curation"],
+ "chain": "prepare → gen (or gen-set) → extract → compose-atlas; optional curation and recompose", "doc": "docs/run-contract.md"},
{"key": "B", "name": "video → loop", "verbs": ["video-canvas", "video", "video-frames", "video-loop", "video-set"],
"chain": "video-canvas → video → video-frames → video-loop, or video-set", "doc": "docs/video-pipeline.md"},
{"key": "C", "name": "utilities", "verbs": ["cutout", "slice-sheet", "unpack-atlas"],
diff --git a/sprite_gen/cli.py b/sprite_gen/cli.py
index 2d0fae3..dccf91c 100644
--- a/sprite_gen/cli.py
+++ b/sprite_gen/cli.py
@@ -22,6 +22,7 @@ from sprite_gen.serve import serve_compose, serve_curation
from sprite_gen.spec import migrate_breathe, migrate_request
from sprite_gen.gen.prepare import STYLE_DEFAULT, _outline_config
from sprite_gen.spec.subject import SUBJECTS
+from sprite_gen.workflow import guide, preferences
def _parse_frames(value: str) -> list[int]:
@@ -227,6 +228,8 @@ def _add_correction_loop(p: argparse.ArgumentParser) -> None:
COMMANDS: dict[str, tuple[str, Callable[[argparse.ArgumentParser], None], Callable[..., int]]] = {
+ "workflow": ("Resolve image/sprite choices, check access and guide the next conversation step.", guide.add_arguments, guide.run),
+ "defaults": ("Show, explicitly save or clear the defaults for each user workflow.", preferences.add_arguments, preferences.run),
"prepare": ("Prepare a sprite-gen component-row run.", _add_prepare, prepare.run),
"extract": ("Extract component-row sprite strips into clean RGBA frames.", _add_extract, extract.run),
"compose-atlas": (
diff --git a/sprite_gen/workflow/__init__.py b/sprite_gen/workflow/__init__.py
new file mode 100644
index 0000000..8345247
--- /dev/null
+++ b/sprite_gen/workflow/__init__.py
@@ -0,0 +1,2 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Conversation choices and saved defaults; generation stays in its own domains."""
diff --git a/sprite_gen/workflow/access.py b/sprite_gen/workflow/access.py
new file mode 100644
index 0000000..4e4978f
--- /dev/null
+++ b/sprite_gen/workflow/access.py
@@ -0,0 +1,43 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Credential readiness is not proof of a paid subscription or remaining quota."""
+from __future__ import annotations
+
+import shutil
+import subprocess
+
+from sprite_gen.gen.base import provider_binary, provider_subprocess_env
+from sprite_gen.gen.video import AUTH_SOURCE_API_KEY, resolve_credential
+
+
+def probe_access(provider: str, *, video: bool = False) -> dict:
+ result = {"provider": provider, "login": "unknown", "subscription": "unknown", "quota": "unknown",
+ "billing": "subscription", "reason": "Subscription and media access need user confirmation when not independently known."}
+ if provider == "codex":
+ if shutil.which("codex") is None:
+ return {**result, "login": "unavailable", "reason": "codex CLI is not installed"}
+ try:
+ check = subprocess.run([provider_binary("codex"), "login", "status"], capture_output=True,
+ text=True, encoding="utf-8", errors="replace", timeout=15, env=provider_subprocess_env())
+ except (OSError, subprocess.SubprocessError):
+ return {**result, "reason": "codex login status could not be checked"}
+ if check.returncode != 0:
+ return {**result, "login": "unavailable", "reason": "codex login status failed; sign in and check again"}
+ # Never publish the CLI's raw output: some authentication modes can name keys.
+ output = (check.stdout + check.stderr).lower()
+ if "chatgpt" not in output:
+ return {**result, "reason": "login succeeded but ChatGPT subscription authentication was not identified"}
+ return {**result, "login": "ready"}
+ if provider != "grok":
+ raise ValueError(f"unknown provider: {provider}")
+ if not video and shutil.which("grok") is None:
+ return {**result, "login": "unavailable", "reason": "grok CLI is not installed"}
+ try:
+ # Image generation uses CLI login. Video may instead use the configured
+ # API key; the existing video resolver alone owns that precedence.
+ credential = resolve_credential(env=None if video else {})
+ except (SystemExit, OSError, ValueError):
+ return {**result, "login": "unavailable", "reason": "grok credential missing, expired or unreadable; check grok login"}
+ if credential.source == AUTH_SOURCE_API_KEY:
+ return {**result, "login": "ready", "billing": "api-credit",
+ "reason": "Video will use XAI_API_KEY and separate API credit; confirm this billing choice."}
+ return {**result, "login": "ready"}
diff --git a/sprite_gen/workflow/catalog.py b/sprite_gen/workflow/catalog.py
new file mode 100644
index 0000000..c54ea11
--- /dev/null
+++ b/sprite_gen/workflow/catalog.py
@@ -0,0 +1,33 @@
+# SPDX-License-Identifier: Apache-2.0
+"""The two user journeys and their selectable fields, declared once."""
+from sprite_gen.gen import PROVIDERS
+
+MOTION_METHODS = {
+ "gpt-rows": {"label": "지피티 이미지 스프라이트", "provider": "codex", "doc": "docs/atlas-workflow.md",
+ "steps": ["prepare", "gen-set", "extract", "compose-atlas", "compose-gif"]},
+ "grok-video": {"label": "그록 영상", "provider": "grok", "doc": "docs/video-pipeline.md",
+ "steps": ["video-set"]},
+}
+FIELDS = {
+ "image_provider": {"options": dict(zip(PROVIDERS, ("지피티", "그록"))),
+ "question": "이미지를 지피티로 만들까요, 그록으로 만들까요?"},
+ "motion_method": {"options": {k: v["label"] for k, v in MOTION_METHODS.items()},
+ "question": "동작을 그록 영상으로 만들까요, 지피티 이미지 스프라이트로 만들까요?"},
+ "curation": {"options": {"open": "열기", "skip": "열지 않기"},
+ "question": "큐레이션뷰에서 결과를 확인하고 골라볼까요?"},
+}
+FLOWS = {
+ "sprite": {"label": "스프라이트 만들기", "fields": ("image_provider", "motion_method", "curation")},
+ "image": {"label": "이미지 만들기", "fields": ("image_provider", "curation")},
+}
+
+
+def validate_choices(kind: str, choices: dict) -> dict:
+ if kind not in FLOWS:
+ raise ValueError(f"unknown workflow: {kind}")
+ if not isinstance(choices, dict):
+ raise ValueError("workflow choices must be an object")
+ for key, value in choices.items():
+ if key not in FLOWS[kind]["fields"] or not isinstance(value, str) or value not in FIELDS[key]["options"]:
+ raise ValueError(f"invalid {kind} choice: {key}")
+ return dict(choices)
diff --git a/sprite_gen/workflow/guide.py b/sprite_gen/workflow/guide.py
new file mode 100644
index 0000000..205a2da
--- /dev/null
+++ b/sprite_gen/workflow/guide.py
@@ -0,0 +1,103 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Read-only conversation guide. It never generates, opens a view or saves choices."""
+from __future__ import annotations
+
+import argparse
+import json
+from pathlib import Path
+
+from .access import probe_access
+from .catalog import FIELDS, FLOWS, MOTION_METHODS, validate_choices
+from .preferences import read_settings
+
+
+def guide(kind: str, *, stage: str = "start", base_image: Path | None = None, result: Path | None = None,
+ choices: dict | None = None, confirmed_access: tuple[str, ...] = (), confirm_api_billing: bool = False) -> dict:
+ explicit = validate_choices(kind, choices or {})
+ if stage not in ("start", "finish"):
+ raise ValueError("stage must be start or finish")
+ if base_image is not None and (kind != "sprite" or not Path(base_image).is_file()):
+ raise ValueError("--base-image must name an existing sprite reference image")
+ if stage == "finish" and (result is None or not Path(result).exists()):
+ raise ValueError("finish requires an existing --result file or run directory, after generation and QA")
+ snapshot = read_settings()
+ stored = snapshot["profiles"].get(kind, {})
+ selected = {**stored, **explicit}
+ sources = {key: "request" if key in explicit else "saved" for key in selected}
+ active_fields = [key for key in FLOWS[kind]["fields"] if key != "curation"]
+ if base_image is not None:
+ active_fields.remove("image_provider")
+ questions, blocked, access = [], [], []
+ if stage == "start":
+ for field in active_fields:
+ if field not in selected:
+ questions.append({"field": field, **FIELDS[field]})
+ # Report both candidates while choosing, then only the services actually
+ # used. One probe per provider/auth route; a row run always pins codex.
+ required = set()
+ if "image_provider" in active_fields and selected.get("image_provider"):
+ required.add((selected["image_provider"], False))
+ motion = MOTION_METHODS.get(selected.get("motion_method", ""))
+ if motion:
+ required.add((motion["provider"], selected["motion_method"] == "grok-video"))
+ candidates = required or {(provider, False) for provider in FIELDS["image_provider"]["options"]}
+ for provider, is_video in sorted(candidates):
+ state = probe_access(provider, video=is_video)
+ access.append(state)
+ if (provider, is_video) not in required:
+ continue
+ if state["login"] == "unavailable":
+ blocked.append({"provider": provider, "reason": state["reason"]})
+ elif state["billing"] == "api-credit":
+ if not confirm_api_billing:
+ questions.append({"field": "confirm_api_billing", "question": "그록 영상에 별도 API 크레딧을 사용할까요?", "options": {"yes": "사용", "no": "구독 로그인으로 변경"}})
+ elif provider not in confirmed_access and not any(q["field"] == f"access_{provider}" for q in questions):
+ questions.append({"field": f"access_{provider}", "question": f"{FIELDS['image_provider']['options'][provider]} 계정의 구독과 이미지/영상 이용 가능 여부를 확인해 주세요.",
+ "options": {"yes": "사용 가능", "no": "사용 불가"}})
+ else:
+ missing = [field for field in active_fields if field not in selected]
+ if missing:
+ raise ValueError("finish requires the actual generation choices: " + ", ".join(missing))
+ if "curation" not in selected:
+ questions.append({"field": "curation", **FIELDS["curation"]})
+ elif not stored:
+ questions.append({"field": "save_defaults", "question": "이번 선택을 다음 작업에도 기본으로 사용할까요?",
+ "options": {"yes": "기본 설정으로 저장", "no": "이번에만 사용"}})
+ pipeline = None
+ if not any(field not in selected for field in active_fields):
+ motion = MOTION_METHODS.get(selected.get("motion_method", ""))
+ pipeline = {"base_image": str(base_image) if base_image else None,
+ "image_provider": selected.get("image_provider") if "image_provider" in active_fields else None,
+ "generation_provider": motion["provider"] if motion else selected.get("image_provider"),
+ "steps": motion["steps"] if motion else ["gen"],
+ "doc": motion["doc"] if motion else "docs/gen.md"}
+ labels = [FIELDS[key]["options"][selected[key]] for key in active_fields if key in selected]
+ return {"kind": kind, "stage": stage, "status": "blocked" if blocked else "needs-input" if questions else "ready",
+ "notice": " / ".join(labels), "selected": selected, "sources": sources,
+ "settings_revision": snapshot["revision"], "settings_path": snapshot["path"],
+ "access": access, "blocked": blocked, "questions": questions, "pipeline": pipeline,
+ "curation": selected.get("curation", "ask") if stage == "finish" else "after-result",
+ "save_candidate": selected if stage == "finish" and "curation" in selected else None}
+
+
+def add_arguments(parser: argparse.ArgumentParser) -> None:
+ parser.add_argument("--kind", required=True, choices=FLOWS)
+ parser.add_argument("--stage", choices=("start", "finish"), default="start")
+ parser.add_argument("--base-image", type=Path)
+ parser.add_argument("--result", type=Path)
+ parser.add_argument("--confirmed-access", action="append", choices=FIELDS["image_provider"]["options"], default=[])
+ parser.add_argument("--confirm-api-billing", action="store_true")
+ for key, field in FIELDS.items():
+ parser.add_argument("--" + key.replace("_", "-"), choices=field["options"])
+
+
+def run(**kwargs) -> int:
+ choices = {key: kwargs.pop(key) for key in FIELDS if kwargs.get(key) is not None}
+ for key in FIELDS:
+ kwargs.pop(key, None)
+ try:
+ result = guide(choices=choices, **kwargs)
+ except (ValueError, OSError) as exc:
+ raise SystemExit(f"workflow: {exc}") from exc
+ print(json.dumps(result, ensure_ascii=False, indent=2))
+ return 0 if result["status"] == "ready" else 2
diff --git a/sprite_gen/workflow/preferences.py b/sprite_gen/workflow/preferences.py
new file mode 100644
index 0000000..e5767d1
--- /dev/null
+++ b/sprite_gen/workflow/preferences.py
@@ -0,0 +1,91 @@
+# SPDX-License-Identifier: Apache-2.0
+"""One preferences file; read-only queries, atomic compare-and-swap writes."""
+from __future__ import annotations
+
+import argparse
+import hashlib
+import json
+import os
+from pathlib import Path
+
+from sprite_gen.spec.runio import atomic_write_text, publish_guard
+from .catalog import FIELDS, FLOWS, validate_choices
+
+
+def settings_path() -> Path:
+ configured = os.environ.get("SPRITE_GEN_CONFIG_DIR")
+ if configured is not None and not configured.strip():
+ raise ValueError("SPRITE_GEN_CONFIG_DIR is empty")
+ root = Path(configured).expanduser() if configured is not None else Path.home() / ".config" / "sprite-gen"
+ return root / "preferences.json"
+
+
+def read_settings() -> dict:
+ path = settings_path()
+ try:
+ raw = path.read_bytes()
+ except FileNotFoundError:
+ return {"path": str(path), "revision": "missing", "profiles": {}}
+ try:
+ data = json.loads(raw)
+ if not isinstance(data, dict) or set(data) != {"version", "profiles"} or type(data["version"]) is not int or data["version"] != 1:
+ raise ValueError("expected preferences version 1")
+ if not isinstance(data["profiles"], dict):
+ raise ValueError("profiles must be an object")
+ for kind, choices in data["profiles"].items():
+ validate_choices(kind, choices)
+ except (ValueError, TypeError) as exc:
+ raise ValueError(f"invalid preferences at {path}: {exc}; repair or explicitly remove the file") from exc
+ return {"path": str(path), "revision": hashlib.sha256(raw).hexdigest(), "profiles": data["profiles"]}
+
+
+def save_settings(kind: str, choices: dict, *, expected_revision: str, clear: bool = False) -> dict:
+ """Only explicit user-approved calls write. First matching revision wins a race."""
+ choices = validate_choices(kind, choices)
+ if not expected_revision:
+ raise ValueError("expected_revision is required; read current settings first")
+ if not clear and not choices:
+ raise ValueError("provide at least one default to save")
+ path = settings_path()
+ path.parent.mkdir(parents=True, exist_ok=True)
+ # Reuse the package's cross-platform lock backend. The stable sidecar is for
+ # this file (not the replaceable JSON inode); atomic replace keeps reads pure.
+ with publish_guard(path):
+ before = read_settings()
+ if before["revision"] != expected_revision:
+ raise ValueError("preferences changed since they were read; read again and reconfirm the intended change")
+ profiles = before["profiles"]
+ if clear:
+ profiles.pop(kind, None)
+ else:
+ profiles[kind] = {**profiles.get(kind, {}), **choices}
+ payload = json.dumps({"version": 1, "profiles": profiles}, ensure_ascii=False, sort_keys=True, indent=2) + "\n"
+ if not path.exists() or path.read_text(encoding="utf-8") != payload:
+ atomic_write_text(path, payload)
+ return read_settings()
+
+
+def add_arguments(parser: argparse.ArgumentParser) -> None:
+ parser.add_argument("action", choices=("show", "save", "clear"))
+ parser.add_argument("--kind", choices=FLOWS)
+ parser.add_argument("--expected-revision")
+ for key, field in FIELDS.items():
+ parser.add_argument("--" + key.replace("_", "-"), choices=field["options"])
+
+
+def run(**kwargs) -> int:
+ args = argparse.Namespace(**kwargs)
+ choices = {key: getattr(args, key, None) for key in FIELDS if getattr(args, key, None) is not None}
+ try:
+ if args.action == "show":
+ if choices or args.kind or args.expected_revision:
+ raise ValueError("show accepts no mutation arguments")
+ result = read_settings()
+ else:
+ if args.action == "clear" and choices:
+ raise ValueError("clear does not accept choices")
+ result = save_settings(args.kind, choices, expected_revision=args.expected_revision, clear=args.action == "clear")
+ except (ValueError, OSError) as exc:
+ raise SystemExit(f"defaults: {exc}") from exc
+ print(json.dumps(result, ensure_ascii=False, indent=2))
+ return 0
diff --git a/tests/effects/test_recolor_docs.py b/tests/effects/test_recolor_docs.py
index a501922..311df33 100644
--- a/tests/effects/test_recolor_docs.py
+++ b/tests/effects/test_recolor_docs.py
@@ -65,8 +65,6 @@ def test_skill_hub_routes_recolor_triggers_and_points_at_leaf() -> None:
assert "docs/recolor.md" in text
assert "sprite-gen recolor" in text
assert "recolor-palette" in text
- # Workflow step after compose.
- assert "4.5" in text
# Docs topology branch.
assert "COLOURWAYS" in text or "docs/recolor.md" in text
# Wrapper listed among required scripts.
diff --git a/tests/workflow/test_workflow.py b/tests/workflow/test_workflow.py
new file mode 100644
index 0000000..ac0cbc9
--- /dev/null
+++ b/tests/workflow/test_workflow.py
@@ -0,0 +1,225 @@
+# SPDX-License-Identifier: Apache-2.0
+"""User journeys, persisted defaults, access uncertainty and real CLI contracts."""
+import json
+import multiprocessing
+import os
+import subprocess
+import sys
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+from sprite_gen.workflow import access, guide, preferences
+from sprite_gen.workflow.catalog import FIELDS, FLOWS, MOTION_METHODS
+from sprite_gen.gen.video import AUTH_SOURCE_API_KEY
+
+
[email protected](autouse=True)
+def isolated_settings(tmp_path, monkeypatch):
+ monkeypatch.setenv("SPRITE_GEN_CONFIG_DIR", str(tmp_path / "settings"))
+
+
+def ready_login(monkeypatch):
+ seen = []
+ def probe(provider, *, video=False):
+ seen.append((provider, video))
+ return {"provider": provider, "login": "ready", "subscription": "unknown", "quota": "unknown",
+ "billing": "subscription", "reason": "unverified media access"}
+ monkeypatch.setattr(guide, "probe_access", probe)
+ return seen
+
+
+def test_reads_and_request_overrides_never_write(tmp_path, ready_login):
+ assert preferences.read_settings()["revision"] == "missing"
+ assert not preferences.settings_path().parent.exists()
+ saved = preferences.save_settings("image", {"image_provider": "codex", "curation": "skip"}, expected_revision="missing")
+ path = preferences.settings_path()
+ original, mtime = path.read_bytes(), path.stat().st_mtime_ns
+ for _ in range(2):
+ view = guide.guide("image", choices={"image_provider": "grok"}, confirmed_access=("grok",))
+ assert view["status"] == "ready"
+ assert view["selected"] == {"image_provider": "grok", "curation": "skip"}
+ assert view["sources"] == {"image_provider": "request", "curation": "saved"}
+ assert path.read_bytes() == original and path.stat().st_mtime_ns == mtime
+ again = preferences.save_settings("image", saved["profiles"]["image"], expected_revision=saved["revision"])
+ assert again == saved and path.stat().st_mtime_ns == mtime
+
+
+def test_profiles_merge_and_clear_without_erasing_other_kind():
+ first = preferences.save_settings("image", {"image_provider": "grok"}, expected_revision="missing")
+ second = preferences.save_settings("sprite", {"motion_method": "gpt-rows"}, expected_revision=first["revision"])
+ third = preferences.save_settings("image", {"curation": "open"}, expected_revision=second["revision"])
+ assert third["profiles"]["image"] == {"image_provider": "grok", "curation": "open"}
+ cleared = preferences.save_settings("sprite", {}, expected_revision=third["revision"], clear=True)
+ assert cleared["profiles"] == {"image": third["profiles"]["image"]}
+
+
[email protected]("raw", [b"bad json", b'[]', b'{"version":2,"profiles":{}}',
+ b'{"version":1,"profiles":{"image":{"motion_method":"gpt-rows"}}}',
+ b'{"version":1,"profiles":{"image":{"image_provider":true}}}'])
+def test_corrupt_settings_fail_without_reset(raw):
+ path = preferences.settings_path()
+ path.parent.mkdir()
+ path.write_bytes(raw)
+ with pytest.raises(ValueError, match="invalid preferences"):
+ preferences.read_settings()
+ with pytest.raises(ValueError):
+ preferences.save_settings("image", {"curation": "open"}, expected_revision="missing")
+ assert path.read_bytes() == raw
+
+
+def _race_writer(root, kind, revision, event, queue):
+ os.environ["SPRITE_GEN_CONFIG_DIR"] = root
+ event.wait(10)
+ try:
+ preferences.save_settings(kind, {"curation": "skip"}, expected_revision=revision)
+ queue.put((kind, "saved"))
+ except ValueError:
+ queue.put((kind, "conflict"))
+
+
+def test_two_processes_cannot_overwrite_same_snapshot():
+ ctx = multiprocessing.get_context("spawn")
+ event, queue = ctx.Event(), ctx.Queue()
+ workers = [ctx.Process(target=_race_writer, args=(str(preferences.settings_path().parent), kind, "missing", event, queue)) for kind in FLOWS]
+ for worker in workers:
+ worker.start()
+ event.set()
+ results = [queue.get(timeout=15) for _ in workers]
+ for worker in workers:
+ worker.join(15)
+ assert worker.exitcode == 0
+ assert sorted(status for _, status in results) == ["conflict", "saved"]
+ winner = next(kind for kind, status in results if status == "saved")
+ assert preferences.read_settings()["profiles"] == {winner: {"curation": "skip"}}
+
+
+def test_first_sprite_request_and_existing_base(ready_login, tmp_path):
+ view = guide.guide("sprite")
+ assert [q["field"] for q in view["questions"]] == ["image_provider", "motion_method"]
+ assert view["pipeline"] is None
+ base = tmp_path / "base.png"
+ base.write_bytes(b"reference fixture")
+ ready_login.clear()
+ view = guide.guide("sprite", base_image=base, choices={"motion_method": "gpt-rows"}, confirmed_access=("codex",))
+ assert view["status"] == "ready" and view["pipeline"]["image_provider"] is None
+ assert ready_login == [("codex", False)]
+ assert "extract" in view["pipeline"]["steps"]
+
+
[email protected]("base_provider", ["codex", "grok"])
[email protected]("method", MOTION_METHODS)
+def test_every_sprite_combination_keeps_base_and_motion_distinct(ready_login, base_provider, method):
+ view = guide.guide("sprite", choices={"image_provider": base_provider, "motion_method": method}, confirmed_access=("codex", "grok"))
+ assert view["status"] == "ready"
+ assert view["pipeline"]["image_provider"] == base_provider
+ assert view["pipeline"]["generation_provider"] == MOTION_METHODS[method]["provider"]
+ assert view["pipeline"]["steps"] == MOTION_METHODS[method]["steps"]
+
+
+def test_unknown_subscription_is_not_inferred_from_login_or_defaults(ready_login):
+ preferences.save_settings("image", {"image_provider": "codex"}, expected_revision="missing")
+ view = guide.guide("image")
+ assert view["access"][0]["subscription"] == "unknown"
+ assert [q["field"] for q in view["questions"]] == ["access_codex"]
+ assert view["status"] == "needs-input"
+
+
+def test_failed_provider_stays_blocked_even_with_confirmation(monkeypatch):
+ monkeypatch.setattr(guide, "probe_access", lambda provider, **kw: {"provider": provider, "login": "unavailable", "billing": "subscription", "reason": "expired"})
+ view = guide.guide("image", choices={"image_provider": "codex"}, confirmed_access=("codex",))
+ assert view["status"] == "blocked"
+ assert view["selected"]["image_provider"] == "codex"
+
+
+def test_finish_offers_curation_then_save_but_never_writes_or_probes(tmp_path, monkeypatch):
+ monkeypatch.setattr(guide, "probe_access", lambda *a, **k: pytest.fail("finish must not probe"))
+ output = tmp_path / "output.png"
+ output.touch()
+ view = guide.guide("image", stage="finish", result=output, choices={"image_provider": "grok"})
+ assert [q["field"] for q in view["questions"]] == ["curation"]
+ view = guide.guide("image", stage="finish", result=output, choices={"image_provider": "grok", "curation": "skip"})
+ assert [q["field"] for q in view["questions"]] == ["save_defaults"]
+ assert preferences.read_settings()["revision"] == "missing"
+ preferences.save_settings("image", view["save_candidate"], expected_revision=view["settings_revision"])
+ view = guide.guide("image", stage="finish", result=output, choices={"image_provider": "codex"})
+ assert view["questions"] == [] and view["curation"] == "skip"
+ assert preferences.read_settings()["profiles"]["image"]["image_provider"] == "grok"
+
+
+def test_finish_requires_result_and_generation_choices(tmp_path):
+ with pytest.raises(ValueError, match="existing --result"):
+ guide.guide("image", stage="finish")
+ with pytest.raises(ValueError, match="actual generation choices"):
+ guide.guide("sprite", stage="finish", result=tmp_path)
+
+
+def test_access_probe_redacts_output_and_separates_auth_from_subscription(monkeypatch):
+ monkeypatch.setattr(access.shutil, "which", lambda _: "/fake/codex")
+ monkeypatch.setattr(access.subprocess, "run", lambda *a, **k: SimpleNamespace(returncode=0, stdout="Logged in using ChatGPT", stderr="synthetic-secret"))
+ result = access.probe_access("codex")
+ assert result["login"] == "ready" and result["subscription"] == "unknown"
+ assert "synthetic-secret" not in json.dumps(result)
+ monkeypatch.setattr(access.subprocess, "run", lambda *a, **k: SimpleNamespace(returncode=0, stdout="API key authentication", stderr=""))
+ assert access.probe_access("codex")["login"] == "unknown"
+
+
+def test_video_api_key_requires_own_confirmation(monkeypatch, tmp_path):
+ monkeypatch.setattr(access, "resolve_credential", lambda **kw: SimpleNamespace(source=AUTH_SOURCE_API_KEY))
+ actual = access.probe_access("grok", video=True)
+ assert actual["billing"] == "api-credit"
+ monkeypatch.setattr(guide, "probe_access", lambda *a, **k: actual)
+ base = tmp_path / "base.png"
+ base.touch()
+ options = dict(base_image=base, choices={"motion_method": "grok-video"}, confirmed_access=("grok",))
+ view = guide.guide("sprite", **options)
+ assert [q["field"] for q in view["questions"]] == ["confirm_api_billing"]
+ assert guide.guide("sprite", confirm_api_billing=True, **options)["status"] == "ready"
+
+
+def test_real_cli_finish_save_and_reload(tmp_path):
+ def cli(*args):
+ p = subprocess.run([sys.executable, "-m", "sprite_gen.cli", *args], capture_output=True, text=True)
+ return p, json.loads(p.stdout) if p.stdout else None
+ p, data = cli("defaults", "show")
+ assert p.returncode == 0 and data["revision"] == "missing"
+ p, data = cli("workflow", "--kind", "image", "--stage", "finish", "--result", str(tmp_path), "--image-provider", "grok", "--curation", "skip")
+ assert p.returncode == 2 and data["questions"][0]["field"] == "save_defaults"
+ p, saved = cli("defaults", "save", "--kind", "image", "--image-provider", "grok", "--curation", "skip", "--expected-revision", data["settings_revision"])
+ assert p.returncode == 0
+ p, data = cli("workflow", "--kind", "image", "--stage", "finish", "--result", str(tmp_path))
+ assert p.returncode == 0 and not data["questions"] and data["curation"] == "skip"
+ p, _ = cli("defaults", "save", "--kind", "image", "--image-provider", "codex", "--expected-revision", "missing")
+ assert p.returncode != 0 and "changed since" in p.stderr
+
+
+def test_catalog_routes_use_real_engine_verbs_and_docs():
+ from sprite_gen.cli import COMMANDS
+ root = Path(__file__).resolve().parents[2]
+ for method in MOTION_METHODS.values():
+ assert set(method["steps"]) <= set(COMMANDS)
+ assert (root / method["doc"]).is_file()
+ assert all(set(flow["fields"]) <= set(FIELDS) for flow in FLOWS.values())
+
+
+def test_one_image_can_enter_optional_curation(tmp_path, ready_login):
+ from PIL import Image
+ from sprite_gen.serve.serve_curation import build_run_state
+
+ pngs = tmp_path / "images"
+ pngs.mkdir()
+ output = pngs / "candidate.png"
+ Image.new("RGBA", (24, 24), (55, 80, 110, 255)).save(output)
+ view = guide.guide("image", stage="finish", result=output,
+ choices={"image_provider": "codex", "curation": "open"})
+ assert view["curation"] == "open"
+ run = tmp_path / "curation-run"
+ imported = subprocess.run([sys.executable, "-m", "sprite_gen.cli", "unpack-atlas",
+ "--pngs-dir", str(pngs), "--out-dir", str(run)],
+ capture_output=True, text=True)
+ assert imported.returncode == 0, imported.stderr
+ state = build_run_state(run)
+ assert sum(len(row["frames"]) for row in state["states"]) == 1
+ assert output.is_file()