Skip to content

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

release: v1.59.0 contributor collection

Soohong Kimda0e60968961
diff --git a/.githooks/pre-commit b/.githooks/pre-commit
new file mode 100755
index 0000000..beba654
--- /dev/null
+++ b/.githooks/pre-commit
@@ -0,0 +1,78 @@
+#!/bin/bash
+# .githooks/pre-commit — safedeps repo gate (scaffolded by `safedeps hooks init`).
+#
+# Two checks:
+# 1. Secret scan (always, fail-closed) — blocks a commit when gitleaks finds a
+# secret in the STAGED changes, so a key or a real .env never enters
+# history. The detection POLICY lives in this repo's .gitleaks.toml
+# (public) / .gitleaks.private.toml (private); safedeps owns execution.
+# 2. Dependency audit (npm) — on every commit when this repo has an npm
+# lockfile. Catches a vulnerable direct or *transitive* dependency,
+# including a CVE published AFTER you installed it ("looked safe then,
+# flagged now"). A real finding blocks (fail-closed); only the advisory DB
+# being unreachable (offline) warns and lets the commit through — an
+# observable availability failover, never a silent skip.
+#
+# Intentional bypass (use sparingly — you own the risk): git commit --no-verify
+set -euo pipefail
+
+repo_root=$(git rev-parse --show-toplevel 2>/dev/null || pwd)
+
+# Resolve the safedeps CLI: PATH first, then the known skill install locations.
+resolve_safedeps() {
+ if command -v safedeps >/dev/null 2>&1; then printf 'safedeps'; return 0; fi
+ local candidate
+ for candidate in \
+ "${SAFEDEPS_BIN:-}" \
+ "${HOME}/.claude/skills/safedeps/bin/safedeps" \
+ "${HOME}/.codex/skills/safedeps/bin/safedeps"; do
+ if [ -n "${candidate}" ] && [ -x "${candidate}" ]; then
+ printf '%s' "${candidate}"
+ return 0
+ fi
+ done
+ return 1
+}
+
+if ! sd=$(resolve_safedeps); then
+ cat >&2 <<'EOF'
+safedeps pre-commit: cannot locate the `safedeps` CLI.
+
+The secret-scan gate is FAIL-CLOSED — the commit is blocked because the scanner
+could not run (no silent skip). Fix one of:
+ - put `safedeps` on PATH, or
+ - export SAFEDEPS_BIN=/path/to/bin/safedeps, or
+ - install the skill: node scripts/install/install-safedeps-hooks.mjs
+
+To bypass intentionally (you own the risk): git commit --no-verify
+EOF
+ exit 1
+fi
+
+# 1. Secret scan (always). A non-zero exit means either a secret was found OR
+# no scanner (gitleaks/docker) is available — both fail-closed, block commit.
+"${sd}" scan secrets --staged --root "${repo_root}"
+
+# 2. Dependency audit (npm) — every commit when this repo has an npm lockfile.
+# `safedeps audit npm` exit codes: 0 clean / 1 vulnerable / 2 could-not-run.
+# - vulnerable (1) → BLOCK (fail-closed on the security verdict).
+# - unreachable (2) → WARN and ALLOW (availability failover, observable):
+# an offline commit is never silently dropped, and CI / the daily
+# re-check still cover what this commit could not verify.
+if [ -f "${repo_root}/package-lock.json" ] || [ -f "${repo_root}/npm-shrinkwrap.json" ]; then
+ if "${sd}" audit npm --root "${repo_root}"; then
+ : # clean — no advisory at or above the audit level.
+ else
+ audit_rc=$?
+ if [ "${audit_rc}" -eq 2 ]; then
+ {
+ printf '\n'
+ printf 'safedeps pre-commit: dependency audit could not reach the advisory DB.\n'
+ printf ' -> commit ALLOWED without a fresh dependency verdict (offline failover).\n'
+ printf ' -> re-run `safedeps audit npm` once online; CI / the daily re-check also cover this.\n'
+ } >&2
+ else
+ exit "${audit_rc}" # vulnerable (or unknown failure) -> fail-closed.
+ fi
+ fi
+fi
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
new file mode 100644
index 0000000..504848c
--- /dev/null
+++ b/.github/workflows/ci.yml
@@ -0,0 +1,41 @@
+# SPDX-License-Identifier: Apache-2.0
+name: CI
+
+on:
+ push:
+ branches: [main]
+ pull_request:
+
+jobs:
+ test:
+ name: Tests (Python ${{ matrix.python-version }})
+ runs-on: ubuntu-latest
+ strategy:
+ fail-fast: false
+ matrix:
+ # Keep this matrix aligned with pyproject.toml and README.md:
+ # 3.10 is the minimum supported CPython; 3.14 is the latest covered version.
+ python-version: ["3.10", "3.14"]
+ steps:
+ - uses: actions/checkout@v4
+
+ - uses: actions/setup-python@v5
+ with:
+ python-version: ${{ matrix.python-version }}
+
+ - name: Install (clean environment, as the quickstart does)
+ run: |
+ python -m venv .venv
+ .venv/bin/pip install -e ".[dev]"
+
+ - name: Quickstart smoke (prepare -> extract -> compose)
+ run: |
+ .venv/bin/python scripts/prepare_sprite_run.py --help > /dev/null
+ cp -r tests/fixtures/run /tmp/smoke-run
+ .venv/bin/python scripts/extract_sprite_row_frames.py --run-dir /tmp/smoke-run
+ .venv/bin/python scripts/compose_sprite_atlas.py --run-dir /tmp/smoke-run
+ test -f /tmp/smoke-run/sprite-sheet-alpha.png
+ test -f /tmp/smoke-run/manifest.json
+
+ - name: Tests
+ run: .venv/bin/python -m pytest -q
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..d5e34ea
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,18 @@
+__pycache__/
+*.py[cod]
+.DS_Store
+*.egg-info/
+.venv/
+.pytest_cache/
+/assets/
+app/build/dist/
+app/build/work/
+app/desktop/dist/
+app/desktop/node_modules/
+app/desktop/src-tauri/target/
+app/desktop/src-tauri/binaries/sprite-mcp-*
+.gjc/
+uv.lock
+
+# transient validator reply scratch (never track)
+.validator-reply-*
diff --git a/.gitleaks.toml b/.gitleaks.toml
new file mode 100644
index 0000000..80b8674
--- /dev/null
+++ b/.gitleaks.toml
@@ -0,0 +1,43 @@
+# .gitleaks.toml — safedeps starter secret-scan policy (public repo profile).
+#
+# safedeps OWNS execution (it runs gitleaks via `safedeps scan secrets`).
+# THIS FILE is the repo's POLICY — you own it. Tune the [allowlist] below for
+# this repo. `safedeps hooks init` scaffolds this file once and will NOT
+# overwrite it on a re-run, so your edits are safe.
+#
+# gitleaks config reference: https://github.com/gitleaks/gitleaks#configuration
+
+title = "safedeps secret-scan policy"
+
+# Inherit gitleaks' built-in ruleset (AWS / GCP / private keys / OAuth tokens /
+# generic high-entropy secrets, etc.). This is the bulk of the coverage.
+[extend]
+useDefault = true
+
+# --- Extra rules layered on top of the defaults -------------------------------
+
+# Flag a committed real dotenv file with an assigned secret. The .example /
+# .sample / .template variants are allowlisted below so docs stay committable.
+[[rules]]
+id = "safedeps-dotenv-file"
+description = "Committed .env file with an assigned secret value"
+path = '''(^|/)\.env(\.[\w.-]+)?$'''
+regex = '''(?i)(secret|token|password|passwd|api[_-]?key|access[_-]?key|private[_-]?key|client[_-]?secret)\s*[:=]\s*\S{6,}'''
+ [rules.allowlist]
+ paths = [
+ '''(^|/)\.env\.example$''',
+ '''(^|/)\.env\.sample$''',
+ '''(^|/)\.env\.template$''',
+ ]
+
+# --- Repo-owned allowlist — CUSTOMIZE FOR THIS REPO ---------------------------
+[allowlist]
+description = "Repo-specific allowlist (tune me)"
+paths = [
+ '''(^|/)\.gitleaks\.toml$''',
+ '''(^|/)\.gitleaks\.private\.toml$''',
+ # Add test fixtures / docs that legitimately contain secret-shaped strings:
+ # '''(^|/)test/fixtures/''',
+]
+# regexes = ['''EXAMPLE_PLACEHOLDER_[A-Z0-9]+''']
+# stopwords = ["example", "dummy", "placeholder"]
diff --git a/CHANGELOG.md b/CHANGELOG.md
new file mode 100644
index 0000000..0867b7d
--- /dev/null
+++ b/CHANGELOG.md
@@ -0,0 +1,27 @@
+# Changelog
+
+All notable public changes to `sprite-gen` are recorded here. Versions track the `version:` field in `SKILL.md` and `pyproject.toml`.
+
+## v1.59.0 - Contributor Collection
+
+This release collects five community pull requests into one tested release. Thanks to [@Dongkyu-ES](https://github.com/Dongkyu-ES) for deterministic CLI tests, engine export, and subject-aware sparse-frame handling, and to [@napkn34](https://github.com/napkn34) for the Windows provider and publish-lock fixes.
+
+- Added `sprite-gen export-aseprite` for Phaser-compatible Aseprite JSON and Flame-compatible hash files split by state. Curated frame geometry and timing remain canonical, and exports are confined to the run's `exports/` directory.
+- Added a Windows `LockFileEx` backend that preserves shared readers and exclusive publishers across processes without weakening the fail-loud isolation contract.
+- Fixed provider CLI resolution and UTF-8 subprocess I/O on Windows, including npm `.cmd` shims and non-UTF-8 console code pages.
+- Made Python 3.14 CLI option tests deterministic under colored shell output.
+- Added `character` and `effect` subject profiles. Their sparse-frame floors scale with cell resolution: `ceil(sqrt(width * height))` for characters and half that value for effects. Explicit `--min-used-pixels` still wins.
+
+## v1.58.0 - Compose canvas and domain package layout
+
+- Added the human-facing `sprite-gen compose` assembly canvas and handoff to the curation view.
+- Reorganized the Python package and tests into domain subpackages while preserving CLI and script entrypoints.
+- Split request loading from schema migration so reads no longer mutate run state.
+
+## v1.57.0 - First Pixel Breath
+
+- Added deterministic breathing, pixel-grid measurement, curation editing, and run repair contracts.
+- Added deterministic palette-swap recolor baking (`sprite-gen recolor` / `recolor-palette`) and curation-side colourway selection.
+- Added package entrypoints, declared runtime dependencies, and install smoke coverage.
+
+Earlier public milestones are summarized above. Historical tags remain published only where their contents pass the current public-data policy.
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..13e25df
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,201 @@
+Apache License
+Version 2.0, January 2004
+http://www.apache.org/licenses/
+
+TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf of
+ any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+END OF TERMS AND CONDITIONS
+
+APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don\'t include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+Copyright [yyyy] [name of copyright owner]
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
diff --git a/NOTICE b/NOTICE
new file mode 100644
index 0000000..83e09ec
--- /dev/null
+++ b/NOTICE
@@ -0,0 +1,29 @@
+sprite-gen
+Copyright 2026 Alex Kim
+
+This project is inspired by the Apache-2.0 licensed hatch-pet component-row
+workflow. sprite-gen targets generic game sprite atlases and does not include
+Codex pet assets, pet packages, or hatch-pet visual assets.
+
+The `align_x: "alpha-centroid"` frame alignment (sprite_gen/extract.py) is a
+port of the alpha-weighted mass-centroid alignment from perfectpixel-studio
+(https://github.com/gykim80/perfectpixel-studio, internal/sprite/extract.go),
+Copyright Andrew Kim (gykim80), MIT License.
+
+The `segmentation: "projection"` frame separation (sprite_gen/segment.py) is a
+port of the projection-profile + DP optimal-cut segmentation from
+perfectpixel-studio (https://github.com/gykim80/perfectpixel-studio,
+internal/sprite/segment.go), Copyright Andrew Kim (gykim80), MIT License.
+
+The opt-in `chroma.mode: "ycbcr"` background matting (sprite_gen/extract.py) is
+a port of the chrominance-plane matting — CbCr border-mode key detection,
+Hermite soft matte, key-direction despill, border flood fill and the pure-key
+rematte self-diagnostic — from perfectpixel-studio
+(https://github.com/gykim80/perfectpixel-studio, internal/sprite/chroma.go),
+Copyright Andrew Kim (gykim80), MIT License.
+
+The estimation-only `estimate_pixel_grid_runlen` pitch estimator
+(sprite_gen/extract.py) is a port of the unfake same-color run-length mode
+block-size estimation from perfectpixel-studio
+(https://github.com/gykim80/perfectpixel-studio, internal/sprite/pixelize.go),
+Copyright Andrew Kim (gykim80), MIT License.
diff --git a/README.es.md b/README.es.md
new file mode 100644
index 0000000..2f226e2
--- /dev/null
+++ b/README.es.md
@@ -0,0 +1,235 @@
+<h1 align="center">sprite-gen</h1>
+
+<p align="center"><b>Entra un dibujo. Sale un atlas de sprites listo para el juego, respirando.</b></p>
+
+<p align="center">
+
+**Inglés** · [한국어](README.ko.md) · [日本語](README.ja.md) · [简体中文](README.zh-Hans.md) · [Español](README.es.md) · [Français](README.fr.md)
+
+</p>
+
+---
+
+## Respiración
+
+Una pose estática de reposo parece congelada. **Breathe** convierte una sola pose en un bucle vivo mediante una deformación determinista de compresión y estiramiento aplicada sobre tus fotogramas seleccionados. Sin regeneración, sin volver a extraer y sin arte adicional. Basta con un campo en el archivo auxiliar:
+
+```json
+"breathe": { "depth": 0.05, "breaths": 3 }
+```
+
+- **Consciente de la anatomía.** El motor mide la silueta: el estrechamiento del cuello, el par de ojos simétrico en figuras amorfas sin cuello y la anchura del torso frente a la de los apéndices. Las cabezas permanecen **idénticas bit a bit** en todos los fotogramas; las alas y los brazos se desplazan, nunca se estiran.
+- **Fiel al píxel.** Solo se usan correspondencias de filas y columnas enteras: cada fotograma de salida sigue siendo pixel art limpio sobre la misma cuadrícula. Un contorno de 1 px sigue siendo un contorno de 1 px: la deformación conserva los bordes de la silueta y normaliza la duplicación en escalera, anclándose en la línea interior.
+- **Una regla que puedes agarrar.** Arrastra el límite rígido (rojo), el eje del cuerpo (azul) y la anchura del torso (línea discontinua) directamente sobre la reproducción en vivo. Al soltar, el servidor vuelve a calcular la anatomía, mientras la vista previa sigue respirando durante el cálculo.
+- **Vista previa idéntica byte a byte.** El espejo de la webview y la generación en Python producen los mismos bytes, algo garantizado mediante pruebas doradas. El bucle que ves es exactamente el que se publica en el atlas.
+
+<p align="center">
+ <img src="docs/assets/breathe-editor.png" width="760" alt="editor de regiones de respiración: límite rígido, eje corporal y líneas de anchura del torso sobre la reproducción en vivo, con la tira de fotogramas de las fases generadas" />
+</p>
+
+El mismo horneado determinista se aplica a vistas frontales, laterales y traseras de cualquier silueta, incluidos humanoides, masas y tentáculos.
+
+Pídele a un modelo de imágenes una «hoja de sprites» y ya sabes qué obtendrás: un personaje cuyo rostro cambia en cada fotograma, un fondo que no se puede eliminar por clave de color, poses que se solapan y se desvían de la cuadrícula, y un PNG que tu motor de juego ni siquiera puede usar. Una demostración bonita, un recurso inútil.
+
+`sprite-gen` es una habilidad para Codex/Claude que cierra esa brecha. Dale **una imagen base** y una lista de acciones: genera fila por fila, fija la identidad del personaje, elimina el fondo cromático para obtener un canal alfa real, extrae cada pose como un fotograma transparente y limpio, y genera un atlas para ejecución **con un `manifest.json.frame_layout` legible por máquina**.
+
+Y para ese último 10 % que la generación nunca resuelve bien, existe una **webview de selección**: compara fotogramas en paralelo, descarta los defectuosos, ajusta la rotación, la escala y la posición de forma no destructiva, y observa el bucle en vivo antes de generar el resultado. La canalización se encarga del trabajo; tú aportas el criterio.
+
+```text
+sprite-request.json → guías de diseño + prompts → filas de estados de sprite-gen gen
+→ alfa cromático → componentes conectados → fotogramas transparentes
+→ sprite-sheet-alpha.png + manifest.json.frame_layout
+```
+
+```mermaid
+flowchart LR
+ REQ["sprite-request.json<br/>(SSoT numérica)"] --> GUIDES["guías de diseño<br/>+ prompts"]
+ GUIDES --> GEN["sprite-gen gen<br/>tiras de filas de estados"]
+ GEN --> EXTRACT["alfa cromático →<br/>componentes conectados"]
+ EXTRACT --> FRAMES["fotogramas transparentes"]
+ FRAMES --> ATLAS["sprite-sheet-alpha.png<br/>+ manifest.json.frame_layout"]
+ FRAMES -. "webview de selección (opcional)" .-> ATLAS
+```
+
+> Arquitectura completa: [`docs/architecture.md`](docs/architecture.md)
+
+## Lo que realmente obtienes
+
+- **Un atlas de sprites transparente** (`sprite-sheet-alpha.png`): alfa real, sin restos de halos cromáticos y verificado sobre fondos blancos.
+- **Un manifiesto para ejecución** (`manifest.json.frame_layout`): rectángulos absolutos de los fotogramas, fps por estado e indicadores de bucle. Tu motor muestrea rectángulos; nunca tiene que adivinar una cuadrícula.
+- **Variantes de color deterministas**: `sprite-gen recolor` toma la hoja base y un mapa de paleta, y genera N hojas variantes con un solo comando (coincidencia RGB exacta de forma predeterminada; la misma entrada produce los mismos bytes de salida). La webview de selección permite compararlas mediante parpadeo y registra el nombre adoptado. Detalles: [`docs/recolor.md`](docs/recolor.md).
+- **Control de calidad que puedes observar**: GIF y hojas de contacto por estado, para evaluar el movimiento como movimiento antes de publicar nada.
+- **Etiquetas honestas**: las acciones breves y legibles (reposo, salto, ataque, saludo) constituyen la ruta estable; la locomoción cíclica (caminar/correr) se marca como experimental salvo que supere realmente el control de calidad de movimiento. Sin promesas exageradas ocultas.
+
+## Calidad del alfa cromático
+
+El extractor mantiene determinista la limpieza cromática: la separación mediante alfa suave conserva los mechones de cabello con antialiasing y los contornos finos, en lugar de arrancarlos antes de poder calcular la cobertura.
+
+<p align="center">
+ <img src="docs/assets/chroma-fullbody-illustration-magenta.png" width="640" alt="comparación cromática de cuerpo completo: ilustración sobre clave magenta" /><br />
+ <em>Ilustración, clave magenta: fuente, eliminación de v1.12.0 y separación mediante alfa suave de v1.13.0.</em>
+</p>
+
+<p align="center">
+ <img src="docs/assets/chroma-fullbody-illustration-green.png" width="640" alt="comparación cromática de cuerpo completo: ilustración sobre clave verde" /><br />
+ <em>Ilustración, clave verde: fuente, eliminación de v1.12.0 y separación mediante alfa suave de v1.13.0.</em>
+</p>
+
+<p align="center">
+ <img src="docs/assets/chroma-fullbody-pixelart-magenta.png" width="640" alt="comparación cromática de cuerpo completo: pixel art sobre clave magenta" /><br />
+ <em>Pixel art, clave magenta: fuente, eliminación de v1.12.0 y salida binarizada de v1.13.0.</em>
+</p>
+
+<p align="center">
+ <img src="docs/assets/chroma-fullbody-pixelart-green.png" width="640" alt="comparación cromática de cuerpo completo: pixel art sobre clave verde" /><br />
+ <em>Pixel art, clave verde: fuente, eliminación de v1.12.0 y salida binarizada de v1.13.0.</em>
+</p>
+
+Los recortes ampliados que aparecen a continuación muestran el detalle de los bordes de las comparaciones de cuerpo completo.
+
+![eliminación cromática antes y después: mechón de cabello ilustrado](docs/assets/chroma-peel-illustration-before-after.png)
+
+![eliminación cromática antes y después: contorno de pixel art](docs/assets/chroma-peel-pixelart-before-after.png)
+
+## Backbone Lattice
+
+El «pixel art» generado por IA no es pixel art. Los bloques oscilan, los bordes contienen antialiasing y la retícula se desplaza dentro de una misma fila, por lo que cortar sobre una cuadrícula uniforme mezcla un bloque con el siguiente. La solución de la comunidad consiste en «desfalsear» la imagen: estimar el tamaño de los bloques a partir de la longitud de los segmentos y volver a cuantizar. Sin embargo, esto mide cada fotograma por separado, por lo que el tamaño de las celdas de un ciclo de marcha se expande y contrae de un fotograma a otro.
+
+**Backbone Lattice** mide una única cuadrícula para todo el sujeto y ajusta cada corte a ella. La detección del paso por fotograma alimenta un consenso de toda la fila y entre fotogramas que descarta las detecciones armónicas erróneas; esa cuadrícula de consenso es la *columna vertebral* a la que se ajusta cada corte. Los cortes caen sobre límites de color reales, y una anchura mínima de celda proporcional al paso medido evita que dos cortes vecinos lleguen a colapsar sobre la misma banda. Una única columna vertebral hace que un bloque conserve el mismo tamaño durante toda la animación, en lugar de saltar entre fotogramas.
+
+El resultado se verifica contra lo que se publica, no mediante una inspección visual de un fotograma elegido a mano: cada ejecución de corrección de píxeles vuelve a derivarse de su propia tira de origen y se compara píxel por píxel. La forma que aprobaste sigue siendo la que obtienes; lo único que cambia es dónde se colocan los contornos y el sombreado, que es precisamente lo que decide la columna vertebral.
+
+## Webview de selección
+
+La generación te lleva al 90 %. La webview es donde una persona completa el trabajo hasta dejarlo *listo para publicar*: es independiente, no depende de Studio ni de ningún framework y se ejecuta en cualquier lugar donde esté instalada la habilidad (Claude Code Desktop, la aplicación Codex o una terminal convencional).
+
+![webview de selección: personajes](docs/assets/demo-character.gif)
+
+- **Dos filas por estado:** la **secuencia de reproducción** arriba y un **grupo de candidatos** debajo (por ejemplo, una segunda o tercera generación). Arrastra el control ⠿ de un fotograma para reordenar la secuencia, o sube un recorte desde el grupo para reconstruir un bucle de carrera limpio con los mejores fotogramas de distintas generaciones. La disposición se guarda, por lo que se restaura al volver a abrirla.
+- **Transformación no destructiva** por fotograma: arrastrar = mover, rueda = escalar, control superior = rotar, control inferior izquierdo = sesgar, además de un interruptor de volteo horizontal para salidas invertidas de izquierda a derecha. Las ediciones se guardan en un archivo auxiliar `curation.json`: los PNG de origen nunca se reescriben y el paso de composición genera el resultado de forma determinista. La vista previa y la generación comparten una única matriz afín, por lo que lo que alineas es lo que obtienes.
+- La **vista previa en vivo** anima la secuencia a los fps del estado, con reproducción/pausa, avance fotograma a fotograma y control de velocidad de 0.25× a 4×.
+- No sirve solo para sprites: haz que apunte a cualquier carpeta de imágenes candidatas (iconos, logotipos o borradores generados) mediante `unpack_atlas_run.py --pngs-dir` y úsala como una vista general para elegir la mejor opción.
+
+### Cuadrícula de suelo isométrica
+
+Para conjuntos isométricos, la webview superpone la cuadrícula del suelo (obtenida de los campos de mosaico/anclaje de `meta.json`) para que puedas ajustar los muebles a los ejes del rombo mediante el control de sesgo.
+
+![webview de selección: mobiliario isométrico](docs/assets/demo-furniture.gif)
+
+<img src="docs/assets/curator-iso.png" width="520" alt="superposición de cuadrícula de suelo isométrica" />
+
+### Idiomas
+
+La webview incluye inglés y coreano. Pasa `--lang en|ko` al iniciarla o utiliza el selector integrado:
+
+```bash
+python3 scripts/serve_curation.py --run-dir <run-dir> --lang en # o ko
+```
+
+## Compatibilidad con Python
+
+`sprite-gen` es compatible con CPython 3.10 o posterior. La integración continua ejecuta la versión mínima compatible (3.10) y la última versión cubierta (3.14) en ejecutores alojados en GitHub.
+
+El inicio rápido requiere una instalación de Python con `venv`/`ensurepip` funcionales. Si `python3 -m venv` falla antes de instalar paquetes en una distribución local, utiliza una compilación estándar de CPython de cualquier versión compatible y vuelve a ejecutar los mismos comandos.
+
+## Inicio rápido
+
+```bash
+# 0. instalar las dependencias (Pillow, NumPy) en un entorno virtual nuevo
+python3 -m venv .venv && source .venv/bin/activate
+pip install -e .
+
+# 1. preparar una ejecución a partir de una imagen base
+python3 scripts/prepare_sprite_run.py --out-dir <run-dir> --character-id <id> --base-image base.png
+
+# 2. generar una imagen de fila por estado con la CLI del proveedor controlada por el motor
+python3 scripts/generate_sprite_image.py --provider codex \
+ --prompt-file <run-dir>/prompts/<state>.txt \
+ --out <run-dir>/raw/<state>.png \
+ --ref <run-dir>/base-source.png \
+ --ref <run-dir>/references/layout-guides/<state>.png
+# 3. extraer los fotogramas
+python3 scripts/extract_sprite_row_frames.py --run-dir <run-dir>
+
+# 4. (opcional) seleccionar los fotogramas en la webview
+python3 scripts/serve_curation.py --run-dir <run-dir>
+
+# 5. generar el atlas para ejecución
+python3 scripts/compose_sprite_atlas.py --run-dir <run-dir>
+```
+
+### Editar una hoja terminada
+
+Cuando solo se conserva la hoja combinada, reconstruye un directorio de ejecución preparado para el selector y, a continuación, selecciona y exporta:
+
+```bash
+# reconstruir fotogramas: --grid explícito, rectángulos de --manifest o detección alfa automática (predeterminada)
+python3 scripts/unpack_atlas_run.py --atlas sheet.png # detección automática
+python3 scripts/unpack_atlas_run.py --manifest manifest.json # rectángulos exactos
+python3 scripts/unpack_atlas_run.py --pngs-dir furniture/ # importar un conjunto de PNG independientes
+
+# después de la selección, aplicar las correcciones a los PNG con nombre
+python3 scripts/export_curated_pngs.py --run-dir <run-dir>
+```
+
+La salida se guarda de forma predeterminada en una carpeta localizable `<source>-curator` junto a la entrada.
+
+### Generación de variantes de color de una hoja terminada
+
+Una vez compuesto el atlas, sustituye los colores seleccionados para obtener N hojas terminadas sin volver a ejecutar la generación. El arte de píxeles utiliza coincidencia exacta de forma predeterminada; el arte con bordes suaves puede habilitar una tolerancia. La geometría y el alfa nunca cambian: el manifiesto base describe cada variante.
+
+```bash
+# bosqueja los colores opacos (edítalo para convertirlo en una especificación de recoloreado con kind "sprite-gen-recolor")
+python3 -m sprite_gen.cli recolor-palette --base <run-dir>/sprite-sheet-alpha.png --out palette.draft.json
+
+# genera cada variante de color en <run-dir>/variants/
+python3 -m sprite_gen.cli recolor --run-dir <run-dir> --spec recolor.spec.json
+
+# compara mediante parpadeo y adopta en la vista de curación
+python3 -m sprite_gen.cli curation --run-dir <run-dir>
+```
+
+Contrato completo de especificación/informe y campo del sidecar de adopción: [`docs/recolor.md`](docs/recolor.md).
+
+### Eliminación del fondo de una imagen importada
+
+Los sprites generados se recortan a partir de su propio fondo magenta/verde dentro del pipeline, por lo que nunca necesitan esto. `cutout` es la utilidad de importación/posedición: una imagen que llegó *con* un fondo uniforme opaco (un icono dibujado a mano, un sprite descargado, una captura de pantalla) se convierte en un PNG transparente limpio.
+
+<p align="center">
+ <img src="docs/assets/cutout-demo.png" width="720" alt="cutout: un icono de juego con fondo blanco convertido en un PNG transparente limpio, conservando los reflejos del cristal" />
+</p>
+
+```bash
+# enruta según el color de la esquina: blanco/marfil -> matte, magenta/verde -> motor de extracción
+python3 -m sprite_gen.cli cutout icon.png --white-check
+```
+
+Lee el color de fondo de la esquina y enruta (`--key auto|white|magenta|green`):
+
+- **blanco / marfil / sólido** → matte posicional. Un relleno por inundación desde una esquina conserva únicamente el fondo conectado (los reflejos brillantes *dentro* del objeto sobreviven, sin crear agujeros) y, a continuación, un alfa suave descontaminado difumina el borde. Ajústalo con `--strength` (eliminación del bisel), `--band` (profundidad del borde) y `--erode`.
+- **clave magenta / verde** → se reutiliza sin cambios el motor cromático `extract` verificado del proyecto. Los colores clave nunca aparecen en los objetos, por lo que allí su recorte basado únicamente en el color es seguro, exactamente donde *no* se necesita la protección del relleno por inundación de un matte blanco.
+
+`--white-check` genera composiciones cian/magenta/amarillo para que cualquier halo restante destaque claramente. Está pensado para fondos uniformes, no para fondos complejos o no uniformes.
+
+El flujo de trabajo completo orientado a agentes y sus contratos se encuentran en [`SKILL.md`](SKILL.md).
+
+## Instalación
+
+Desde los flujos de trabajo del instalador de skills de Codex, instala este repositorio como skill raíz:
+
+```bash
+python3 ~/.codex/skills/.system/skill-installer/scripts/install-skill-from-github.py \
+ --repo aldegad/sprite-gen --path .
+```
+
+### Propiedad de la generación de imágenes
+
+La generación respaldada por proveedores forma parte de este motor (`sprite_gen.gen`), con `codex` y `grok` como proveedores compatibles. La skill general `image-gen` es solo un puente ligero hacia el mismo comando, por lo que no necesita una segunda implementación de proveedor. Consulta [`docs/gen.md`](docs/gen.md) para conocer el contrato de la CLI y de verificación.
+
+## Atribución
+
+El flujo de trabajo por filas de componentes está inspirado en la skill `hatch-pet`, licenciada bajo Apache-2.0, pero está dirigido a atlas genéricos de sprites para juegos y no incluye paquetes de mascotas ni recursos visuales de mascotas.
+
+## Licencia
+
+Apache-2.0
diff --git a/README.fr.md b/README.fr.md
new file mode 100644
index 0000000..6d6d79b
--- /dev/null
+++ b/README.fr.md
@@ -0,0 +1,235 @@
+<h1 align="center">sprite-gen</h1>
+
+<p align="center"><b>Un dessin en entrée. Un atlas de sprites prêt pour le jeu en sortie — et qui respire.</b></p>
+
+<p align="center">
+
+**Anglais** · [한국어](README.ko.md) · [日本語](README.ja.md) · [简体中文](README.zh-Hans.md) · [Español](README.es.md) · [Français](README.fr.md)
+
+</p>
+
+---
+
+## Respiration
+
+Une pose de repos immobile paraît figée. **Breathe** transforme une pose unique en une boucle vivante — un effet déterministe d’écrasement et d’étirement appliqué par-dessus vos images soigneusement sélectionnées. Aucune nouvelle génération, aucune nouvelle extraction, aucune ressource graphique supplémentaire. Un seul champ annexe :
+
+```json
+"breathe": { "depth": 0.05, "breaths": 3 }
+```
+
+- **Conscient de l’anatomie.** Le moteur mesure la silhouette : étranglement du cou, paire d’yeux symétrique sur les formes sans cou, largeur du torse par rapport aux appendices. Les têtes restent **strictement identiques au niveau des bits** sur toutes les images ; les ailes et les bras sont déplacés, jamais étirés.
+- **Fidèle aux pixels.** Uniquement une correspondance entière des lignes et des colonnes — chaque image produite reste un pixel art net sur la même grille. Un contour de 1 px reste un contour de 1 px : la déformation préserve les bords de la silhouette et normalise le doublement en escalier, avec un ancrage sur la ligne intérieure.
+- **Une règle que vous pouvez saisir.** Faites glisser directement sur la lecture en direct la limite rigide (rouge), l’axe du corps (bleu) et la largeur du torse (pointillés). Le serveur recalcule l’anatomie au relâchement — et l’aperçu continue de respirer pendant le recalcul.
+- **Aperçu identique octet pour octet.** Le miroir de la webview et la génération Python produisent les mêmes octets, ce que garantissent des tests de référence. La boucle que vous regardez est exactement celle qui est livrée dans l’atlas.
+
+<p align="center">
+ <img src="docs/assets/breathe-editor.png" width="760" alt="éditeur de région de respiration : limite rigide, axe du corps et lignes de largeur du torse sur la lecture en direct, avec la pellicule des phases générées" />
+</p>
+
+Le même traitement déterministe s’applique aux vues de face, de profil et de dos de toute silhouette, y compris les humanoïdes, les formes amorphes et les tentacules.
+
+Demandez une « sprite sheet » à un modèle d’image et vous savez ce que vous obtiendrez : un personnage dont le visage change à chaque image, un arrière-plan impossible à détourer proprement, des poses qui se chevauchent et dérivent hors de la grille, ainsi qu’un PNG que votre moteur de jeu ne peut pas réellement exploiter. Une jolie démo, mais une ressource inutilisable.
+
+`sprite-gen` est une compétence Codex/Claude qui comble cette lacune. Fournissez-lui **une image de base** et une liste d’actions : elle pilote la génération ligne par ligne, verrouille l’identité du personnage, remplace l’arrière-plan chromatique par une véritable transparence alpha, extrait chaque pose sous forme d’image transparente propre et génère un atlas d’exécution **avec un `manifest.json.frame_layout` lisible par machine**.
+
+Et pour les 10 % restants que la génération ne réussit jamais parfaitement, une **webview de sélection** permet de comparer les images côte à côte, de rejeter celles qui sont défectueuses, d’ajuster de manière non destructive la rotation, l’échelle et la position, puis d’observer la boucle en direct avant la génération finale. Le pipeline effectue le travail ; vous gardez la maîtrise artistique.
+
+```text
+sprite-request.json → guides de disposition + prompts → lignes d’états sprite-gen gen
+→ alpha chromatique → composantes connexes → images transparentes
+→ sprite-sheet-alpha.png + manifest.json.frame_layout
+```
+
+```mermaid
+flowchart LR
+ REQ["sprite-request.json<br/>(SSoT numérique)"] --> GUIDES["guides de disposition<br/>+ prompts"]
+ GUIDES --> GEN["sprite-gen gen<br/>bandes de lignes d’états"]
+ GEN --> EXTRACT["alpha chromatique →<br/>composantes connexes"]
+ EXTRACT --> FRAMES["images transparentes"]
+ FRAMES --> ATLAS["sprite-sheet-alpha.png<br/>+ manifest.json.frame_layout"]
+ FRAMES -. "webview de sélection (facultative)" .-> ATLAS
+```
+
+> Architecture complète : [`docs/architecture.md`](docs/architecture.md)
+
+## Ce que vous obtenez réellement
+
+- **Un atlas de sprites transparent** (`sprite-sheet-alpha.png`) — véritable transparence alpha, sans frange chromatique résiduelle, vérifié sur des arrière-plans blancs.
+- **Un manifeste d’exécution** (`manifest.json.frame_layout`) — rectangles absolus des images, fréquence d’images et indicateurs de boucle pour chaque état. Votre moteur échantillonne des rectangles ; il ne tente jamais de deviner une grille.
+- **Des palettes de couleurs déterministes** — `sprite-gen recolor` utilise la feuille de base et une table de correspondance de palette pour générer N feuilles variantes en une seule commande (correspondance RVB exacte par défaut ; mêmes données en entrée, mêmes octets en sortie). La webview de sélection les compare par clignotement et enregistre le nom retenu. Détails : [`docs/recolor.md`](docs/recolor.md).
+- **Une assurance qualité observable** — des GIF par état et des planches-contact permettent d’évaluer le mouvement comme un mouvement avant toute livraison.
+- **Des libellés honnêtes** — les actions courtes et lisibles (repos, saut, attaque, salut) constituent le parcours stable ; la locomotion cyclique (marche/course) est signalée comme expérimentale, sauf si le contrôle qualité du mouvement est effectivement réussi. Aucune promesse excessive passée sous silence.
+
+## Qualité de l’alpha chromatique
+
+L’extracteur assure un nettoyage chromatique déterministe : le démélange avec alpha progressif préserve les mèches de cheveux anticrénelées et les contours fins au lieu de les retirer avant que la couverture puisse être calculée.
+
+<p align="center">
+ <img src="docs/assets/chroma-fullbody-illustration-magenta.png" width="640" alt="comparaison chromatique en pied : illustration sur fond d’incrustation magenta" /><br />
+ <em>Illustration, fond d’incrustation magenta : source, détourage v1.12.0, démélange avec alpha progressif v1.13.0.</em>
+</p>
+
+<p align="center">
+ <img src="docs/assets/chroma-fullbody-illustration-green.png" width="640" alt="comparaison chromatique en pied : illustration sur fond d’incrustation vert" /><br />
+ <em>Illustration, fond d’incrustation vert : source, détourage v1.12.0, démélange avec alpha progressif v1.13.0.</em>
+</p>
+
+<p align="center">
+ <img src="docs/assets/chroma-fullbody-pixelart-magenta.png" width="640" alt="comparaison chromatique en pied : pixel art sur fond d’incrustation magenta" /><br />
+ <em>Pixel art, fond d’incrustation magenta : source, détourage v1.12.0, sortie binarisée v1.13.0.</em>
+</p>
+
+<p align="center">
+ <img src="docs/assets/chroma-fullbody-pixelart-green.png" width="640" alt="comparaison chromatique en pied : pixel art sur fond d’incrustation vert" /><br />
+ <em>Pixel art, fond d’incrustation vert : source, détourage v1.12.0, sortie binarisée v1.13.0.</em>
+</p>
+
+Les recadrages rapprochés ci-dessous montrent les détails des bords à l’origine des comparaisons en pied.
+
+![détourage chromatique avant et après — mèche de cheveux illustrée](docs/assets/chroma-peel-illustration-before-after.png)
+
+![détourage chromatique avant et après — contour en pixel art](docs/assets/chroma-peel-pixelart-before-after.png)
+
+## Backbone Lattice
+
+Le « pixel art » généré par l’IA n’est pas du pixel art. Les blocs vacillent, les bords comportent de l’anticrénelage et la grille dérive au sein d’une même ligne, si bien qu’une découpe sur une grille régulière étale un bloc sur le suivant. La solution communautaire consiste à « défalsifier » l’image — estimer la taille des blocs à partir de la longueur des segments et effectuer une nouvelle quantification — mais chaque image est alors mesurée indépendamment, ce qui fait varier la taille des cellules d’une image à l’autre dans un cycle de marche.
+
+**Backbone Lattice** mesure une grille unique pour l’ensemble du sujet et y contraint chaque découpe. La détection du pas pour chaque image alimente un consensus couvrant toute la ligne et toutes les images, capable de l’emporter sur les détections harmoniques erronées ; cette grille consensuelle constitue l’*ossature* sur laquelle s’aligne chaque découpe. Les découpes tombent sur les véritables limites de couleur, et une largeur de cellule minimale proportionnelle au pas mesuré empêche deux découpes voisines de se rabattre sur la même bande. Une seule ossature permet ainsi à un même bloc de conserver la même taille pendant toute une animation au lieu de sauter d’une image à l’autre.
+
+Le résultat est vérifié par rapport à ce qui est effectivement livré, et non évalué à l’œil sur une image soigneusement choisie : chaque exécution de défalsification des pixels est recalculée depuis sa propre bande source, puis comparée pixel par pixel. La forme que vous avez approuvée reste celle que vous obtenez ; seules les positions des contours et des ombrages changent, ce qui correspond précisément à la décision prise par l’ossature.
+
+## Webview de sélection
+
+La génération vous amène à 90 %. La webview permet à une personne de parvenir à une ressource *prête à être livrée* — elle est autonome, ne dépend ni de Studio ni d’un framework et fonctionne partout où la compétence est installée (Claude Code Desktop, l’application Codex ou un simple terminal).
+
+![webview de sélection — personnages](docs/assets/demo-character.gif)
+
+- **Deux lignes par état :** la **séquence de lecture** en haut et une **réserve de candidats** en dessous (par exemple, une deuxième ou une troisième génération). Faites glisser la poignée ⠿ d’une image pour réorganiser la séquence, ou remontez une découpe depuis la réserve afin de reconstruire une boucle de course propre à partir des meilleures images de plusieurs générations. La disposition est enregistrée et restaurée à la réouverture.
+- **Transformation non destructive** pour chaque image : glisser = déplacer, molette = redimensionner, poignée supérieure = faire pivoter, poignée inférieure gauche = incliner, avec en plus une option de retournement horizontal pour les sorties inversées gauche-droite. Les modifications sont conservées dans un fichier annexe `curation.json` — les PNG sources ne sont jamais réécrits et l’étape de composition génère le résultat de manière déterministe. L’aperçu et la génération finale utilisent la même matrice affine : ce que vous alignez est donc exactement ce que vous obtenez.
+- **L’aperçu en direct** anime la séquence à la fréquence d’images de l’état, avec lecture/pause, progression image par image et réglage de la vitesse de 0.25× à 4×.
+- Pas seulement pour les sprites : dirigez l’outil vers n’importe quel dossier contenant des images candidates (icônes, logos, brouillons générés) avec `unpack_atlas_run.py --pngs-dir` et utilisez-le comme une vue générale de sélection du meilleur résultat.
+
+### Grille de sol isométrique
+
+Pour les ensembles isométriques, la webview superpose la grille du sol (à partir de la tuile et de l’ancrage définis dans `meta.json`) afin que vous puissiez aligner les meubles sur les axes du losange à l’aide de la poignée d’inclinaison.
+
+![webview de sélection — mobilier isométrique](docs/assets/demo-furniture.gif)
+
+<img src="docs/assets/curator-iso.png" width="520" alt="superposition de la grille de sol isométrique" />
+
+### Langues
+
+La webview est fournie en anglais et en coréen. Passez `--lang en|ko` au lancement ou utilisez le sélecteur intégré à l’application :
+
+```bash
+python3 scripts/serve_curation.py --run-dir <run-dir> --lang en # ou ko
+```
+
+## Prise en charge de Python
+
+`sprite-gen` prend en charge CPython 3.10 et versions ultérieures. L’intégration continue s’exécute avec la version minimale prise en charge (3.10) et la version la plus récente couverte (3.14) sur les exécuteurs hébergés par GitHub.
+
+Le démarrage rapide nécessite une installation de Python disposant de modules `venv`/`ensurepip` fonctionnels. Si `python3 -m venv` échoue avant l’installation des paquets dans une distribution locale, utilisez une version standard de CPython parmi les versions prises en charge, puis relancez les mêmes commandes.
+
+## Démarrage rapide
+
+```bash
+# 0. installer les dépendances (Pillow, NumPy) dans un nouvel environnement virtuel
+python3 -m venv .venv && source .venv/bin/activate
+pip install -e .
+
+# 1. préparer une exécution à partir d’une image de base
+python3 scripts/prepare_sprite_run.py --out-dir <run-dir> --character-id <id> --base-image base.png
+
+# 2. générer une image de ligne par état avec la CLI du fournisseur gérée par le moteur
+python3 scripts/generate_sprite_image.py --provider codex \
+ --prompt-file <run-dir>/prompts/<state>.txt \
+ --out <run-dir>/raw/<state>.png \
+ --ref <run-dir>/base-source.png \
+ --ref <run-dir>/references/layout-guides/<state>.png
+# 3. extraire les images
+python3 scripts/extract_sprite_row_frames.py --run-dir <run-dir>
+
+# 4. (facultatif) sélectionner les images dans la webview
+python3 scripts/serve_curation.py --run-dir <run-dir>
+
+# 5. générer l’atlas d’exécution
+python3 scripts/compose_sprite_atlas.py --run-dir <run-dir>
+```
+
+### Modification d’une feuille terminée
+
+Lorsqu’il ne reste que la feuille combinée, reconstruisez un répertoire d’exécution prêt pour l’outil de sélection, puis sélectionnez et exportez :
+
+```bash
+# reconstruire les images : --grid explicite, rectangles --manifest ou détection alpha automatique (par défaut)
+python3 scripts/unpack_atlas_run.py --atlas sheet.png # détection automatique
+python3 scripts/unpack_atlas_run.py --manifest manifest.json # rectangles exacts
+python3 scripts/unpack_atlas_run.py --pngs-dir furniture/ # importer un ensemble de PNG indépendants
+
+# après la sélection, réintégrer les corrections dans les PNG nommés
+python3 scripts/export_curated_pngs.py --run-dir <run-dir>
+```
+
+La sortie est créée par défaut dans un dossier `<source>-curator` facile à retrouver, à côté de l’entrée.
+
+### Création de variantes colorimétriques d’une planche finalisée
+
+Une fois l’atlas composé, remplacez certaines couleurs afin de produire N planches finalisées sans relancer la génération. Par défaut, le pixel art utilise une correspondance exacte ; les illustrations aux contours adoucis peuvent utiliser une tolérance. La géométrie et l’alpha ne changent jamais — le manifeste de base décrit chaque variante.
+
+```bash
+# ébaucher les couleurs opaques (à transformer en spécification de recoloration avec le kind "sprite-gen-recolor")
+python3 -m sprite_gen.cli recolor-palette --base <run-dir>/sprite-sheet-alpha.png --out palette.draft.json
+
+# créer toutes les variantes colorimétriques dans <run-dir>/variants/
+python3 -m sprite_gen.cli recolor --run-dir <run-dir> --spec recolor.spec.json
+
+# comparer par clignotement et adopter dans la vue de curation
+python3 -m sprite_gen.cli curation --run-dir <run-dir>
+```
+
+Contrat complet de spécification/rapport et champ sidecar d’adoption : [`docs/recolor.md`](docs/recolor.md).
+
+### Suppression de l’arrière-plan d’une image importée
+
+Les sprites générés sont détourés à partir de leur propre arrière-plan magenta/vert au sein du pipeline ; ils n’ont donc jamais besoin de cette opération. `cutout` est l’utilitaire d’importation/post-édition : une image arrivée *avec* un arrière-plan uniforme opaque (une icône dessinée à la main, un sprite téléchargé, une capture d’écran) est transformée en PNG transparent propre.
+
+<p align="center">
+ <img src="docs/assets/cutout-demo.png" width="720" alt="cutout : une icône de jeu sur fond blanc transformée en PNG transparent propre, avec les reflets du verre préservés" />
+</p>
+
+```bash
+# routage selon la couleur du coin : blanc/ivoire -> matte, magenta/vert -> moteur d’extraction
+python3 -m sprite_gen.cli cutout icon.png --white-check
+```
+
+L’outil lit la couleur d’arrière-plan dans le coin et effectue le routage (`--key auto|white|magenta|green`) :
+
+- **blanc / ivoire / uni** → matte positionnel. Un remplissage par diffusion depuis un coin ne conserve que l’arrière-plan connecté (les reflets lumineux *à l’intérieur* de l’objet sont préservés, sans créer de trous), puis un alpha doux décontaminé estompe la bordure. Ajustez avec `--strength` (suppression du biseau), `--band` (profondeur du contour) et `--erode`.
+- **incrustation magenta / verte** → le moteur chromatique `extract` vérifié du projet est réutilisé tel quel. Les couleurs d’incrustation n’apparaissent jamais dans les objets ; sa découpe fondée uniquement sur la couleur y est donc sûre — précisément là où la protection par remplissage d’un matte blanc n’est *pas* nécessaire.
+
+`--white-check` écrit des composites cyan/magenta/jaune afin que toute frange restante soit immédiatement visible. Destiné aux arrière-plans uniformes, pas aux arrière-plans complexes ou non uniformes.
+
+Le workflow complet destiné aux agents et ses contrats se trouvent dans [`SKILL.md`](SKILL.md).
+
+## Installation
+
+Depuis les workflows de l’installateur de skills Codex, installez ce dépôt comme skill racine :
+
+```bash
+python3 ~/.codex/skills/.system/skill-installer/scripts/install-skill-from-github.py \
+ --repo aldegad/sprite-gen --path .
+```
+
+### Responsabilité de la génération d’images
+
+La génération adossée à des fournisseurs fait partie de ce moteur (`sprite_gen.gen`), avec `codex` et `grok` comme fournisseurs pris en charge. Le skill général `image-gen` n’est qu’une fine passerelle vers la même commande ; il n’a donc pas besoin d’une seconde implémentation de fournisseur. Consultez [`docs/gen.md`](docs/gen.md) pour le contrat de CLI et de vérification.
+
+## Attribution
+
+Le workflow par lignes de composants s’inspire du skill `hatch-pet`, distribué sous licence Apache-2.0, mais cible des atlas génériques de sprites de jeu et n’inclut aucun package d’animal de compagnie ni aucun élément visuel associé.
+
+## Licence
+
+Apache-2.0
diff --git a/README.ja.md b/README.ja.md
new file mode 100644
index 0000000..364bfe0
--- /dev/null
+++ b/README.ja.md
@@ -0,0 +1,235 @@
+<h1 align="center">sprite-gen</h1>
+
+<p align="center"><b>1枚の絵を入力。ゲーム対応のスプライトアトラスを出力——息づく姿で。</b></p>
+
+<p align="center">
+
+**English** · [한국어](README.ko.md) · [日本語](README.ja.md) · [简体中文](README.zh-Hans.md) · [Español](README.es.md) · [Français](README.fr.md)
+
+</p>
+
+---
+
+## Breathe
+
+静止した待機姿勢は、凍りついて見えます。**Breathe**は、厳選したフレームに決定論的なスカッシュ&ストレッチをベイクし、1つのポーズを生きたループへ変えます。再生成も、再抽出も、追加アートも不要です。必要なのはサイドカーのフィールド1つだけです。
+
+```json
+"breathe": { "depth": 0.05, "breaths": 3 }
+```
+
+- **解剖学を考慮。** エンジンはシルエットを計測します。首のくびれ、首のない塊にある左右対称の目、胴体と付属肢の幅。頭部はすべてのフレームで**ビット単位で同一**に保たれ、翼や腕は押し動かされますが、引き伸ばされることはありません。
+- **ピクセルに忠実。** 整数による行・列のマッピングのみを使用するため、すべての出力フレームは同じグリッド上のクリーンなピクセルアートのままです。1pxの輪郭は1pxのまま維持されます。ワープはシルエットのエッジを保ち、内側の線を基準に階段状の重複を正規化します。
+- **直接つかめる定規。** ライブ再生上で、剛体境界(赤)、身体軸(青)、胴体幅(破線)をドラッグできます。離すとサーバーが解剖構造を再導出し、再計算中もプレビューは呼吸し続けます。
+- **プレビューとバイト単位で同一。** webviewのミラーとPythonのベイクは同じバイト列を生成し、ゴールデンテストによって保証されています。ループ再生で見ているものが、そのままアトラスに収録されます。
+
+<p align="center">
+ <img src="docs/assets/breathe-editor.png" width="760" alt="呼吸領域エディター:ライブ再生上の剛体境界、身体軸、胴体幅の線と、ベイク済みフェーズのフィルムストリップ" />
+</p>
+
+同じ決定論的なベイクは、人型、ブロブ、触手など、あらゆるシルエットの正面、側面、背面に適用できます。
+
+画像モデルに「スプライトシート」を頼むと、何が出てくるかはご存じでしょう。フレームごとに顔が変わるキャラクター、キーイングできない背景、重なり合ってグリッドからずれていくポーズ、そしてゲームエンジンでは実際に使えないPNG。デモとしてはかわいくても、アセットとしては役に立ちません。
+
+`sprite-gen`は、その隔たりを埋めるCodex/Claudeスキルです。**1枚のベース画像**とアクションの一覧を渡すと、行ごとに生成を進め、キャラクターの同一性を固定し、クロマ背景を本物のアルファへ変換し、各ポーズをクリーンな透過フレームとして抽出し、**機械可読な`manifest.json.frame_layout`付き**のランタイムアトラスをベイクします。
+
+そして、生成だけではどうしても仕上がらない最後の10%のために、**キュレーションwebview**があります。フレームを並べて比較し、壊れたものを除外し、回転・スケール・位置を非破壊で微調整し、ループをライブで確認してからベイクできます。パイプラインが作業を担い、あなたは審美眼を発揮できます。
+
+```text
+sprite-request.json → レイアウトガイド + プロンプト → sprite-gen genのステート行
+→ クロマアルファ → 連結成分 → 透過フレーム
+→ sprite-sheet-alpha.png + manifest.json.frame_layout
+```
+
+```mermaid
+flowchart LR
+ REQ["sprite-request.json<br/>(数値のSSoT)"] --> GUIDES["レイアウトガイド<br/>+ プロンプト"]
+ GUIDES --> GEN["sprite-gen gen<br/>ステート行ストリップ"]
+ GEN --> EXTRACT["クロマアルファ →<br/>連結成分"]
+ EXTRACT --> FRAMES["透過フレーム"]
+ FRAMES --> ATLAS["sprite-sheet-alpha.png<br/>+ manifest.json.frame_layout"]
+ FRAMES -. "キュレーションwebview(任意)" .-> ATLAS
+```
+
+> 完全なアーキテクチャ:[`docs/architecture.md`](docs/architecture.md)
+
+## 実際に得られるもの
+
+- **透過スプライトアトラス**(`sprite-sheet-alpha.png`)——本物のアルファを使用し、クロマの縁取りが残っていないことを白背景で検証済みです。
+- **ランタイムマニフェスト**(`manifest.json.frame_layout`)——絶対座標のフレーム矩形、ステートごとのfps、ループフラグを収録しています。エンジンは矩形を参照するだけで、グリッドを推測する必要はありません。
+- **決定論的なカラーバリエーション**——`sprite-gen recolor`は、ベースシートとパレットマップを受け取り、1つのコマンドでN個のバリエーションシートをベイクします(デフォルトではRGBの完全一致。同じ入力からは同じ出力バイト列を生成)。キュレーションwebviewでは点滅比較ができ、採用した名前も記録されます。詳細:[`docs/recolor.md`](docs/recolor.md)。
+- **目で確認できるQA**——ステートごとのGIFとコンタクトシートにより、出荷前に動きを動きとして評価できます。
+- **誠実なラベル**——短く読みやすいアクション(idle、jump、attack、wave)が安定したパスです。周期的な移動(walk/run)は、モーションQAを実際に通過しない限り実験的と明記されます。黙って過剰な約束をすることはありません。
+
+## クロマアルファの品質
+
+抽出処理では、クロマ除去を決定論的に維持します。ソフトアルファ・アンミックスにより、アンチエイリアスされた髪の房や細い輪郭を、カバレッジを解決する前に剥ぎ取ることなく保持します。
+
+<p align="center">
+ <img src="docs/assets/chroma-fullbody-illustration-magenta.png" width="640" alt="全身クロマ比較:マゼンタキー上のイラスト" /><br />
+ <em>イラスト、マゼンタキー:ソース、v1.12.0の剥離、v1.13.0のソフトアルファ・アンミックス。</em>
+</p>
+
+<p align="center">
+ <img src="docs/assets/chroma-fullbody-illustration-green.png" width="640" alt="全身クロマ比較:グリーンキー上のイラスト" /><br />
+ <em>イラスト、グリーンキー:ソース、v1.12.0の剥離、v1.13.0のソフトアルファ・アンミックス。</em>
+</p>
+
+<p align="center">
+ <img src="docs/assets/chroma-fullbody-pixelart-magenta.png" width="640" alt="全身クロマ比較:マゼンタキー上のピクセルアート" /><br />
+ <em>ピクセルアート、マゼンタキー:ソース、v1.12.0の剥離、v1.13.0の二値化出力。</em>
+</p>
+
+<p align="center">
+ <img src="docs/assets/chroma-fullbody-pixelart-green.png" width="640" alt="全身クロマ比較:グリーンキー上のピクセルアート" /><br />
+ <em>ピクセルアート、グリーンキー:ソース、v1.12.0の剥離、v1.13.0の二値化出力。</em>
+</p>
+
+以下の拡大クロップは、全身比較の裏側にあるエッジの詳細を示しています。
+
+![クロマ剥離の前後——イラストの髪の房](docs/assets/chroma-peel-illustration-before-after.png)
+
+![クロマ剥離の前後——ピクセルアートの輪郭](docs/assets/chroma-peel-pixelart-before-after.png)
+
+## Backbone Lattice
+
+AI生成の「ピクセルアート」は、ピクセルアートではありません。ブロックは揺らぎ、エッジにはアンチエイリアスが付き、1つの行の中でも格子がずれていくため、均等なグリッドで切り出すと、あるブロックが隣のブロックへにじみます。コミュニティで使われる解決策は、画像を「unfake」することです。ランレングスからブロックサイズを推定し、再量子化します。しかし、これは各フレームを個別に計測するため、歩行サイクルのセルサイズがフレームごとに膨らんだり縮んだりします。
+
+**Backbone Lattice**は、対象全体に対して1つのグリッドを計測し、すべての切り出しをそのグリッドに固定します。フレームごとのピッチ検出結果を、行全体かつフレーム横断の合意形成に入力し、高調波による誤検出を多数決で排除します。その合意グリッドが、すべての切り出し先となる*バックボーン*です。切り出し位置は実際の色境界に置かれ、計測したピッチに比例する最小セル幅によって、隣接する2つの切り出し位置が同じ帯へ潰れることを防ぎます。バックボーンが1つなので、同じブロックはアニメーション全体で同じサイズを保ち、フレーム間で跳ねることがありません。
+
+結果は、選び抜いた1フレームを目視するのではなく、実際に出荷されたものに対して検証されます。pixel-unfakeの各実行結果は、それぞれのソースストリップから再導出され、ピクセル単位で比較されます。承認した形状はそのまま維持され、変わるのは輪郭と陰影が置かれる位置だけです。それこそがバックボーンの決定するものです。
+
+## キュレーションwebview
+
+生成で90%まで到達できます。webviewは、人間がそれを*出荷可能*な状態へ仕上げる場所です。単独で動作し、Studioやフレームワークには依存せず、スキルがインストールされている場所ならどこでも実行できます(Claude Code Desktop、Codexアプリ、通常のターミナル)。
+
+![キュレーションwebview——キャラクター](docs/assets/demo-character.gif)
+
+- **ステートごとに2行:** 上段は**再生シーケンス**、下段は**候補プール**です(たとえば、2回目や3回目に生成した別テイク)。フレームの⠿グリップをドラッグしてシーケンスを並べ替えたり、プールから切り出しを上へ移したりできます。複数テイクの最良フレームを組み合わせて、クリーンな1つの走行ループを再構築できます。配置は保存されるため、再度開いたときに復元されます。
+- フレームごとの**非破壊変形**:ドラッグ = 移動、ホイール = 拡大縮小、上部ハンドル = 回転、左下 = シアー、さらに左右反転した出力用の水平反転トグルがあります。編集内容は`curation.json`サイドカーに保存され、ソースPNGが書き換えられることはありません。合成ステップが結果を決定論的にベイクします。プレビューとベイクは同じアフィン行列を共有するため、位置合わせしたとおりの結果が得られます。
+- **ライブプレビュー**は、ステートのfpsでシーケンスをアニメーション再生します。再生・一時停止、フレーム単位のステップ移動、0.25×~4×の速度調整に対応しています。
+- スプライト専用ではありません。`unpack_atlas_run.py --pngs-dir`で画像候補(アイコン、ロゴ、生成した下書き)の任意のフォルダーを指定すれば、汎用的な勝者選択ビューとして使えます。
+
+### アイソメトリック地面グリッド
+
+アイソメトリックセットでは、webviewが床グリッド(`meta.json`のtile/anchorから取得)をオーバーレイするため、シアーハンドルを使って家具をひし形の軸へスナップできます。
+
+![キュレーションwebview——アイソメトリック家具](docs/assets/demo-furniture.gif)
+
+<img src="docs/assets/curator-iso.png" width="520" alt="アイソメトリック地面グリッドのオーバーレイ" />
+
+### 言語
+
+webviewには英語と韓国語が付属しています。起動時に`--lang en|ko`を渡すか、アプリ内の切り替えを使用してください。
+
+```bash
+python3 scripts/serve_curation.py --run-dir <run-dir> --lang en # またはko
+```
+
+## Pythonサポート
+
+`sprite-gen`はCPython 3.10以降をサポートしています。CIは、GitHubホストランナー上でサポート対象の最小バージョン(3.10)と最新の対象バージョン(3.14)を実行します。
+
+クイックスタートには、`venv`/`ensurepip`が正常に動作するPython環境が必要です。ローカルディストリビューションで、パッケージのインストール前に`python3 -m venv`が失敗する場合は、サポート対象バージョンの標準CPythonビルドを使用し、同じコマンドを再実行してください。
+
+## クイックスタート
+
+```bash
+# 0. 新しい仮想環境に依存関係(Pillow、NumPy)をインストール
+python3 -m venv .venv && source .venv/bin/activate
+pip install -e .
+
+# 1. ベース画像から実行環境を準備
+python3 scripts/prepare_sprite_run.py --out-dir <run-dir> --character-id <id> --base-image base.png
+
+# 2. エンジン管理のプロバイダーCLIでステートごとに1枚の行画像を生成
+python3 scripts/generate_sprite_image.py --provider codex \
+ --prompt-file <run-dir>/prompts/<state>.txt \
+ --out <run-dir>/raw/<state>.png \
+ --ref <run-dir>/base-source.png \
+ --ref <run-dir>/references/layout-guides/<state>.png
+# 3. フレームを抽出
+python3 scripts/extract_sprite_row_frames.py --run-dir <run-dir>
+
+# 4. (任意)webviewでフレームをキュレーション
+python3 scripts/serve_curation.py --run-dir <run-dir>
+
+# 5. ランタイムアトラスをベイク
+python3 scripts/compose_sprite_atlas.py --run-dir <run-dir>
+```
+
+### 完成済みシートの編集
+
+結合済みシートだけが残っている場合は、キュレーター対応の実行ディレクトリを再構築し、キュレーションしてエクスポートします。
+
+```bash
+# フレームを再構築:明示的な--grid、--manifestの矩形、またはアルファ自動検出(デフォルト)
+python3 scripts/unpack_atlas_run.py --atlas sheet.png # 自動検出
+python3 scripts/unpack_atlas_run.py --manifest manifest.json # 正確な矩形
+python3 scripts/unpack_atlas_run.py --pngs-dir furniture/ # 個別PNGセットをインポート
+
+# キュレーション後、修正内容を名前付きPNGへベイク
+python3 scripts/export_curated_pngs.py --run-dir <run-dir>
+```
+
+出力先はデフォルトで、入力の隣に作成される見つけやすい `<source>-curator` フォルダーです。
+
+### 完成したシートのカラーバリエーションを焼き込む
+
+アトラスを構成した後、生成を再実行せずに、選択した色を置き換えて N 枚の完成シートを作成できます。ドット絵ではデフォルトで完全一致を使用し、ソフトエッジのアートでは許容差を指定できます。ジオメトリとアルファは一切変化せず、ベースマニフェストがすべてのバリアントを記述します。
+
+```bash
+# 不透明色のドラフトを作成(kind が "sprite-gen-recolor" の recolor spec に編集)
+python3 -m sprite_gen.cli recolor-palette --base <run-dir>/sprite-sheet-alpha.png --out palette.draft.json
+
+# すべてのカラーバリエーションを <run-dir>/variants/ に焼き込む
+python3 -m sprite_gen.cli recolor --run-dir <run-dir> --spec recolor.spec.json
+
+# キュレーションビューで点滅比較し、採用する
+python3 -m sprite_gen.cli curation --run-dir <run-dir>
+```
+
+完全な spec/report コントラクトと採用用サイドカーフィールドについては、[`docs/recolor.md`](docs/recolor.md) を参照してください。
+
+### インポートした画像から背景を切り抜く
+
+生成されたスプライトはパイプライン内で固有のマゼンタ/グリーン背景を基準に処理されるため、この操作は不要です。`cutout` はインポート/後編集用ユーティリティです。不透明で均一な背景が付いた状態で取り込まれた画像(手描きアイコン、ダウンロードしたスプライト、スクリーンショット)を、きれいな透過 PNG に変換します。
+
+<p align="center">
+ <img src="docs/assets/cutout-demo.png" width="720" alt="cutout:白背景のゲームアイコンを、ガラスのハイライトを保持したきれいな透過 PNG に変換" />
+</p>
+
+```bash
+# コーナーの色に応じて振り分け:白/アイボリー -> matte、マゼンタ/グリーン -> extract エンジン
+python3 -m sprite_gen.cli cutout icon.png --white-check
+```
+
+コーナーの背景色を読み取り、処理を振り分けます(`--key auto|white|magenta|green`)。
+
+- **白/アイボリー/単色** → position matte。コーナーからの flood-fill により、接続している背景だけを保持します(オブジェクトの*内部*にある明るいハイライトは穴にならず残ります)。その後、色かぶりを除去したソフトアルファで境界をぼかします。`--strength`(ベベル除去)、`--band`(エッジ深度)、`--erode` で調整できます。
+- **マゼンタ/グリーンキー** → プロジェクトで検証済みの `extract` クロマエンジンをそのまま再利用します。キー色はオブジェクト内に現れないため、色だけに基づく切り抜きを安全に行えます。これはまさに、白マットの flood-fill ガードが*不要*な場合です。
+
+`--white-check` はシアン/マゼンタ/イエローの合成画像を書き出すため、残ったフリンジが目立って確認できます。均一な背景向けであり、複雑または不均一な背景には適していません。
+
+エージェント向けの完全なワークフローとコントラクトは、[`SKILL.md`](SKILL.md) にあります。
+
+## インストール
+
+Codex skill installer ワークフローから、このリポジトリをルートスキルとしてインストールします。
+
+```bash
+python3 ~/.codex/skills/.system/skill-installer/scripts/install-skill-from-github.py \
+ --repo aldegad/sprite-gen --path .
+```
+
+### 画像生成の所有権
+
+プロバイダーを利用した生成はこのエンジン(`sprite_gen.gen`)の一部であり、サポートされるプロバイダーは `codex` と `grok` です。汎用の `image-gen` スキルは同じコマンドへの薄いシャトルにすぎないため、2 つ目のプロバイダー実装は必要ありません。CLI と検証コントラクトについては、[`docs/gen.md`](docs/gen.md) を参照してください。
+
+## 帰属表示
+
+コンポーネント行ワークフローは、Apache-2.0 ライセンスの `hatch-pet` スキルから着想を得ていますが、汎用ゲームスプライトアトラスを対象としており、ペットパッケージやペットのビジュアルアセットは一切含まれていません。
+
+## ライセンス
+
+Apache-2.0
diff --git a/README.ko.md b/README.ko.md
new file mode 100644
index 0000000..a932750
--- /dev/null
+++ b/README.ko.md
@@ -0,0 +1,235 @@
+<h1 align="center">sprite-gen</h1>
+
+<p align="center"><b>그림 한 장을 넣으면, 바로 게임에 쓸 수 있는 스프라이트 아틀라스가 나옵니다 — 숨을 쉬면서.</b></p>
+
+<p align="center">
+
+[English](README.md) · **한국어** · [日本語](README.ja.md) · [简体中文](README.zh-Hans.md) · [Español](README.es.md) · [Français](README.fr.md)
+
+</p>
+
+---
+
+## 호흡
+
+정지된 대기 자세는 얼어붙은 것처럼 보입니다. **호흡**은 하나의 자세를 살아 있는 루프로 바꿉니다 — 선별한 프레임 위에 결정론적 스쿼시 앤 스트레치(squash & stretch)를 베이크합니다. 재생성도, 재추출도, 추가 아트도 필요 없습니다. 사이드카 필드 하나면 됩니다.
+
+```json
+"breathe": { "depth": 0.05, "breaths": 3 }
+```
+
+- **해부학 인식.** 엔진이 실루엣을 측정합니다. 목의 잘록한 지점, 목이 없는 덩어리의 대칭적인 눈 한 쌍, 몸통과 부속지의 너비를 분석합니다. 머리는 모든 프레임에서 **바이트 단위로 동일하게** 유지되며, 날개와 팔은 늘어나지 않고 밀려납니다.
+- **픽셀 그대로.** 정수 행/열 매핑만 사용하므로 모든 출력 프레임이 같은 격자 위의 깔끔한 픽셀 아트로 유지됩니다. 1px 외곽선은 계속 1px 외곽선입니다. 워프는 안쪽 선을 기준으로 실루엣 가장자리를 보존하고 계단 현상의 중복을 정규화합니다.
+- **직접 잡을 수 있는 자.** 실시간 재생 화면에서 강체 경계선(빨간색), 몸체 축(파란색), 몸통 너비(점선)를 직접 드래그할 수 있습니다. 놓는 순간 서버가 해부 구조를 다시 계산하며, 재계산 중에도 미리보기는 계속 숨을 쉽니다.
+- **바이트 단위로 동일한 미리보기.** 웹뷰 미러와 Python 베이크는 동일한 바이트를 생성하며, 골든 테스트로 이를 보장합니다. 루프로 보고 있는 바로 그 결과가 아틀라스에 그대로 담깁니다.
+
+<p align="center">
+ <img src="docs/assets/breathe-editor.png" width="760" alt="호흡 영역 편집기: 실시간 재생 화면 위의 강체 경계선, 몸체 축, 몸통 너비 선과 베이크된 위상 필름스트립" />
+</p>
+
+같은 결정론적 베이크는 사람형, 덩어리형, 촉수형 등 어떤 실루엣의 정면, 측면, 후면에도 적용됩니다.
+
+이미지 모델에 "스프라이트 시트"를 요청하면 어떤 결과가 나오는지 아실 겁니다. 프레임마다 얼굴이 달라지는 캐릭터, 키잉으로 제거되지 않는 배경, 서로 겹치고 격자를 벗어나는 자세, 그리고 게임 엔진에서 실제로 사용할 수 없는 PNG가 나옵니다. 귀여운 데모지만 쓸모없는 에셋입니다.
+
+`sprite-gen`은 그 간극을 메우는 Codex/Claude 스킬입니다. **기본 이미지 한 장**과 동작 목록을 주면 행 단위로 생성을 진행하고, 캐릭터의 정체성을 고정하고, 크로마 배경을 실제 알파로 제거하고, 각 자세를 깔끔한 투명 프레임으로 추출한 뒤 **기계가 읽을 수 있는 `manifest.json.frame_layout`을 포함한** 런타임 아틀라스를 베이크합니다.
+
+생성만으로는 제대로 완성되지 않는 마지막 10%를 위해 **선별 웹뷰**도 제공합니다. 프레임을 나란히 비교하고, 망가진 프레임을 제외하고, 회전·크기·위치를 비파괴 방식으로 미세 조정하고, 루프를 실시간으로 확인한 뒤 베이크할 수 있습니다. 파이프라인이 노동을 맡고, 여러분은 안목을 발휘하면 됩니다.
+
+```text
+sprite-request.json → 레이아웃 가이드 + 프롬프트 → sprite-gen gen 상태 행
+→ 크로마 알파 → 연결 요소 → 투명 프레임
+→ sprite-sheet-alpha.png + manifest.json.frame_layout
+```
+
+```mermaid
+flowchart LR
+ REQ["sprite-request.json<br/>(숫자형 SSoT)"] --> GUIDES["레이아웃 가이드<br/>+ 프롬프트"]
+ GUIDES --> GEN["sprite-gen gen<br/>상태 행 스트립"]
+ GEN --> EXTRACT["크로마 알파 →<br/>연결 요소"]
+ EXTRACT --> FRAMES["투명 프레임"]
+ FRAMES --> ATLAS["sprite-sheet-alpha.png<br/>+ manifest.json.frame_layout"]
+ FRAMES -. "선별 웹뷰(선택 사항)" .-> ATLAS
+```
+
+> 전체 아키텍처: [`docs/architecture.md`](docs/architecture.md)
+
+## 실제로 얻는 결과물
+
+- **투명 스프라이트 아틀라스** (`sprite-sheet-alpha.png`) — 실제 알파를 사용하고 남은 크로마 테두리가 없으며, 흰색 배경을 기준으로 검증됩니다.
+- **런타임 매니페스트** (`manifest.json.frame_layout`) — 절대 좌표 프레임 사각형과 상태별 fps 및 루프 플래그를 제공합니다. 엔진은 사각형 영역을 샘플링할 뿐, 격자를 추측하지 않습니다.
+- **결정론적 색상 변형** — `sprite-gen recolor`는 기본 시트와 팔레트 맵을 받아 한 번의 명령으로 N개의 변형 시트를 베이크합니다. 기본적으로 정확한 RGB 일치를 사용하며, 입력이 같으면 출력 바이트도 같습니다. 선별 웹뷰는 변형을 깜박이며 비교하고 채택한 이름을 기록합니다. 자세한 내용: [`docs/recolor.md`](docs/recolor.md).
+- **눈으로 확인할 수 있는 QA** — 상태별 GIF와 콘택트 시트를 제공하므로, 무엇이든 출시하기 전에 움직임을 움직임 자체로 평가할 수 있습니다.
+- **정직한 표기** — 짧고 명확한 동작(idle, jump, attack, wave)은 안정적인 경로입니다. 주기적 이동 동작(walk/run)은 모션 QA를 실제로 통과하지 않는 한 실험적 기능으로 표시됩니다. 조용히 과장하지 않습니다.
+
+## 크로마 알파 품질
+
+추출기는 크로마 정리를 결정론적으로 유지합니다. 소프트 알파 언믹스는 커버리지를 계산하기 전에 앤티앨리어싱된 머리카락과 얇은 외곽선을 벗겨내지 않고 보존합니다.
+
+<p align="center">
+ <img src="docs/assets/chroma-fullbody-illustration-magenta.png" width="640" alt="전신 크로마 비교: 마젠타 키 위의 일러스트레이션" /><br />
+ <em>일러스트레이션, 마젠타 키: 원본, v1.12.0 필, v1.13.0 소프트 알파 언믹스.</em>
+</p>
+
+<p align="center">
+ <img src="docs/assets/chroma-fullbody-illustration-green.png" width="640" alt="전신 크로마 비교: 그린 키 위의 일러스트레이션" /><br />
+ <em>일러스트레이션, 그린 키: 원본, v1.12.0 필, v1.13.0 소프트 알파 언믹스.</em>
+</p>
+
+<p align="center">
+ <img src="docs/assets/chroma-fullbody-pixelart-magenta.png" width="640" alt="전신 크로마 비교: 마젠타 키 위의 픽셀 아트" /><br />
+ <em>픽셀 아트, 마젠타 키: 원본, v1.12.0 필, v1.13.0 이진화 출력.</em>
+</p>
+
+<p align="center">
+ <img src="docs/assets/chroma-fullbody-pixelart-green.png" width="640" alt="전신 크로마 비교: 그린 키 위의 픽셀 아트" /><br />
+ <em>픽셀 아트, 그린 키: 원본, v1.12.0 필, v1.13.0 이진화 출력.</em>
+</p>
+
+아래의 확대 이미지는 전신 비교 결과를 만들어낸 가장자리의 세부 모습을 보여줍니다.
+
+![크로마 필 전후 — 일러스트레이션 머리카락](docs/assets/chroma-peel-illustration-before-after.png)
+
+![크로마 필 전후 — 픽셀 아트 외곽선](docs/assets/chroma-peel-pixelart-before-after.png)
+
+## 백본 격자
+
+AI가 생성한 "픽셀 아트"는 픽셀 아트가 아닙니다. 블록이 흔들리고, 가장자리에 앤티앨리어싱이 남으며, 하나의 행 안에서도 격자가 떠다닙니다. 따라서 균일한 격자로 자르면 한 블록이 다음 블록에 번져 들어갑니다. 커뮤니티에서 사용하는 해결책은 이미지를 "가짜 픽셀 아트가 아니게" 만드는 것입니다. 연속 길이에서 블록 크기를 추측하고 다시 양자화하는 방식입니다. 하지만 이 방법은 각 프레임을 개별적으로 측정하기 때문에 걷기 사이클의 셀 크기가 프레임마다 숨 쉬듯 달라집니다.
+
+**백본 격자**는 피사체 전체에 사용할 하나의 격자를 측정하고 모든 컷을 그 격자에 고정합니다. 프레임별 피치 감지 결과를 행 전체와 프레임 전체의 합의 과정에 입력해 배수 관계를 잘못 감지한 결과를 배제합니다. 이렇게 합의된 격자가 모든 컷이 스냅되는 *백본*입니다. 컷은 실제 색상 경계에 놓이며, 측정된 피치에 비례하는 최소 셀 너비를 적용해 인접한 두 컷이 같은 밴드로 겹치는 일을 방지합니다. 하나의 백본을 사용하므로 애니메이션 전체에서 동일한 블록은 프레임마다 튀지 않고 같은 크기를 유지합니다.
+
+결과는 손으로 고른 프레임을 눈대중으로 확인하는 대신 실제 출시된 결과를 기준으로 검증합니다. 모든 픽셀 언페이크 실행 결과를 자체 원본 스트립에서 다시 도출해 픽셀 단위로 비교합니다. 승인한 형태는 그대로 유지되며, 바뀌는 것은 외곽선과 음영이 놓이는 위치뿐입니다. 그리고 그것이 바로 백본이 결정하는 부분입니다.
+
+## 선별 웹뷰
+
+생성으로 90%까지 완성할 수 있습니다. 웹뷰는 사람이 결과를 *출시 가능한 상태*로 만드는 곳입니다. 독립 실행형이며 Studio나 프레임워크에 의존하지 않고, 스킬이 설치된 모든 환경(Claude Code Desktop, Codex 앱, 일반 터미널)에서 실행됩니다.
+
+![선별 웹뷰 — 캐릭터](docs/assets/demo-character.gif)
+
+- **상태별 두 개의 행:** 위에는 **재생 시퀀스**, 아래에는 **후보 풀**이 표시됩니다(예: 두 번째 또는 세 번째 생성 시안). 프레임의 ⠿ 핸들을 드래그해 시퀀스 순서를 바꾸거나 풀의 컷을 위로 끌어올릴 수 있습니다. 여러 시안의 최적 프레임을 조합해 깔끔한 달리기 루프 하나를 다시 만들 수 있습니다. 배치 상태는 저장되므로 다시 열어도 그대로 복원됩니다.
+- 프레임별 **비파괴 변환:** 드래그 = 이동, 휠 = 크기 조절, 위쪽 핸들 = 회전, 왼쪽 아래 = 전단 변형이며, 좌우가 뒤집힌 출력을 위한 수평 반전 토글도 제공합니다. 편집 내용은 `curation.json` 사이드카에 저장됩니다. 원본 PNG는 절대 다시 쓰지 않으며, 합성 단계에서 결과를 결정론적으로 베이크합니다. 미리보기와 베이크가 하나의 아핀 행렬을 공유하므로 정렬한 그대로 결과를 얻습니다.
+- **실시간 미리보기**는 상태의 fps에 맞춰 시퀀스를 애니메이션으로 재생하며, 재생/일시정지, 프레임 단위 이동, 0.25×–4× 속도 조절 기능을 제공합니다.
+- 스프라이트만을 위한 도구가 아닙니다. `unpack_atlas_run.py --pngs-dir`로 이미지 후보 폴더(아이콘, 로고, 생성된 초안)를 지정하면 범용 우승작 선택 화면으로 사용할 수 있습니다.
+
+### 아이소메트릭 바닥 격자
+
+아이소메트릭 세트에서는 웹뷰가 바닥 격자(`meta.json`의 타일/앵커 정보)를 오버레이하므로, 전단 핸들을 사용해 가구를 다이아몬드 축에 맞춰 스냅할 수 있습니다.
+
+![선별 웹뷰 — 아이소메트릭 가구](docs/assets/demo-furniture.gif)
+
+<img src="docs/assets/curator-iso.png" width="520" alt="아이소메트릭 바닥 격자 오버레이" />
+
+### 언어
+
+웹뷰는 영어와 한국어를 제공합니다. 실행할 때 `--lang en|ko`를 전달하거나 앱 내 토글을 사용하세요.
+
+```bash
+python3 scripts/serve_curation.py --run-dir <run-dir> --lang en # 또는 ko
+```
+
+## Python 지원
+
+`sprite-gen`은 CPython 3.10 이상을 지원합니다. CI는 GitHub 호스팅 러너에서 지원되는 최소 버전(3.10)과 최신 검사 대상 버전(3.14)을 실행합니다.
+
+빠른 시작에는 `venv`/`ensurepip`가 정상적으로 작동하는 Python 설치가 필요합니다. 로컬 배포판에서 패키지를 설치하기도 전에 `python3 -m venv`가 실패한다면, 지원되는 버전의 표준 CPython 빌드를 사용해 같은 명령을 다시 실행하세요.
+
+## 빠른 시작
+
+```bash
+# 0. 새 가상 환경에 의존성(Pillow, NumPy) 설치
+python3 -m venv .venv && source .venv/bin/activate
+pip install -e .
+
+# 1. 기본 이미지에서 실행 준비
+python3 scripts/prepare_sprite_run.py --out-dir <run-dir> --character-id <id> --base-image base.png
+
+# 2. 엔진이 소유한 제공자 CLI로 상태별 행 이미지 하나씩 생성
+python3 scripts/generate_sprite_image.py --provider codex \
+ --prompt-file <run-dir>/prompts/<state>.txt \
+ --out <run-dir>/raw/<state>.png \
+ --ref <run-dir>/base-source.png \
+ --ref <run-dir>/references/layout-guides/<state>.png
+# 3. 프레임 추출
+python3 scripts/extract_sprite_row_frames.py --run-dir <run-dir>
+
+# 4. (선택 사항) 웹뷰에서 프레임 선별
+python3 scripts/serve_curation.py --run-dir <run-dir>
+
+# 5. 런타임 아틀라스 베이크
+python3 scripts/compose_sprite_atlas.py --run-dir <run-dir>
+```
+
+### 완성된 시트 편집하기
+
+결합된 시트만 남아 있다면 선별 도구에서 사용할 수 있는 실행 디렉터리를 다시 만든 뒤, 선별하고 내보내세요.
+
+```bash
+# 프레임 재구성: 명시적 --grid, --manifest 사각형 또는 알파 자동 감지(기본값)
+python3 scripts/unpack_atlas_run.py --atlas sheet.png # 자동 감지
+python3 scripts/unpack_atlas_run.py --manifest manifest.json # 정확한 사각형
+python3 scripts/unpack_atlas_run.py --pngs-dir furniture/ # 개별 PNG 세트 가져오기
+
+# 선별 후 수정 사항을 이름이 지정된 PNG에 다시 베이크
+python3 scripts/export_curated_pngs.py --run-dir <run-dir>
+```
+
+출력은 기본적으로 입력 파일 옆의 찾기 쉬운 `<source>-curator` 폴더에 저장됩니다.
+
+### 완성된 시트의 색상 변형 베이킹
+
+아틀라스 구성이 끝나면 생성을 다시 실행하지 않고 선택한 색상을 교체해 N개의 완성된 시트를 만들 수 있습니다. 도트 아트는 기본적으로 정확히 일치하는 색상을 사용하며, 가장자리가 부드러운 아트에는 허용 오차를 적용할 수 있습니다. 지오메트리와 알파는 절대 움직이지 않으며, 기본 매니페스트가 모든 변형을 기술합니다.
+
+```bash
+# 불투명 색상 초안 생성(kind가 "sprite-gen-recolor"인 리컬러 명세로 편집)
+python3 -m sprite_gen.cli recolor-palette --base <run-dir>/sprite-sheet-alpha.png --out palette.draft.json
+
+# 모든 색상 변형을 <run-dir>/variants/에 베이킹
+python3 -m sprite_gen.cli recolor --run-dir <run-dir> --spec recolor.spec.json
+
+# 큐레이션 뷰에서 깜빡임 비교 후 채택
+python3 -m sprite_gen.cli curation --run-dir <run-dir>
+```
+
+전체 명세/리포트 계약과 채택 사이드카 필드: [`docs/recolor.md`](docs/recolor.md).
+
+### 가져온 이미지에서 배경 잘라내기
+
+생성된 스프라이트는 파이프라인 내부에서 자체 마젠타/그린 배경을 기준으로 키잉되므로 이 작업이 필요하지 않습니다. `cutout`은 가져오기/후편집 유틸리티입니다. 불투명한 단색 배경이 *포함된 채* 들어온 이미지(손으로 그린 아이콘, 다운로드한 스프라이트, 스크린샷)를 깔끔한 투명 PNG로 변환합니다.
+
+<p align="center">
+ <img src="docs/assets/cutout-demo.png" width="720" alt="cutout: 흰색 배경의 게임 아이콘을 유리 하이라이트가 보존된 깔끔한 투명 PNG로 변환" />
+</p>
+
+```bash
+# 모서리 색상을 기준으로 라우팅: 흰색/아이보리 -> 매트, 마젠타/그린 -> 추출 엔진
+python3 -m sprite_gen.cli cutout icon.png --white-check
+```
+
+모서리의 배경색을 읽어 라우팅합니다(`--key auto|white|magenta|green`).
+
+- **흰색 / 아이보리 / 단색** → 위치 기반 매트. 모서리 플러드 필은 연결된 배경만 유지하므로 객체 *내부*의 밝은 하이라이트는 구멍이 뚫리지 않고 살아남습니다. 그런 다음 색 오염을 제거한 부드러운 알파가 테두리를 자연스럽게 흐립니다. `--strength`(베벨 제거), `--band`(가장자리 깊이), `--erode`로 조정하세요.
+- **마젠타 / 그린 키** → 프로젝트에서 검증된 `extract` 크로마 엔진을 그대로 재사용합니다. 키 색상은 객체에 절대 나타나지 않으므로 색상만으로 잘라내도 안전합니다. 이는 흰색 매트의 플러드 필 보호 장치가 *필요하지 않은* 바로 그 경우입니다.
+
+`--white-check`는 시안/마젠타/옐로 합성 이미지를 생성하여 남은 테두리가 선명하게 드러나게 합니다. 균일한 배경용이며, 복잡하거나 불균일한 배경에는 적합하지 않습니다.
+
+에이전트용 전체 워크플로와 계약은 [`SKILL.md`](SKILL.md)에 있습니다.
+
+## 설치
+
+Codex 스킬 설치 워크플로에서 이 저장소를 루트 스킬로 설치합니다.
+
+```bash
+python3 ~/.codex/skills/.system/skill-installer/scripts/install-skill-from-github.py \
+ --repo aldegad/sprite-gen --path .
+```
+
+### 이미지 생성 소유권
+
+프로바이더 기반 생성은 이 엔진(`sprite_gen.gen`)의 일부이며, 지원되는 프로바이더는 `codex`와 `grok`입니다. 범용 `image-gen` 스킬은 같은 명령으로 전달하는 얇은 셔틀일 뿐이므로 별도의 프로바이더 구현이 필요하지 않습니다. CLI와 검증 계약은 [`docs/gen.md`](docs/gen.md)를 참조하세요.
+
+## 저작자 표시
+
+컴포넌트 행 워크플로는 Apache-2.0 라이선스의 `hatch-pet` 스킬에서 영감을 얻었지만, 범용 게임 스프라이트 아틀라스를 대상으로 하며 펫 패키지나 펫 시각 에셋은 포함하지 않습니다.
+
+## 라이선스
+
+Apache-2.0
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..b8f14b0
--- /dev/null
+++ b/README.md
@@ -0,0 +1,251 @@
+<h1 align="center">sprite-gen</h1>
+
+<p align="center"><b>One drawing in. A game-ready sprite atlas out — breathing.</b></p>
+
+<p align="center">
+
+**English** · [한국어](README.ko.md) · [日本語](README.ja.md) · [简体中文](README.zh-Hans.md) · [Español](README.es.md) · [Français](README.fr.md)
+
+</p>
+
+---
+
+## Breathe
+
+A still idle reads as frozen. **Breathe** turns a single pose into a living loop — deterministic squash & stretch baked on top of your curated frames. No regeneration, no re-extraction, no extra art. One sidecar field:
+
+```json
+"breathe": { "depth": 0.05, "breaths": 3 }
+```
+
+- **Anatomy-aware.** The engine measures the silhouette: neck bottleneck, symmetric eye pair on neckless blobs, torso-vs-appendage width. Heads stay **bit-identical** across every frame; wings and arms get pushed, never stretched.
+- **Pixel-true.** Integer row/column mapping only — every output frame is still clean pixel art on the same grid. A 1px outline stays a 1px outline: the warp preserves silhouette edges and normalizes staircase doubling, anchored on the inner line.
+- **A ruler you can grab.** Drag the rigid boundary (red), the body axis (blue), and the torso width (dashed) right on the live playback. The server re-derives the anatomy on release — and the preview keeps breathing while it recalculates.
+- **Byte-identical preview.** The webview mirror and the Python bake produce the same bytes, enforced by golden tests. What you watch looping is exactly what ships in the atlas.
+
+<p align="center">
+ <img src="docs/assets/breathe-editor.png" width="760" alt="breathe region editor: rigid boundary, body axis and torso width lines over live playback, with the baked phase filmstrip" />
+</p>
+
+The same deterministic bake applies to front, side, and back views of any silhouette, including humanoids, blobs, and tentacles.
+
+Ask an image model for a "sprite sheet" and you know what you get: a character whose face changes every frame, a background that won't key out, poses that overlap and drift off-grid, and a PNG your game engine can't actually consume. Cute demo, useless asset.
+
+`sprite-gen` is a Codex/Claude skill that closes that gap. Give it **one base image** and a list of actions — it drives the 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`**.
+
+And for the last 10% that generation never gets right, there's a **curation webview**: compare frames side by side, reject the broken ones, nudge rotation/scale/position non-destructively, watch the loop live — then bake. The pipeline does the labor; you keep the taste.
+
+```text
+sprite-request.json → layout guides + prompts → sprite-gen gen state rows
+→ chroma alpha → connected components → transparent frames
+→ sprite-sheet-alpha.png + manifest.json.frame_layout
+```
+
+```mermaid
+flowchart LR
+ REQ["sprite-request.json<br/>(numeric SSoT)"] --> GUIDES["layout guides<br/>+ prompts"]
+ GUIDES --> GEN["sprite-gen gen<br/>state row strips"]
+ GEN --> EXTRACT["chroma alpha →<br/>connected components"]
+ EXTRACT --> FRAMES["transparent frames"]
+ FRAMES --> ATLAS["sprite-sheet-alpha.png<br/>+ manifest.json.frame_layout"]
+ FRAMES -. "curation webview (optional)" .-> ATLAS
+```
+
+> Full architecture: [`docs/architecture.md`](docs/architecture.md)
+
+## What you actually get
+
+- **A transparent sprite atlas** (`sprite-sheet-alpha.png`) — real alpha, no leftover chroma fringe, verified against white backgrounds.
+- **A runtime manifest** (`manifest.json.frame_layout`) — absolute frame rectangles, per-state fps and loop flags. Your engine samples rectangles; it never guesses a grid.
+- **Deterministic colourways** — `sprite-gen recolor` takes the base sheet plus a palette map and bakes N variant sheets in one command (exact RGB match by default; same input, same output bytes). The curation webview blink-compares them and records the adopted name. Detail: [`docs/recolor.md`](docs/recolor.md).
+- **QA you can watch** — per-state GIFs and contact sheets, so motion is judged as motion before anything ships.
+- **Honest labels** — short readable actions (idle, jump, attack, wave) are the stable path; cyclic locomotion (walk/run) is marked experimental unless motion QA actually passes. No silent overpromising.
+
+## Chroma alpha quality
+
+The extractor keeps chroma cleanup deterministic: soft-alpha unmix preserves antialiased hair strands and thin outlines instead of peeling them away before coverage can be solved.
+
+<p align="center">
+ <img src="docs/assets/chroma-fullbody-illustration-magenta.png" width="640" alt="full-body chroma comparison: illustration on magenta key" /><br />
+ <em>Illustration, magenta key: source, v1.12.0 peel, v1.13.0 soft-alpha unmix.</em>
+</p>
+
+<p align="center">
+ <img src="docs/assets/chroma-fullbody-illustration-green.png" width="640" alt="full-body chroma comparison: illustration on green key" /><br />
+ <em>Illustration, green key: source, v1.12.0 peel, v1.13.0 soft-alpha unmix.</em>
+</p>
+
+<p align="center">
+ <img src="docs/assets/chroma-fullbody-pixelart-magenta.png" width="640" alt="full-body chroma comparison: pixel art on magenta key" /><br />
+ <em>Pixel art, magenta key: source, v1.12.0 peel, v1.13.0 binarized output.</em>
+</p>
+
+<p align="center">
+ <img src="docs/assets/chroma-fullbody-pixelart-green.png" width="640" alt="full-body chroma comparison: pixel art on green key" /><br />
+ <em>Pixel art, green key: source, v1.12.0 peel, v1.13.0 binarized output.</em>
+</p>
+
+The close-up crops below show the edge detail behind the full-body comparisons.
+
+![chroma peel before and after — illustrated hair strand](docs/assets/chroma-peel-illustration-before-after.png)
+
+![chroma peel before and after — pixel-art outline](docs/assets/chroma-peel-pixelart-before-after.png)
+
+## Backbone Lattice
+
+AI-generated "pixel art" is not pixel art. The blocks wobble, the edges carry antialiasing, and the lattice drifts within a single row, so cutting on an even grid smears one block into the next. The community fix is to "unfake" the image — guess the block size from run lengths and re-quantize — but that measures each frame on its own, so a walk cycle's cell size breathes frame to frame.
+
+**Backbone Lattice** measures one grid for the whole subject and holds every cut to it. Per-frame pitch detection feeds a row-wide, cross-frame consensus that outvotes harmonic misdetections; that consensus grid is the *backbone* every cut snaps to. Cuts land on actual colour boundaries, and a minimum cell width proportional to the measured pitch keeps two neighbouring cuts from ever collapsing onto the same band. One backbone, so the same block stays the same size across a whole animation instead of jumping between frames.
+
+The result is verified against what shipped, not eyeballed on a hand-picked frame: every pixel-unfake run is re-derived from its own source strip and compared pixel by pixel. The shape you approved stays the shape you get; what changes is only where outlines and shading land, which is exactly what the backbone decides.
+
+## Curation webview
+
+Generation gets you 90%. The webview is where a human takes it to *shipped* — standalone, no Studio or framework dependency, runs anywhere the skill is installed (Claude Code Desktop, the Codex app, a plain terminal).
+
+![curation webview — characters](docs/assets/demo-character.gif)
+
+- **Two rows per state:** the **play sequence** on top and a **candidate pool** below (e.g. a second or third generated take). Drag a frame's ⠿ grip to reorder the sequence, or pull a cut up from the pool — rebuild one clean run loop from the best frames across takes. The arrangement is saved, so reopening restores it.
+- **Non-destructive transform** per frame: drag = move, wheel = scale, top handle = rotate, bottom-left = shear, plus a horizontal-flip toggle for left-right-reversed output. Edits live in a `curation.json` sidecar — source PNGs are never rewritten, and the compose step bakes the result deterministically. Preview and bake share one affine matrix, so what you align is what you get.
+- **Live preview** animates the sequence at the state's fps, with play/pause, frame-by-frame stepping, and a 0.25×–4× speed control.
+- Not just for sprites: point it at any folder of image candidates (icons, logos, generated drafts) with `unpack_atlas_run.py --pngs-dir` and use it as a general pick-the-winner view.
+
+### Isometric ground grid
+
+For isometric sets, the webview overlays the floor grid (from `meta.json` tile/anchor) so you can snap furniture to the diamond axes with the shear handle.
+
+![curation webview — isometric furniture](docs/assets/demo-furniture.gif)
+
+<img src="docs/assets/curator-iso.png" width="520" alt="isometric ground grid overlay" />
+
+### Languages
+
+The webview ships with English and Korean. Pass `--lang en|ko` when launching, or use the in-app toggle:
+
+```bash
+python3 scripts/serve_curation.py --run-dir <run-dir> --lang en # or ko
+```
+
+## Python support
+
+`sprite-gen` supports CPython 3.10+. CI runs the minimum supported version (3.10) and the latest covered version (3.14) on GitHub-hosted runners.
+
+The quickstart requires a Python install with working `venv`/`ensurepip`. If `python3 -m venv` fails before package installation in a local distribution, use a standard CPython build for any supported version and rerun the same commands.
+
+## Quickstart
+
+```bash
+# 0. install dependencies (Pillow, NumPy) into a fresh virtualenv
+python3 -m venv .venv && source .venv/bin/activate
+pip install -e .
+
+# 1. prepare a run from a base image
+python3 scripts/prepare_sprite_run.py --out-dir <run-dir> --character-id <id> --base-image base.png
+
+# 2. generate one row image per state with the engine-owned provider CLI
+python3 scripts/generate_sprite_image.py --provider codex \
+ --prompt-file <run-dir>/prompts/<state>.txt \
+ --out <run-dir>/raw/<state>.png \
+ --ref <run-dir>/base-source.png \
+ --ref <run-dir>/references/layout-guides/<state>.png
+# 3. extract frames
+python3 scripts/extract_sprite_row_frames.py --run-dir <run-dir>
+
+# 4. (optional) curate frames in the webview
+python3 scripts/serve_curation.py --run-dir <run-dir>
+
+# 5. bake the runtime atlas
+python3 scripts/compose_sprite_atlas.py --run-dir <run-dir>
+```
+
+### Editing a finished sheet
+
+When only the combined sheet survives, rebuild a curator-ready run dir, then curate and export:
+
+```bash
+# rebuild frames: explicit --grid, --manifest rectangles, or alpha auto-detect (default)
+python3 scripts/unpack_atlas_run.py --atlas sheet.png # auto-detect
+python3 scripts/unpack_atlas_run.py --manifest manifest.json # exact rectangles
+python3 scripts/unpack_atlas_run.py --pngs-dir furniture/ # import a loose PNG set
+
+# after curating, bake corrections back to named PNGs
+python3 scripts/export_curated_pngs.py --run-dir <run-dir>
+```
+
+Output defaults to a findable `<source>-curator` folder next to the input.
+
+### Baking colourways of a finished sheet
+
+Once the atlas is composed, swap selected colours into N finished sheets without
+re-running generation. Dot art is exact-match by default; soft-edged art can opt
+into a tolerance. Geometry and alpha never move — the base manifest describes
+every variant.
+
+```bash
+# draft the opaque colours (edit into a recolor spec with kind "sprite-gen-recolor")
+python3 -m sprite_gen.cli recolor-palette --base <run-dir>/sprite-sheet-alpha.png --out palette.draft.json
+
+# bake every colourway into <run-dir>/variants/
+python3 -m sprite_gen.cli recolor --run-dir <run-dir> --spec recolor.spec.json
+
+# blink-compare and adopt in the curation view
+python3 -m sprite_gen.cli curation --run-dir <run-dir>
+```
+
+Full spec/report contract and the adopt sidecar field: [`docs/recolor.md`](docs/recolor.md).
+
+### Cutting a background off an imported image
+
+Generated sprites are keyed off their own magenta/green background inside the
+pipeline, so they never need this. `cutout` is the import/post-edit utility: an
+image that arrived *with* an opaque uniform background (a hand-drawn icon, a
+downloaded sprite, a screenshot) is turned into a clean transparent PNG.
+
+<p align="center">
+ <img src="docs/assets/cutout-demo.png" width="720" alt="cutout: a white-background game icon turned into a clean transparent PNG, glass highlights preserved" />
+</p>
+
+```bash
+# routes on the corner colour: white/ivory -> matte, magenta/green -> extract engine
+python3 -m sprite_gen.cli cutout icon.png --white-check
+```
+
+It reads the corner background colour and routes (`--key auto|white|magenta|green`):
+
+- **white / ivory / solid** → position matte. A corner flood-fill keeps the
+ connected background only (bright highlights *inside* the object survive, not
+ holed), then a decontaminated soft alpha feathers the border. Tune with
+ `--strength` (bevel removal), `--band` (edge depth), `--erode`.
+- **magenta / green key** → the project's verified `extract` chroma engine is
+ reused as-is. Key colours never appear in objects, so its colour-only cut is
+ safe there — exactly where a white matte's flood-fill guard is *not* needed.
+
+`--white-check` writes cyan/magenta/yellow composites so any leftover fringe
+shows loudly. For uniform backgrounds; not for complex/non-uniform ones.
+
+The full agent-facing workflow and contracts live in [`SKILL.md`](SKILL.md).
+
+## Install
+
+From Codex skill installer workflows, install this repository as a root skill:
+
+```bash
+python3 ~/.codex/skills/.system/skill-installer/scripts/install-skill-from-github.py \
+ --repo aldegad/sprite-gen --path .
+```
+
+### Image generation ownership
+
+Provider-backed generation is part of this engine (`sprite_gen.gen`), with
+`codex` and `grok` as the supported providers. The general `image-gen` skill is
+only a thin shuttle to the same command, so it does not need a second provider
+implementation. See [`docs/gen.md`](docs/gen.md) for the CLI and verification
+contract.
+
+## Attribution
+
+The component-row workflow is inspired by the Apache-2.0 licensed `hatch-pet` skill, but targets generic game sprite atlases and includes no pet packages or pet visual assets.
+
+## License
+
+Apache-2.0
diff --git a/README.zh-Hans.md b/README.zh-Hans.md
new file mode 100644
index 0000000..1965f2d
--- /dev/null
+++ b/README.zh-Hans.md
@@ -0,0 +1,235 @@
+<h1 align="center">sprite-gen</h1>
+
+<p align="center"><b>输入一张图,输出可直接用于游戏的精灵图集——会呼吸。</b></p>
+
+<p align="center">
+
+**英语** · [한국어](README.ko.md) · [日本語](README.ja.md) · [简体中文](README.zh-Hans.md) · [Español](README.es.md) · [Français](README.fr.md)
+
+</p>
+
+---
+
+## 呼吸
+
+静止的待机姿势看起来像被冻结了一样。**呼吸**功能通过在你精心筛选的帧上烘焙确定性的挤压与拉伸效果,将单一姿势变成鲜活的循环动画。无需重新生成,无需重新提取,也无需额外绘制。只需一个伴随字段:
+
+```json
+"breathe": { "depth": 0.05, "breaths": 3 }
+```
+
+- **感知解剖结构。** 引擎会测量轮廓:颈部收窄处、无颈团块上的对称双眼,以及躯干与附肢的宽度差异。每一帧中的头部都保持**逐比特完全一致**;翅膀和手臂只会被推动,绝不会被拉伸。
+- **像素精准。** 仅使用整数行列映射——每个输出帧仍然是在同一网格上的干净像素画。1px 的轮廓始终保持为 1px:变形会保留轮廓边缘,并以内侧线条为锚点,规范化阶梯状像素的重复。
+- **可以亲手拖动的标尺。** 直接在实时播放画面上拖动刚性边界(红色)、身体轴线(蓝色)和躯干宽度线(虚线)。松开后,服务器会重新推导解剖结构——重新计算期间,预览仍会继续呼吸。
+- **逐字节一致的预览。** webview 镜像与 Python 烘焙会生成完全相同的字节,并由黄金测试强制保证。你看到的循环动画,就是最终随图集交付的内容。
+
+<p align="center">
+ <img src="docs/assets/breathe-editor.png" width="760" alt="呼吸区域编辑器:实时播放画面上的刚性边界、身体轴线和躯干宽度线,以及烘焙后的相位胶片条" />
+</p>
+
+同一确定性烘焙适用于人形、团块、触手等任意轮廓的正面、侧面和背面视图。
+
+让图像模型生成一张“精灵表”,你很清楚结果会是什么:角色的脸每一帧都在变化,背景无法干净抠除,姿势相互重叠并偏离网格,而且生成的 PNG 根本无法被游戏引擎直接使用。演示很可爱,素材却毫无用处。
+
+`sprite-gen` 是一个填补这一缺口的 Codex/Claude 技能。给它**一张基础图像**和一组动作——它会逐行驱动生成过程、锁定角色身份、将色键背景剥离为真正的 Alpha 通道、把每个姿势提取为干净的透明帧,并烘焙出带有**机器可读 `manifest.json.frame_layout`** 的运行时图集。
+
+对于生成始终无法处理好的最后 10%,还有一个**筛选 webview**:并排比较各帧、淘汰损坏的帧、以非破坏方式微调旋转/缩放/位置、实时观看循环动画——然后再进行烘焙。流水线负责苦工;品味由你掌控。
+
+```text
+sprite-request.json → 布局参考线 + 提示词 → sprite-gen gen 状态行
+→ 色键 Alpha → 连通分量 → 透明帧
+→ sprite-sheet-alpha.png + manifest.json.frame_layout
+```
+
+```mermaid
+flowchart LR
+ REQ["sprite-request.json<br/>(数值 SSoT)"] --> GUIDES["布局参考线<br/>+ 提示词"]
+ GUIDES --> GEN["sprite-gen gen<br/>状态行条带"]
+ GEN --> EXTRACT["色键 Alpha →<br/>连通分量"]
+ EXTRACT --> FRAMES["透明帧"]
+ FRAMES --> ATLAS["sprite-sheet-alpha.png<br/>+ manifest.json.frame_layout"]
+ FRAMES -. "筛选 webview(可选)" .-> ATLAS
+```
+
+> 完整架构:[`docs/architecture.md`](docs/architecture.md)
+
+## 你实际会得到什么
+
+- **透明精灵图集**(`sprite-sheet-alpha.png`)——真正的 Alpha 通道,没有残留的色键边缘,并已在白色背景上验证。
+- **运行时清单**(`manifest.json.frame_layout`)——包含绝对帧矩形,以及每个状态的 fps 和循环标志。你的引擎只需采样矩形,永远不必猜测网格。
+- **确定性的配色变体**——`sprite-gen recolor` 接收基础精灵表和调色板映射,通过一条命令烘焙 N 张变体精灵表(默认精确匹配 RGB;相同输入会生成相同的输出字节)。筛选 webview 会通过闪烁对比这些变体,并记录最终采用的名称。详情:[`docs/recolor.md`](docs/recolor.md)。
+- **可以亲眼查看的质量保证**——为每个状态生成 GIF 和接触表,让动画在交付前以动态形式接受评估。
+- **诚实的标签**——简短易读的动作(idle、jump、attack、wave)是稳定路径;循环位移动作(walk/run)除非真正通过动态质量检查,否则会被标记为实验性功能。绝不暗中夸大承诺。
+
+## 色键 Alpha 质量
+
+提取器以确定性方式清理色键:软 Alpha 解混会保留经过抗锯齿处理的发丝和细轮廓,而不是在计算覆盖率之前就将它们剥除。
+
+<p align="center">
+ <img src="docs/assets/chroma-fullbody-illustration-magenta.png" width="640" alt="全身色键对比:洋红色键背景上的插画" /><br />
+ <em>插画,洋红色键:源图、v1.12.0 剥离、v1.13.0 软 Alpha 解混。</em>
+</p>
+
+<p align="center">
+ <img src="docs/assets/chroma-fullbody-illustration-green.png" width="640" alt="全身色键对比:绿色键背景上的插画" /><br />
+ <em>插画,绿色键:源图、v1.12.0 剥离、v1.13.0 软 Alpha 解混。</em>
+</p>
+
+<p align="center">
+ <img src="docs/assets/chroma-fullbody-pixelart-magenta.png" width="640" alt="全身色键对比:洋红色键背景上的像素画" /><br />
+ <em>像素画,洋红色键:源图、v1.12.0 剥离、v1.13.0 二值化输出。</em>
+</p>
+
+<p align="center">
+ <img src="docs/assets/chroma-fullbody-pixelart-green.png" width="640" alt="全身色键对比:绿色键背景上的像素画" /><br />
+ <em>像素画,绿色键:源图、v1.12.0 剥离、v1.13.0 二值化输出。</em>
+</p>
+
+下面的局部放大图展示了全身对比图中的边缘细节。
+
+![色键剥离前后对比——插画发丝](docs/assets/chroma-peel-illustration-before-after.png)
+
+![色键剥离前后对比——像素画轮廓](docs/assets/chroma-peel-pixelart-before-after.png)
+
+## 主干晶格
+
+AI 生成的“像素画”并不是真正的像素画。色块会晃动,边缘带有抗锯齿,而且同一行内的晶格也会漂移,因此按照均匀网格切割会把一个色块涂抹到下一个色块中。社区通常采用的修复方式是对图像进行“去伪像素化”——根据连续长度猜测色块尺寸,再重新量化——但这种方式会分别测量每一帧,因此步行动画的单元格尺寸会随着帧不断伸缩。
+
+**主干晶格**会为整个主体测量出一套网格,并让每次切割都严格遵循它。逐帧间距检测会汇入覆盖整行、跨越所有帧的共识判断,从而否决谐波误检;这套共识网格就是每次切割所吸附的*主干*。切割线会落在真实的颜色边界上,而与测得间距成比例的最小单元格宽度,则能防止两条相邻切割线重合到同一色带。只使用一套主干,因此同一个色块在整段动画中始终保持相同尺寸,不会在帧与帧之间跳变。
+
+结果会根据实际交付内容进行验证,而不是靠肉眼检查一张精心挑选的帧:每次像素去伪处理都会从其自身的源条带重新推导,并逐像素进行比较。你批准的形状就是最终得到的形状;唯一发生变化的是轮廓和明暗的落点,而这正是主干晶格所决定的内容。
+
+## 筛选 webview
+
+生成过程可以完成 90%。webview 则让人工把剩下的部分推进到*可交付*状态——它可以独立运行,不依赖 Studio 或任何框架,只要安装了该技能便可使用(Claude Code Desktop、Codex 应用或普通终端)。
+
+![筛选 webview——角色](docs/assets/demo-character.gif)
+
+- **每个状态两行:**上方是**播放序列**,下方是**候选池**(例如第二次或第三次生成的版本)。拖动帧上的 ⠿ 手柄即可调整序列顺序,也可以把切片从候选池拖到上方——从多次生成结果中选取最佳帧,重新构建一套干净的奔跑循环。排列方式会被保存,因此重新打开时可以恢复。
+- 每帧支持**非破坏性变换**:拖动 = 移动,滚轮 = 缩放,顶部手柄 = 旋转,左下角手柄 = 剪切,另有水平翻转开关,可处理左右方向颠倒的输出。编辑内容保存在 `curation.json` 伴随文件中——源 PNG 永远不会被重写,合成步骤会以确定性方式烘焙结果。预览与烘焙共用同一个仿射矩阵,因此你对齐后的效果就是最终得到的效果。
+- **实时预览**会按照状态的 fps 播放序列动画,支持播放/暂停、逐帧步进,以及 0.25×–4× 的速度控制。
+- 不仅适用于精灵:使用 `unpack_atlas_run.py --pngs-dir` 将其指向任意图像候选文件夹(图标、徽标、生成草稿),即可将它用作通用的优胜者挑选视图。
+
+### 等距地面网格
+
+对于等距素材集,webview 会叠加地面网格(来自 `meta.json` 的 tile/anchor),让你可以使用剪切手柄将家具吸附到菱形轴线上。
+
+![筛选 webview——等距家具](docs/assets/demo-furniture.gif)
+
+<img src="docs/assets/curator-iso.png" width="520" alt="等距地面网格叠加层" />
+
+### 语言
+
+webview 内置英语和韩语。启动时传入 `--lang en|ko`,或使用应用内切换按钮:
+
+```bash
+python3 scripts/serve_curation.py --run-dir <run-dir> --lang en # 或 ko
+```
+
+## Python 支持
+
+`sprite-gen` 支持 CPython 3.10+。CI 会在 GitHub 托管的运行器上测试最低支持版本(3.10)和当前覆盖的最新版本(3.14)。
+
+快速入门需要安装能够正常使用 `venv`/`ensurepip` 的 Python。如果本地发行版在安装软件包之前执行 `python3 -m venv` 就失败,请改用任意受支持版本的标准 CPython 构建,然后重新运行相同命令。
+
+## 快速入门
+
+```bash
+# 0. 在全新的虚拟环境中安装依赖项(Pillow、NumPy)
+python3 -m venv .venv && source .venv/bin/activate
+pip install -e .
+
+# 1. 使用基础图像准备一次运行
+python3 scripts/prepare_sprite_run.py --out-dir <run-dir> --character-id <id> --base-image base.png
+
+# 2. 使用引擎管理的提供方 CLI,为每个状态生成一张行图像
+python3 scripts/generate_sprite_image.py --provider codex \
+ --prompt-file <run-dir>/prompts/<state>.txt \
+ --out <run-dir>/raw/<state>.png \
+ --ref <run-dir>/base-source.png \
+ --ref <run-dir>/references/layout-guides/<state>.png
+# 3. 提取帧
+python3 scripts/extract_sprite_row_frames.py --run-dir <run-dir>
+
+# 4. (可选)在 webview 中筛选帧
+python3 scripts/serve_curation.py --run-dir <run-dir>
+
+# 5. 烘焙运行时图集
+python3 scripts/compose_sprite_atlas.py --run-dir <run-dir>
+```
+
+### 编辑已完成的精灵表
+
+如果只剩下合并后的精灵表,可以重新构建一个可供筛选器使用的运行目录,然后进行筛选和导出:
+
+```bash
+# 重建帧:显式指定 --grid、使用 --manifest 矩形,或自动检测 Alpha(默认)
+python3 scripts/unpack_atlas_run.py --atlas sheet.png # 自动检测
+python3 scripts/unpack_atlas_run.py --manifest manifest.json # 精确矩形
+python3 scripts/unpack_atlas_run.py --pngs-dir furniture/ # 导入松散的 PNG 集合
+
+# 筛选完成后,将修正结果重新烘焙到具名 PNG 中
+python3 scripts/export_curated_pngs.py --run-dir <run-dir>
+```
+
+默认输出到输入文件旁边一个易于查找的 `<source>-curator` 文件夹中。
+
+### 烘焙已完成图集的配色变体
+
+图集编排完成后,无需重新运行生成流程,即可将选定颜色替换并生成 N 份最终图集。点阵图默认采用精确匹配;带柔和边缘的图像可以选择启用容差。几何形状和透明度始终保持不变——基础清单会描述每个变体。
+
+```bash
+# 起草不透明颜色(编辑为 kind 为 "sprite-gen-recolor" 的重新着色规范)
+python3 -m sprite_gen.cli recolor-palette --base <run-dir>/sprite-sheet-alpha.png --out palette.draft.json
+
+# 将所有配色变体烘焙到 <run-dir>/variants/
+python3 -m sprite_gen.cli recolor --run-dir <run-dir> --spec recolor.spec.json
+
+# 在整理视图中闪烁对比并采用
+python3 -m sprite_gen.cli curation --run-dir <run-dir>
+```
+
+完整的规范/报告契约以及采用操作的附属文件字段:[`docs/recolor.md`](docs/recolor.md)。
+
+### 移除导入图像的背景
+
+生成的精灵图在流水线内部会根据其自身的洋红色/绿色背景进行抠图,因此不需要使用此功能。`cutout` 是用于导入和后期编辑的工具:将一张带有不透明纯色背景的图像(手绘图标、下载的精灵图或截图)转换为干净的透明 PNG。
+
+<p align="center">
+ <img src="docs/assets/cutout-demo.png" width="720" alt="cutout:将白色背景的游戏图标转换为干净的透明 PNG,同时保留玻璃高光" />
+</p>
+
+```bash
+# 根据角落颜色分流:白色/象牙色 -> 蒙版,洋红色/绿色 -> 提取引擎
+python3 -m sprite_gen.cli cutout icon.png --white-check
+```
+
+它会读取角落的背景颜色并进行分流(`--key auto|white|magenta|green`):
+
+- **白色 / 象牙色 / 纯色** → 位置蒙版。角落泛洪填充仅保留相连的背景(物体内部的明亮高光会被保留,而不会被挖空),随后使用去除色彩污染的柔和透明度对边缘进行羽化。可通过 `--strength`(斜边移除)、`--band`(边缘深度)、`--erode` 进行调节。
+- **洋红色 / 绿色键色** → 原样复用项目中经过验证的 `extract` 色度引擎。键色绝不会出现在物体中,因此仅按颜色裁切在这里是安全的——这正是白色蒙版不需要泛洪填充保护的场景。
+
+`--white-check` 会写出青色/洋红色/黄色合成图,使任何残留的边缘色都清晰可见。适用于均匀背景;不适用于复杂或不均匀的背景。
+
+面向代理的完整工作流和契约位于 [`SKILL.md`](SKILL.md)。
+
+## 安装
+
+通过 Codex 技能安装器工作流,将此仓库安装为根技能:
+
+```bash
+python3 ~/.codex/skills/.system/skill-installer/scripts/install-skill-from-github.py \
+ --repo aldegad/sprite-gen --path .
+```
+
+### 图像生成的所有权
+
+由提供商支持的生成能力属于此引擎(`sprite_gen.gen`)的一部分,支持的提供商为 `codex` 和 `grok`。通用的 `image-gen` 技能只是通往同一命令的轻量转发层,因此不需要另一套提供商实现。有关 CLI 和验证契约,请参阅 [`docs/gen.md`](docs/gen.md)。
+
+## 归属说明
+
+组件行工作流受采用 Apache-2.0 许可证的 `hatch-pet` 技能启发,但其目标是通用游戏精灵图集,并且不包含任何宠物包或宠物视觉资源。
+
+## 许可证
+
+Apache-2.0
diff --git a/SECURITY.md b/SECURITY.md
new file mode 100644
index 0000000..784c088
--- /dev/null
+++ b/SECURITY.md
@@ -0,0 +1,74 @@
+# Security
+
+This repository uses `safedeps` as the local security gate for agent-driven
+dependency changes and commit-time secret scanning.
+
+## Dependency Changes
+
+Before adding a dependency with npm, pip, cargo, Go, RubyGems, Maven, or NuGet,
+run the advisory gate first:
+
+```bash
+safedeps check <ecosystem> <pkg>@<version-or-range> --json
+```
+
+Install only after the result is `clean` or `already_approved`, and use the
+reported `install_hint` or `suggested_spec` exactly. Do not install when the
+provider is unavailable, when a CISA KEV match is reported, or when no patched
+version is available.
+
+## Secret Scanning
+
+The repository-owned secret policy is `.gitleaks.toml`. The repo-local
+pre-commit hook is installed through `core.hooksPath=.githooks` and runs:
+
+```bash
+safedeps scan secrets --staged --root .
+```
+
+Do not commit real `.env` files or secret-bearing local configuration. Keep
+example files limited to placeholders.
+
+## Current Dependency Surface
+
+The runtime surface is two PyPI packages, both declared directly in
+`pyproject.toml`: **Pillow** (image I/O and the PIL-vector paths) and **NumPy**
+(the vectorized chroma extraction path). Neither may be relied on transitively —
+a package that arrives only because some other dependency pulls it in can leave
+on the next clean environment, and this package's own code must not be at the
+mercy of another package's dependency list.
+
+NumPy was cleared through the advisory gate above before it was declared, and
+every version that `numpy>=2.2.6,<3` resolves to on a supported interpreter
+carries a live approval: 2.2.6 on CPython 3.10, 2.4.6 on 3.11, and 2.5.1 on 3.12
+and later.
+
+Pillow is a separate matter and predates this section, so this document does not
+claim it is cleared. Its ledger approval for 12.2.0 is recorded as revoked, and
+12.3.0 — the version `pillow>=12.0,<13` actually resolves to today — has no
+ledger entry at all. The declared Pillow range is therefore not covered by a
+live approval. Closing that gap is tracked separately and is not resolved here.
+
+A pure-Python fallback for a missing NumPy is not permitted. The extraction path
+carries a byte-identity contract, and a second code path for the same contract
+is two answers to one question, so an interpreter without NumPy must fail
+loudly rather than silently take a slower route. `sprite_gen/_deps.py` is the
+single module that imports NumPy and is imported by `sprite_gen/__init__.py`, so
+that failure happens at package import and names both the interpreter that was
+used and the install command for the skill venv;
+`tests/test_numpy_dependency_gate.py` holds it there.
+
+This repository currently has no npm lockfile, so `safedeps audit npm` cannot
+produce a reproducible npm verdict yet. If a package manager is added later,
+commit the lockfile and let the pre-commit hook audit it.
+
+## Release Gates
+
+Run the local release gate before a release:
+
+```bash
+safedeps gates run --root . --strict
+```
+
+GitHub security workflows and branch protection are opt-in for this repository
+because they can spend runner minutes or change remote governance.
diff --git a/SKILL.md b/SKILL.md
new file mode 100644
index 0000000..ddf4aea
--- /dev/null
+++ b/SKILL.md
@@ -0,0 +1,554 @@
+---
+name: sprite-gen
+version: 1.59.0
+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."
+license: Apache-2.0
+depends_on:
+ required_bins:
+ - name: codex
+ why: "gen --provider codex (image_gen via ChatGPT OAuth)"
+ - name: grok
+ why: "gen --provider grok (Imagine via xAI OAuth)"
+ required_scripts:
+ - scripts/prepare_sprite_run.py
+ - scripts/generate_sprite_image.py
+ - scripts/extract_sprite_row_frames.py
+ - scripts/interpolate_frames.py
+ - scripts/compose_sprite_atlas.py
+ - scripts/preview_animation.py
+ - scripts/compose_selected_cycle.py
+ - scripts/compose_sprite_gif.py
+ - scripts/inspect_sprite_run.py
+ - scripts/score_sprite_run.py
+ - scripts/run_correction_loop.py
+ - scripts/gif_utils.py
+ - scripts/curation.py
+ - scripts/runio.py
+ - scripts/serve_curation.py
+ - scripts/slice_sheet_cells.py
+ - scripts/unpack_atlas_run.py
+ - scripts/export_curated_pngs.py
+ - scripts/recolor.py
+ - scripts/compose_layers.py
+modes:
+ default: component-row
+---
+
+# Sprite Gen
+
+`sprite-gen` builds generic game sprite atlases with a `component-row` pipeline:
+
+```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. Do not treat one-shot master sheets, fixed-grid atlas cutting, local drawing, or static fallback as a successful sprite result.
+
+## 필수 게이트 — AI raw 는 최종 에셋이 아니다 (BLOCKING)
+
+이 스킬의 모든 산출물은 아래 체크리스트를 통과해야 한다. 하나라도 어기면 그 결과물은 실패로 보고한다:
+
+- [ ] **AI 개입은 raw 생성 한 곳뿐이다.** `raw/<state>.png` 는 중간 산출물이며, 최종 에셋은 반드시 결정론 변환 — `extract_sprite_row_frames.py`(크로마 제거 → 컴포넌트 분리 → 피치 검출/그리드 스냅 → kCentroid → 공유 팔레트 → 셀 배치) — 를 거친다. 같은 입력이면 항상 같은 출력이 나오는 코드 경로만 픽셀 언페이크다.
+- [ ] **단순 다운스케일 쇼트컷 금지.** raw 를 PIL `resize()` 한 줄로 줄여 최종 경로에 놓는 것은 픽셀 언페이크 변환이 아니다 — AA 가장자리 열화와 그리드 미정렬이 그대로 남는다. "이번 한 번만 빠르게" 도 금지. 파이프라인 없이 낱장만 변환할 때도 run dir 를 만들어 같은 추출 경로를 태운다.
+- [ ] **베이스/앵커가 스타일 SSoT 다 — 도트 런이면 베이스부터 진짜 도트여야 한다.** 조립되는
+ 프롬프트의 `Style contract:` 기본값은 "첨부한 베이스/앵커 레퍼런스를 그대로 따라라"이고,
+ 이미지 모델은 첨부 레퍼런스를 프롬프트 텍스트보다 강하게 따른다. 그래서 `fit.pixel_unfake`
+ 런에 AA/벡터풍 베이스를 붙이면 프롬프트에 "TRUE 32x32 pixel art" 를 적어도 raw 가 도트로
+ 나오지 않는다. 잠금 전에 베이스에서 **픽셀 격자가 실측으로 검출되는지**(균일 블록 피치,
+ AA 반투명 가장자리 없음) 확인하고, 아니면 베이스부터 다시
+ 만든다. 프롬프트 문구로 베이스의 스타일을 이기려 하지 마라.
+- [ ] **크로마 키는 소재색을 먼저 보고 고른다.** 핑크/보라/자주 소재 → 그린 `#00FF00`, 녹색/청록 식물 → 마젠타 `#FF00FF`. 분기표 SSoT 는 image-gen SKILL.md 최상단 게이트 (상세는 [`docs/chroma-alpha.md`](docs/chroma-alpha.md)).
+- [ ] **변환 후 소재색 보존을 검증한다.** 꽃이 희게 탈색됐거나 주요 색이 빠졌으면 키 선택이 소재와 충돌한 것이다 — 로컬 보정이 아니라 키를 바꿔 재생성한다.
+
+## 리네임 게이트 — 어휘/키를 바꿀 때 (BLOCKING)
+
+스키마 키·식별자·라벨을 걸쳐 어휘를 바꾸는 작업(`pixel_perfect` → `pixel_unfake` 류)은
+**일괄 치환으로 시작하지 않는다**. 치환은 이름을 바꾸지만 계약은 **층위**로 존재한다:
+
+```text
+식별자 → 키 문자열 → 사용자 라벨(en+ko) → 문서 예제 → --help 문구 → 테스트 하니스
+```
+
+순서가 정해져 있다 (회귀 2026-07-25/26, plan `sprite-gen/pixel-unfake-rename` — 이 순서를
+거꾸로 해서 검증자 리젝트 3라운드가 났다):
+
+- [ ] **구조 단정을 스윕보다 먼저 쓴다.** 판독 SSoT(게이트) 밖에서 그 파일/키를 읽는 프로덕션
+ 경로가 있으면 실패하는 테스트. **정규식이 아니라 AST** 로 — 실제 회귀 형태는 보통 두
+ 줄(경로를 변수에 담고 다음 줄에서 읽기)이라 한 줄 정규식은 못 잡는다
+ (`tests/test_pixel_unfake_migration.py` 마지막 케이스가 그 형태).
+- [ ] **그 단정을 mutant 로 검증한다.** 옛 형태를 일부러 되돌려 실제로 실패하는지 본다. 통과만
+ 하는 단정은 장식이고, 그걸 근거로 "구조로 닫았다" 고 말하면 거짓 보고가 된다.
+- [ ] **판독부는 키 이름만 바꾸지 않고 게이트 뒤로 옮긴다.** 이관 전 데이터에서 그 판독부만
+ 조용히 틀린 답을 본다 (실측: 리롤이 "언페이크가 꺼져 있다" 며 거짓 거부).
+- [ ] **구분자가 바뀌는 치환은 토큰 단위로.** `pixel-perfect` → `pixel unfake` 처럼 하이픈이
+ 공백이 되는 치환은 argparse 옵션·경로·식별자를 깨뜨린다 (실측: `--fit-pixel unfake` 유령
+ 옵션 등록 + 은퇴 안내문이 현행 플래그를 은퇴했다고 말하는 자기모순).
+- [ ] **은퇴 이름은 조용한 별칭으로 남기지 않는다.** 새 이름을 안내하며 hard error. 그 안내
+ 문구 자체는 치환 대상에서 제외한다.
+- [ ] **순수 리네임 주장은 골든 회귀로 증명한다.** 리네임 전/후 산출물이 바이트 동일한지.
+
+
+## Base Lock Gate (Stage 0, BLOCKING)
+
+Identity ownership in the row pipeline:
+
+```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
+```
+
+The full reference-ownership flow (base → idle anchors → base 폐기 → basis/paired rows) and the base re-attach ban live in [`docs/architecture.md`](docs/architecture.md) §5.
+
+A weak idle anchor poisons every state — proportions, style, and identity drift compound across all rows. Before any row generation, answer the gate question `y`/`n`:
+
+> Is there an image good enough to **lock** as the canonical base idle?
+
+The base idle locks only when **all** of these hold:
+
+- Full body, nothing cropped (head to feet inside frame).
+- The final proportions and style the user asked for are already correct in this image (for example SD / chibi head-to-body ratio, pixel look, outline weight). The base defines the target — do not plan to "fix it later" in the rows.
+- For a pixel-art run (`fit.pixel_unfake`): the base itself is true pixel art — a uniform pixel-block grid is measurably present and edges are hard (no anti-aliased fringe). The style contract delegates style authority to this image, so a non-pixel base structurally produces a non-pixel row.
+- Identity matches the character sheet / reference (face, hair, markings, palette, props).
+- One clear single idle pose, facing the intended camera, readable silhouette at small size.
+- Background is a flat clean chroma-ready fill (or trivially keyable).
+
+If the answer is `n`: generate/iterate base candidates, review each against the criteria above, and re-gate. **Do not run `prepare_sprite_run.py` until a base is locked.** "Good enough for now" is not a pass — drift only grows once the rows start. When the answer is `y`, that exact file becomes the accepted idle anchor for its direction; keep the original generation so the lock decision is auditable, but do not attach it again after the idle anchors have replaced it as row identity truth.
+
+## 실행 인터프리터 — 전역 `python3` 는 이 스킬의 인터프리터가 아니다 (BLOCKING)
+
+이 스킬의 모든 명령은 **레포 루트의 venv 인터프리터**로 실행한다:
+
+```bash
+export SPRITE_GEN_ROOT=/path/to/sprite-gen
+$SPRITE_GEN_ROOT/.venv/bin/python <script.py> ...
+```
+
+- **부트스트랩은 README quickstart·CI 와 같은 한 줄이다** — `python3 -m venv .venv && .venv/bin/pip install -e .`.
+ `.venv` 가 없으면 만든 뒤 실행한다. 다른 경로에 만들었다면 그 인터프리터의 절대경로로 바꿔 쓴다 —
+ 바뀌면 안 되는 것은 경로가 아니라 **"전역 `python3` 를 쓰지 않는다"** 는 규칙이다.
+- **이유**: 의존(Pillow, NumPy)의 SSoT 는 `pyproject.toml` 이고, 그것을 실물로 만드는 곳은 이 venv 하나다.
+ 전역 `python3` 는 `$PATH` 가 그날 가리키는 아무 인터프리터이고(macOS 에서는 보통 homebrew CPython,
+ PEP 668 `EXTERNALLY-MANAGED`), 거기 든 패키지는 손으로 넣은 것이라 선언과 실물이 갈린다. 실제로
+ 그렇게 갈렸다: homebrew python3 에는 Pillow 만 있고 NumPy 가 없어서, **한 개가 깔려 있다는 이유로
+ 다 깔린 것처럼 보이는** 상태였다.
+- **폴백 금지**: "`.venv` 있으면 그거, 없으면 `python3`" 같은 해석은 두지 않는다 (원칙 6).
+ 없으면 만들거나 요란하게 실패한다 — 조용히 다른 인터프리터로 도는 경로는 없다.
+- **NumPy 가 없는 인터프리터에서는 아무것도 시작하지 않는다**: 진입점은 패키지 import 시점에
+ 멈추고, 실행한 인터프리터 경로와 위 부트스트랩 명령을 그대로 찍는다. 추출 경로는 바이트 동일
+ 계약을 지고 있어서 **순수 파이썬 폴백은 없다** — 느리게라도 도는 두 번째 구현을 두면 같은 질문에
+ 답이 둘이 된다. (게이트 `sprite_gen/_deps.py`, 잠금 `tests/test_numpy_dependency_gate.py`)
+- **자식 프로세스는 상속한다**: `heal_run` 과 큐레이션 서버는 자식을 `sys.executable` 로 띄운다.
+ 즉 부모를 옳은 인터프리터로 띄우면 그 아래는 자동으로 옳고, 반대로 큐레이션 서버를 전역 `python3` 로
+ 띄우면 그 서버가 부르는 재추출·compose 가 전부 같이 틀린다. 고칠 곳은 **띄우는 순간 한 곳**이다.
+- **`sprite-gen <tool>` 은 실재하는 콘솔 스크립트다** (`anchor`, `cutout`, `curation`,
+ `recolor`, `recolor-palette`, `migrate-breathe`, `migrate-request` …). `pip install` 이 venv 의 `bin/` 에 써 넣고 그 shebang 이 **바로 그 venv 의
+ 인터프리터**를 가리키므로, 이 형식은 인터프리터를 고르는 문제 자체가 없다:
+
+ ```bash
+ $SPRITE_GEN_ROOT/.venv/bin/sprite-gen <tool> ...
+ ```
+
+ - **여기서도 절대경로다** — 맨 `sprite-gen` 이 PATH 에 있는 건 venv 를 활성화했거나 그 환경에
+ 설치한 셸 안에서뿐이다. `SKILL.md`·`docs/*.md` 는 활성화 없는 셸에서 읽히므로 맨 `python3` 와
+ 같은 이유로 맨 `sprite-gen` 도 쓰지 않는다 (README quickstart 는 활성화가 앞에 있어 예외).
+ - **이 변경 이전에 만든 `.venv` 에는 없다** — `[project.scripts]` 가 없던 시절 설치본이라
+ `bin/sprite-gen` 이 안 만들어졌다. `pip install -e .` 를 한 번 다시 돌리면 생긴다.
+ - `$SPRITE_GEN_ROOT/.venv/bin/python -m sprite_gen.cli <tool> ...` 는 같은
+ `cli:main` 을 부르는 동치 형식이다 — 콘솔 스크립트가 아직 없는 venv 에서 쓴다.
+- **레지스터는 파일로 갈린다**: 상대경로 `python3 scripts/...` 형식이 같은 인터프리터를 가리키는 건
+ `source .venv/bin/activate` 가 **바로 앞에 적혀 있는** README quickstart 안에서만이다. `SKILL.md` 와
+ `docs/*.md` 는 활성화 단계가 없는 셸에서 읽히므로, 절대경로든 상대경로든 **여기서는 상대형을 쓰지
+ 않는다** — 위 venv 절대경로 형식 하나만 쓴다. (`tests/test_entrypoint_interpreter.py` 가 이 두 파일군에
+ 대해 잠근다.)
+
+## Script Map
+
+Scripts are explicit pipeline commands, not hidden imports. One job each (stage detail: [`docs/architecture.md`](docs/architecture.md) §2):
+
+- `prepare_sprite_run.py` — write `sprite-request.json`, per-state layout guides, prompts, and empty `raw/` + `frames/` from request truth.
+- `extract_sprite_row_frames.py` — read `raw/<state>.png` strips: chroma removal → connected components → transparent frame cells + `frames/frames-manifest.json`.
+- **에이전트 주도 호흡** (사용자가 "숨쉬기 적용해서 뽑아줘" 라고만 해도 됨): 호흡은 사이드카 필드라 뷰 없이도 켤 수 있다 — (1) `states.<state>.breathe = {"depth": 0.06, "breaths": 1, "lag": 0.1}` 만 쓰면 된다. **경계는 선언하지 않는다** — `sprite_gen/anatomy.py` 가 검출한다. 큐레이터를 거치면 그 결과가 사이드카 `anatomy` 에 얼려지고(`GET /api/breathe-anatomy`), 뷰 없이 에이전트가 `breathe` 만 쓴 런은 `anatomy` 가 비어 있어 **굽기가 매번 다시 잰다** — 굽기는 사이드카에 쓰지 않는다. 어느 쪽이든 동작한다. **굽기는 얼린 값을 신뢰하지 않는다 — 언제나 자기 기준 프레임에서 다시 잰다** (얼린 값은 큐레이터 프리뷰용 캐시다). 사이드카와 어긋나면 manifest 의 `sidecar_drift` 로 값을 실어 보고한다. 그 캐시가 아직 유효한지는 기준 프레임의 **입력** 지문(원본 파일 스탬프·픽셀편집·변형·변종)으로 판정하고, 어긋나면 큐레이터가 프리뷰·영상 내보내기를 **거부하며 갱신하라고 알린다** — 조용히 낡은 숫자로 그리지 않는다. 사람이 특정 행에 고정하고 싶을 때만 `rigid_row` 를 준다. (에이전트 직접 쓰기는 `load_curation`→`stamp_curation` 도장 경로 필수, 열린 탭은 새로고침 안내 — 함정 상세: [`docs/troubleshooting.md`](docs/troubleshooting.md)), (2) `compose_sprite_gif.py`/`compose_sprite_atlas.py` 가 자동으로 굽는다. 검증: gif-manifest 의 `breathe.phases`. **구 `splits`/`amplitude`/`subpixel` 은 요란하게 거부된다** — 옮기려면 `sprite-gen migrate-breathe <run-dir> --apply`.
+- **정지 자세(sit/lie/carry_idle 등) 행 레시피** — 정지 1컷 + 링크 복제 @ 4fps + 허리선 호흡(breaths 3) + 눈 보이는 방향만 깜빡임. **복제 수 = `recommended_breathe_frames(breathe) − 1`** (호흡당 `SMOOTH_CYCLE_FRAMES`=6 프레임 확보; breaths 3 → 총 18컷) — 짧은 루프(옛 11컷)에 다수 호흡을 우겨넣으면 1px 위상이 매 프레임 토글해 진동으로 읽히던 걸 막는다 (maintainer 2026-07-24). 깜빡임은 **시퀀스 끝 근처**(맨 끝 아님, 뒤에 눈뜬 rest ≥2)에 배치해 루프 이음새 전에 다시 떠 스냅을 없앤다. 실측 도출 근거·자동 적용 절차·프레임 게이트: [`docs/static-pose-recipe.md`](docs/static-pose-recipe.md) (maintainer 확정 2026-07-19, 이징 게이트 2026-07-24).
+- 호흡(idle breathing)은 **후처리 레이어**다 (maintainer 확정 2026-07-18) — 스크립트가 아니라 curation.json 사이드카 `states.<state>.breathe = {depth, depth_x?, breaths, lag, rigid_row?, anatomy}` 로 선언하고, compose/GIF 가 재생 시퀀스 위에 결정론(봉투 워프, `sprite_gen/breathe.py`)으로 굽는다. 깜빡임 프레임도 그대로 숨쉰다 (프레임 선택과 직교).
+ - **변형은 자르지 않고 강도를 떨군다** (2026-07-25 교체): 스프라이트 전체에 연속 변형장을 걸고 그 강도를 강체 경계에서 0 으로 테이퍼한다. `env=0` 인 행은 가로 사상이 항등이고 세로 누적이 정확히 1씩 늘어 **그 구간이 프레임 간 비트 동일**하다 — 눈·입이 몇 도트뿐이라 근사로는 표정이 뭉갠다. 가로는 행 안에서 밀도를 적분하므로 사상이 단조라 접힘이 없고, 날개 같은 부속은 밀리기만 하고 안 늘어난다.
+ - **강체 경계는 가슴이 아니라 목이다.** 가슴은 해부학 개념이라 몬스터마다 다르지만 목은 기하학적 병목이라 안정적으로 잡힌다. 얼굴이 몸통에 있으면(버섯·슬라임) 대칭 눈쌍을 찾아 얼굴 아래로 내린다. 병목도 얼굴도 없으면 어깨-기울기로 떨어지고 그 사실이 `anatomy.warnings` 에 남는다.
+ - 큐레이션 뷰: 줄 헤더 호흡 체크박스(즉시 on/off) + 라벨 클릭 편집기(실재생 위 **강체 경계 1개 드래그** · 세로 진폭 `depth` · 가로 진폭 `depth_x`(기본 "=세로", 0 = 가로 끄기 — maintainer 요청 2026-07-30 가로/세로 분리) · 루프당 호흡 횟수 · `auto` 되돌리기 — 즉시 반영, Esc 복원, 최종 굽기 필름스트립). 루프 길이는 시퀀스 그대로 불변이고 위상이 연속값이라 breaths 는 요청 그대로 적용된다 (범위 1~8이고 **정수여야 한다**; 밖이거나 비정수면 조용히 깎지 않고 요란하게 거부한다 — `depth` 0.005~0.20, `depth_x` null|0~0.20, `lag` 0~0.45 도 같다). 재추출/굽기 대기 없음.
+ - 세로선(몸통 밴드)을 **사람이 조정하면** 보호 램프가 밴드 자체에 앵커된다 — 밴드 밖 열은 늘어나지 않고 밀리기만 한다. 자동 검출 밴드는 부속(날개·긴 팔)이 실재할 때만 켜지는 기존 계약 그대로다 (블롭에서 밴드 조정이 무력했던 버그 수리, 2026-07-30).
+- `interpolate_frames.py` — AI in-between: 두 프레임을 ref 로 물려 **생성형**(codex 기본/grok)으로 중간 프레임을 그려 **테이크**로 기록 (raw 단계 AI — 최종 프레임은 여전히 결정론 추출이 굽는다). 서버 머신의 provider CLI OAuth 를 쓰므로 GUI 버튼도 동작 — 인증 전제와 실측 근거(RIFE 파기): [`docs/frame-interpolation.md`](docs/frame-interpolation.md).
+- `compose_sprite_atlas.py` — compose `sprite-sheet-alpha.png` + runtime `manifest.json.frame_layout`.
+- `export_aseprite.py` (`sprite-gen export-aseprite`) — describe the composed atlas as Aseprite-compatible JSON for Phaser or Flame; usage, mapping, and limitations: [`docs/engine-export.md`](docs/engine-export.md).
+- `preview_animation.py` — QA previews from extracted frames: contact sheets + state GIFs under `qa/`.
+- `compose_selected_cycle.py` — record a human-selected frame subset as a selected-cycle manifest + QA GIF/contact sheet (reads `curation.json` by default; `--frames` overrides).
+- `compose_sprite_gif.py` — clean transparent GIF export: single frame set, or `--run-dir` batch (one GIF per state from request fps + `curation.json`) into `<run-dir>/exports/`; called by the webview's Export-GIFs button and the v2 desktop app.
+- `inspect_sprite_run.py` — deterministic row inspection for the automatic correction loop: expected vs found frame count, 64-bin RGB histogram similarity, dHash silhouette similarity, motion presence, centroid jitter, and extraction warnings.
+- `score_sprite_run.py` — score an inspect report (0-100), preserve the best-candidate rank signal, and turn measured defects into provider-ready correction hints.
+- `run_correction_loop.py` — bounded inspect → score → correction-hint loop (max 3 passes by default). It can run as a dry-run verifier without a provider, or call an explicit provider command; missing provider without `--dry-run` fails loudly.
+- `gif_utils.py` — shared transparent-GIF writer.
+- `curation.py` — curation sidecar SSoT (schema + transform math + the stamping atomic writer) shared by the compose scripts, the anchor CLI, and the webview server so they never drift.
+- `sprite_gen/curate/anchor.py` (`sprite-gen anchor`) — direction-anchor SSoT: which curated instance is a direction's identity (human pin > the anchor row's sequence head), the post-processing bake of that one frame, and the `references/anchors/<dir>-anchor-x8.png` derived cache that row generation attaches. Reroll, the generation plan, and the curation view's anchor chip all resolve through it.
+- `sprite_gen/spec/runio.py` — safe run-dir IO: single-writer lock (`.sprite-gen.lock`) + atomic writes for the extract/compose/export/unpack writers, so parallel agents cannot interleave writes into one character folder.
+- `sprite_gen/serve/serve_curation.py` (`sprite-gen curation`) — standalone curation webview for one run dir (works from Claude Code Desktop, the Codex app, or any host with the skill). The `-m sprite_gen.serve.serve_curation` module form and the `scripts/serve_curation.py` wrapper reach the same declaration and the same implementation — three live entry forms, one program (launch forms: [`docs/curation.md`](docs/curation.md)). When `<run-dir>/variants/recolor.report.json` is present, the view also blink-compares baked colourways and records the adopted name in `curation.json.recolor.picked` (detail: [`docs/recolor.md`](docs/recolor.md)).
+- `sprite_gen/effects/recolor.py` (`sprite-gen recolor` / `sprite-gen recolor-palette`) — deterministic palette-swap bake. `recolor-palette` drafts a frequency-ordered palette map from a base sheet; `recolor` takes `base sheet + recolor spec` and bakes N variant sheets + a per-variant substitution report into `<run-dir>/variants/` (or an explicit `--out-dir`). Exact RGB match by default (dot-art safe); opt-in Chebyshev tolerance for soft edges. Alpha preserved, geometry untouched — a base manifest describes every variant. No Silent Fallback: unused map sources and unmapped passthrough colours are named and counted in `recolor.report.json`. Detail: [`docs/recolor.md`](docs/recolor.md).
+- `sprite_gen/compose/compose_layers.py` (`sprite-gen compose-layers`) — deterministic composite bake for a run that declares a **rig**. Stacks curated rows onto each other by integer pivot translation + arbitrary alpha masks (no resampling, rotation or scale of its own) into `<run-dir>/layers/<name>.png` + `<name>.manifest.json` + `layers.report.json`. Optional and opt-in: a request with no `rig` / `track` / `layers` is not a layer run and is refused by name rather than composed. All-or-nothing — declaration, composition **and** publish: one violation reports every violation and writes nothing. Declaration schema, CLI usage, and what `prepare` carries: [`docs/layer-tracks.md`](docs/layer-tracks.md).
+- `unpack_atlas_run.py` — inverse of compose: rebuild a curator-ready run dir from a finished sheet (`--grid` > `--manifest` > auto-detect) or import a PNG folder (`--pngs-dir`, with sibling `meta.json` labels/iso grid).
+- `export_curated_pngs.py` — export curated frames back to named PNGs with the transform baked in, into `<run-dir>/curated/`; the deliverable for imported still sets.
+- `cutout.py` (`sprite-gen cutout`) — background remover for **imported** images (not pipeline output, which is already keyed). Routes on the corner background colour (`--key auto|white|magenta|green`): **white/ivory** → position matte (corner flood-fill keeps interior highlights unholed → decontaminated soft-alpha border + soft erode); **magenta/green key** → reuse the verified `extract.remove_chroma_background` engine as-is (no drift — key colours are absent from objects so its colour-only cut is safe there). `--white-check` writes cyan/magenta/yellow verification composites. No Silent Fallback (leftover non-zero RGB under transparency raises).
+- `slice_sheet_cells.py` — slice a multi-figure grid sheet (same character, N expressions/variants in one image) into per-cell standing cuts: v1.13 chroma alpha + centroid cell assignment + merged-figure split/in-cell re-label + neighbour-debris drop + per-cell height normalization + shared feet baseline. For dialogue cut-in portraits (立ち絵), not animation rows. Detail: [`docs/sheet-slicing.md`](docs/sheet-slicing.md).
+- `check_visible_magenta.py` — optional screenshot QA guard for visible chroma-key leakage.
+
+## Workflow
+
+0. Pass the **Base Lock Gate** above. Do not start step 1 until a base idle is locked (`y`).
+
+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
+```
+
+For hatch-pet-style locomotion, add the cell gate explicitly: `--cell-width 192 --cell-height 208`.
+
+방향 있는 캐릭터(휴머노이드 4/8방향)는 방향 계약을 함께 선언한다: `--directions down,side,up --mirror left=side`.
+방향 계약 런의 파일은 **택소노미**(`raw/<dir>/<pose>.png`, `frames/<dir>/<pose>/`, 가이드/프롬프트 동일)로
+나뉜다 — 자세가 늘어도 flat 폴더가 비대해지지 않는다. 경로 리졸버 SSoT 는 `sprite_gen/layout.py`,
+추출된 프레임의 경로는 frames-manifest `row.files` 가 SSoT 다 (run-contract §2).
+base = down 정면 기본자세 하나이고, prepare 가 방향 앵커(`<dir>_idle`) 슬롯을 합성하고 생성 체인 SSoT
+(`references/generation-plan.json` — 1단계 앵커는 base 기반, 2단계 행은 자기 방향 앵커 기반, 미러 방향은
+생성 생략 계약)를 기록한다. 상세와 좌우 재생성 규칙: [`docs/directional-anchor-workflow.md`](docs/directional-anchor-workflow.md) "Prepare 스캐폴딩".
+
+This writes:
+
+```text
+sprite-request.json
+base-source.<ext>
+references/layout-guides/<state>.png
+prompts/<state>.txt
+raw/
+frames/
+```
+
+2. Generate one image per state with the engine's own `gen` command (generation is engine-owned; the `image-gen` skill is now a thin shuttle over this — [`docs/gen.md`](docs/gen.md)):
+
+```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
+```
+
+Use `prompts/<state>.txt` as the prompt; save the selected image as `raw/<state>.png`. `--provider` is optional — the default is **codex** (`SPRITE_GEN_DEFAULT_PROVIDER` env overrides it; an observable grok fallback kicks in only if codex is unavailable). Pass `--provider grok` explicitly for the faster backend; codex adheres tighter to negative constraints. Default policy: [`docs/gen.md`](docs/gen.md#default-provider-selection). Keep the request chroma key on the background (extraction removes it). Reference attachment rules:
+
+**생성 동시성 (maintainer 확정 2026-07-19)**: 여러 행을 뽑는 배치는 **4동시**로 돌린다 —
+`sprite-gen gen` 호출을 최대 4개 병렬 (codex 실측 4병렬까지 스로틀 없음; grok 도 4,
+사용자 관측상 6까지 가능하나 기본은 4). 1개씩 직렬은 멀티-행 배치에서 안티패턴.
+run-dir 쓰기는 `runio.py` 락이 지키므로 생성(각자 다른 `raw/<state>.png` 출력)은
+안전하게 병렬화된다. 이 규칙은 지침이다 — 오케스트레이션 스크립트를 짤 때
+`ThreadPoolExecutor(max_workers=4)` 급으로 반영하라.
+
+Generation providers are **engine backends**, not user-facing agents. Selecting
+`grok` launches a headless `grok -p` process owned by `GrokProvider`; it does not
+require or route through a separate user-facing skill/task. Spawning a visible
+worker/agent is the caller's orchestrator concern — out of this engine's scope.
+Command chain: [`docs/gen.md`](docs/gen.md#provider-topology).
+
+- Simple/default states (before direction-anchor mode exists): attach exactly two references — `base-source.<ext>` (canonical identity) + `references/layout-guides/<state>.png` (layout only).
+- Direction-anchor mode: do **not** attach `base-source.<ext>` to action rows. Attach the accepted target-direction anchor (**a single-pose single image — never a multi-frame idle row**) + the state layout guide; for a paired row also attach the basis row as timing/scale/motion reference only. **Never choose the anchor crop by hand** — ask the pipeline, right before each generation:
+
+```bash
+$SPRITE_GEN_ROOT/.venv/bin/python -m sprite_gen.cli anchor \
+ --run-dir <run> --for-state <state> # prints the identity ref path (bakes it)
+```
+
+ It returns `references/anchors/<dir>-anchor-x8.png` for an action row (the curated anchor frame — pixel edits, transforms, deletions and reordering all baked, upscaled ×8 NEAREST) and `base-source.<ext>` for an anchor row or a non-direction run. The file is a derived cache, so re-run it every time; which frame is the anchor is the human's call (`--pick <state>#<index>`, or the pin button in the curation view) and defaults to the anchor row's curated sequence head. Chain details: [`docs/directional-anchor-workflow.md`](docs/directional-anchor-workflow.md).
+- Hatch-pet-style locomotion may attach additional references only when they are part of the row plan, recorded in `qa-notes.md`: original sheet / canonical base (identity support only), a previous gait row such as `raw/running-right.png` (motion rhythm only), or an accepted motion-QA artifact (gait readability support only).
+
+3. Extract frames:
+
+```bash
+$SPRITE_GEN_ROOT/.venv/bin/python $SPRITE_GEN_ROOT/scripts/extract_sprite_row_frames.py \
+ --run-dir <target>/assets/generated/sprites/<character-id>
+```
+
+This removes the request chroma key, finds connected sprite components, fits each pose into a fresh transparent request-sized cell, and writes `frames/<state>/frame-N.png` plus `frames/frames-manifest.json`.
+
+3.5. (Optional) Curate frames in the webview:
+
+```bash
+$SPRITE_GEN_ROOT/.venv/bin/sprite-gen curation \
+ --run-dir <target>/assets/generated/sprites/<character-id>
+```
+
+Standalone local webview: side-by-side frame compare, select/reject, drag-to-reorder play sequence, non-destructive per-frame transform saved to `curation.json` (originals never rewritten; no sidecar = all frames in order, an explicit default). Usage detail, finished-sheet editing via `unpack_atlas_run.py`, and the standalone image-candidate curation path: [`docs/curation.md`](docs/curation.md).
+
+4. Compose the runtime atlas:
+
+```bash
+$SPRITE_GEN_ROOT/.venv/bin/python $SPRITE_GEN_ROOT/scripts/compose_sprite_atlas.py \
+ --run-dir <target>/assets/generated/sprites/<character-id>
+```
+
+This writes:
+
+```text
+sprite-sheet-alpha.png
+sprite-sheet-alpha.report.json
+manifest.json
+```
+
+`manifest.json.frame_layout` is the runtime SSoT. Game code must consume rectangles from the manifest and must not recover frame rectangles from alpha content at runtime.
+
+4.5. (Optional) Bake palette-swap colourways of the finished atlas:
+
+```bash
+# draft the opaque colours of the base sheet (edit into a recolor spec)
+$SPRITE_GEN_ROOT/.venv/bin/sprite-gen recolor-palette \
+ --base <run>/sprite-sheet-alpha.png --out <run>/palette.draft.json
+
+# bake N variants from a recolor spec (kind "sprite-gen-recolor") into <run>/variants/
+$SPRITE_GEN_ROOT/.venv/bin/sprite-gen recolor \
+ --run-dir <run> --spec <run>/recolor.spec.json
+```
+
+Exact RGB match by default (dot art); opt-in `match: "tolerance"` for soft edges. Same input → same output bytes. The report names every unused map source and every unmapped passthrough colour — nothing outside the map vanishes quietly. Spec schema, report fields, and curation-view adopt flow: [`docs/recolor.md`](docs/recolor.md).
+
+4.6. (Optional, rig runs only) Bake the declared composite stacks:
+
+```bash
+$SPRITE_GEN_ROOT/.venv/bin/sprite-gen compose-layers \
+ --run-dir <target>/assets/generated/sprites/<character-id>
+```
+
+Only for a run whose `sprite-request.json` declares `rig` / `states.<state>.track` / `layers` — every other run is untouched by this feature and this step is skipped. It stacks the **curated** rows (integer pivot translation + alpha masks, no resampling) into `<run>/layers/<name>.png` + `<name>.manifest.json` + `layers.report.json`, so the same run bakes the same bytes every time. `--names a,b` bakes a subset and leaves the rest of `layers/` alone. Declaration schema, landmark rules, track kinds, and what `prepare` carries: [`docs/layer-tracks.md`](docs/layer-tracks.md).
+
+5. Launch the curation webview automatically (default closing step):
+
+```bash
+$SPRITE_GEN_ROOT/.venv/bin/sprite-gen curation \
+ --run-dir <target>/assets/generated/sprites/<character-id> &
+```
+
+After the atlas composes (and QA previews exist), launch the webview in the background and report the printed URL — finishing a run means handing the human the open webview, not just file paths. Multi-agent launch rules (per-launch free port, one webview per run dir, `.sprite-gen.lock`, `--no-open` for headless): [`docs/curation.md`](docs/curation.md). Skip the auto-launch only for an explicitly unattended batch run.
+
+## SSoT
+
+Every run starts with `sprite-request.json`. It owns the numeric recipe used by prompts and scripts:
+
+```json
+{
+ "version": 1,
+ "kind": "sprite-gen-request",
+ "engine": "component-row",
+ "character": { "id": "demo-hero", "description": "same character as the base image" },
+ "cell": { "shape": "square", "size": 256, "safe_margin": 24 },
+ "chroma_key": { "name": "magenta", "hex": "#FF00FF", "rgb": [255, 0, 255] },
+ "states": {
+ "idle": { "frames": 4, "fps": 4, "loop": true, "action": "subtle breathing and blinking" },
+ "attack": { "frames": 4, "fps": 8, "loop": false, "action": "simple windup, strike, recovery attack pose sequence with no detached effects" },
+ "jump": { "frames": 4, "fps": 8, "loop": false, "action": "jump arc through body position only" },
+ "wave": { "frames": 4, "fps": 6, "loop": false, "action": "friendly hand wave gesture; arm changes clearly while feet stay planted" }
+ }
+}
+```
+
+`256` is a default variable, not a hidden constant. Change it through the request, then regenerate guides, prompts, extraction, and atlas from the same request.
+
+When `safe_margin` is omitted, the default is **proportional**: 9.4% of the cell dimension per axis, floored (256 → 24px, 128 → 12px, rect 192×208 → 18/19px). An explicit request/CLI value is absolute and wins as-is.
+
+**테이크(takes)** — 같은 상태의 후보/보강 스트립은 수동 병합이 아니라 request 로 선언한다:
+`"states": { "down_idle": { "frames": 4, ..., "takes": [{ "label": "blink", "frames": 4 }] } }`
++ `raw/<...>.takes/<label>.png`. 추출이 primary 뒤에 이어붙여 한 행의 프레임 풀을 만들고
+manifest `labels`("blink#0"…)로 큐레이션 뷰에 표시된다. 계약 상세: `docs/run-contract.md` §2.
+
+**실시간 계약** — `frames/` 는 (raw + request + 엔진)의 파생 캐시다. 큐레이션 뷰·compose·
+다운로드가 진입 시 `heal_run` 으로 stale 행을 자동 재유도하므로 "재추출" 을 별도 스텝으로
+지시할 필요가 없다 (raw 없는 행은 보존 + 관측 노트). 캐시 키 = 행별 `engine_revision`.
+
+Optional `fit` object (opt-in; absent means legacy behavior), exposed by `prepare_sprite_run.py` as `--fit-*` flags:
+
+- `"fit": { "resample": "kcentroid", "align_x": "foot-centroid", "align_y": "bottom" }` — pixel-art-aware downscale and jitter-free frame alignment. `align_x: "alpha-centroid"` (opt-in, perfectpixel-studio port) aligns the fringe-insensitive alpha-weighted centroid per frame — the strongest anti-jitter anchor for walk/run rows.
+- `"fit": { "pixel_unfake": true, "logical_height": 64, ... }` — true pixel-unfake extraction with no non-integer resampling (per-frame pitch detection → grid snap → kCentroid → run-wide shared palette → integer NEAREST). Fully deterministic code, applied at the row-extraction stage only; the style SSoT is the attached base/anchor reference, never prompt text.
+- Parameter reference, stage ownership, the pixel-density reference rule, and the before/after plain-twin + curator toggle: [`docs/pixel-unfake.md`](docs/pixel-unfake.md).
+
+Rectangular generation cells are allowed when the target motion benefits from hatch-pet-style row proportions:
+
+```json
+"cell": { "shape": "rect", "width": 192, "height": 208, "safe_margin_x": 18, "safe_margin_y": 16 }
+```
+
+The generated row uses the request cell shape. The final atlas is still consumed through `manifest.json.frame_layout`; runtime code must not assume square cells.
+
+## Prompt Contract
+
+The generated row prompt must come from `prompts/<state>.txt`. Do not hand-write frame counts into a separate prompt. The prompt requires:
+
+- exact state frame count from `sprite-request.json`
+- one complete full-body pose per invisible request-sized slot
+- safe margin from `sprite-request.json`
+- same locked anchor identity across every frame
+- motion-only row responsibility: the row should solve limb/body timing, not rediscover character details
+- flat chroma-key background from `sprite-request.json`
+- no shadows, glows, smears, speed lines, dust, scenery, text, UI, frame numbers, guide boxes, or detached effects
+
+If image generation produces guide boxes, visible labels, overlapping poses, backgrounds, cropped bodies, or identity drift, regenerate the row. Do not repair bad visual generation by drawing or tiling sprites locally.
+
+## Output Contract
+
+**Install from `curated/`, never from `frames/`.** `frames/` is pre-curation — the human's
+picks, pixel edits and transforms live in `curation.json` and are applied downstream. Copying
+`frames/` into an app silently ships the un-edited image and nothing fails. Stills →
+`export_curated_pngs.py` then `curated/`. Animation → the composed atlas + manifest.
+Contract: [`docs/run-contract.md`](docs/run-contract.md) §2-c.
+
+One worker owns exactly one character folder. The canonical run-dir folder tree — every input/output file and which ones drive the curation view — is owned by [`docs/run-contract.md`](docs/run-contract.md) §2. Do not let multiple workers write the same character folder. The `curation.json` sidecar schema (selected/order/transforms/pixel_unfake) and its folder-collision rule: [`docs/curation.md`](docs/curation.md).
+
+## Runtime Contract
+
+`manifest.json` must contain:
+
+- `game_input: "sprite-sheet-alpha.png"`
+- `degraded_static_fallback: false`
+- `animation.rows.<state>` with `frames`, `fps`, `durations_ms`, and `loop`
+- `frame_layout.rows.<state>[i]` absolute atlas rectangles
+
+Runtime must sample only the active rectangle. Rendering the whole atlas on one plane, guessing a grid, or showing a raw chroma row is a failed integration.
+
+Frame timing and cell reuse (2026-07-16, Aseprite-JSON 과 동형 패턴):
+
+- `frame_layout.rows.<state>` 는 재생(인스턴스) 순서 그대로이며, 같은 그림으로
+ 구워지는 복제 인스턴스는 **같은 rect 가 반복**된다 — 텍스처 칸은 고유 굽기당
+ 하나만 쓴다. 소비자는 지금처럼 프레임 인덱스 → rect 샘플링만 하면 된다.
+- `animation.rows.<state>.durations_ms[i]` 가 프레임별 표시 시간의 SSoT 다
+ (현재는 fps 등간격으로 채워짐). 배열이 있으면 fps 대신 이것을 따른다 —
+ 루프딜레이/홀드 프레임은 마지막 프레임 복제(rect 재사용, 텍스처 비용 0)나
+ duration 연장으로 표현한다.
+
+Static fallback is allowed only as explicit survival output when generation is blocked. It is not a sprite-gen pass and must not create `sprite-sheet-alpha.png`.
+
+## QA
+
+Automated checks (must all pass before reporting done):
+
+- `frames/frames-manifest.json.ok` is true
+- `sprite-sheet-alpha.report.json.ok` is true
+- every state has the declared frame count
+- no frame is empty or near-opaque background
+- no frame has excessive edge pixels or chroma-adjacent pixels
+- browser screenshots pass `scripts/check_visible_magenta.py` when used in a game
+
+Automatic correction-loop dry run:
+
+```bash
+$SPRITE_GEN_ROOT/.venv/bin/python $SPRITE_GEN_ROOT/scripts/run_correction_loop.py \
+ --run-dir <target>/assets/generated/sprites/<character-id> \
+ --states <state> \
+ --dry-run
+```
+
+This writes `correction-loop.report.json`, per-attempt `inspect.json`, `score.json`,
+and `correction-hints.txt`. A real regeneration loop must pass an explicit
+provider command; there is no silent fallback generator.
+Use `--min-attempts 2` for a live E2E that must exercise at least one provider
+regeneration even when the seed candidate already clears the score gate.
+
+### Motion Continuity (BLOCKING)
+
+Static identity QA is not enough — a row can have the right frame count, clean alpha, and consistent identity and still animate as garbage. Build the previews and review motion **as motion**:
+
+```bash
+$SPRITE_GEN_ROOT/.venv/bin/python $SPRITE_GEN_ROOT/scripts/preview_animation.py \
+ --run-dir <target>/assets/generated/sprites/<character-id>
+```
+
+The full verdict criteria (cyclic locomotion, loop seam, non-loop gestures, humanoid per-frame anatomy review, independent second opinion) live in [`docs/qa-motion.md`](docs/qa-motion.md). If a row fails motion continuity, **regenerate that row** — do not repair motion by drawing or re-timing frames locally. Record the per-state motion 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
+
+Leaf docs are one link deep from this hub. The tree groups them by the concern
+you are in — walk down the branch that matches your task, don't scan the flat
+list. Each doc owns its tables; SKILL.md and the others point rather than restate.
+
+```text
+sprite-gen (this SKILL.md = behavior contract + hub)
+│
+├─ CONTRACT & STRUCTURE ── "what files exist and what each stage promises"
+│ ├─ docs/run-contract.md # pipeline stage I/O table · canonical run-dir folder tree ·
+│ │ # curation-view display contract · run_revision/HTTP-409 ·
+│ │ # per-state salvage + stale backup · --pngs-dir import rule
+│ └─ docs/architecture.md # how scripts realize the contract: stages · cell geometry ·
+│ # idle-anchor ownership flow · extraction internals (SKILL wins on conflict)
+│
+├─ REQUEST AUTHORING ── "fill sprite-request.json before generating"
+│ ├─ docs/states-and-frames.md # which states · frame counts (4/5/6/8/9/12) · Quick Path JSON
+│ ├─ docs/subject-profiles.md # "subject": character|effect · sparse-floor 프로필 ·
+│ │ # 이펙트 베스트/워스트 프랙티스 (실측 배터리 근거)
+│ ├─ docs/pixel-unfake.md # fit / pixel_unfake params · plain-twin curator toggle · density refs
+│ └─ docs/chroma-alpha.md # chroma key branch table · --chroma-key auto · alpha cleanup
+│
+├─ GENERATION ── "raw/<state>.png from prompts (the one AI step)"
+│ ├─ docs/gen.md # sprite-gen gen provider CLI · verified PNG/report · image-gen shuttle
+│ ├─ docs/frame-interpolation.md # generative in-between (codex/grok) → take raw · auth prereqs · RIFE retire rationale
+│ └─ docs/seamless-video-loop.md # non-looping AI video clip → seamless loop: flow-matched cut + RIFE seam bridge
+│
+├─ CURATION ── "human/agent picks, edits, and downloads via the webview"
+│ └─ docs/curation.md # webview · curation.json schema (selected/order/transforms/
+│ # deleted/clones/revision/recolor.picked) · per-state salvage ·
+│ # frame CLONES · standalone image-candidate path · finished-sheet
+│ # re-edit (unpack)
+│
+├─ COLOURWAYS ── "bake N palette-swapped sheets from one base atlas"
+│ └─ docs/recolor.md # recolor / recolor-palette CLI · spec + report schema · exact vs
+│ # tolerance match · variants/ layout · curation blink-compare + adopt
+│
+├─ LAYER TRACKS ── "compose rows onto each other instead of generating every combination"
+│ └─ docs/layer-tracks.md # rig profiles + integer landmarks · track kinds (base /
+│ # action_overlay / prop_effect / full_body_override) ·
+│ # composite stack · manifest rig block · layers/ artifact tree ·
+│ # compose-layers CLI + prepare 의 레이어 키 반입/드롭 고지
+│
+├─ ENGINE EXPORT ── "adapt one composed atlas to existing game-engine loaders"
+│ └─ docs/engine-export.md # Aseprite JSON mapping · Phaser tags · Flame per-state hash
+│
+├─ SPECIALIZED INPUTS ── "not the plain animation-row path"
+│ ├─ docs/directional-anchor-workflow.md # directional / 45° anchor chains · hatch-pet locomotion
+│ └─ docs/sheet-slicing.md # multi-figure variant sheet → per-cell standing cuts (立ち絵, not rows)
+│
+├─ QA ── "verify motion as motion before reporting done"
+│ ├─ docs/qa-motion.md # Motion Continuity verdict criteria (BLOCKING)
+│ └─ docs/locomotion-curation.md # motion-phase guides · manual selected cycles · clean GIF export
+│
+└─ TROUBLESHOOTING ── "조용히 이상할 때 먼저 볼 표"
+ └─ docs/troubleshooting.md # 사이드카 스테일 가드/도장 경로 · 두-작성자 충돌 ·
+ # provider 무출력 행(env 위생) · 세로 스트립 전멸 · ffmpeg 500
+```
+
+Concept taxonomy (which doc owns each term, so agents don't guess):
+
+- `sprite-request.json`, cell, states, takes → run-contract.md §2 · states-and-frames.md
+- `run_revision`, `state_revision`, per-state salvage, `curation.stale-*.json` → curation.py + curation.md
+- `curation.json` fields (`selected`/`order`/`deleted`/`transforms`/`pixels`/`clones`/`pixel_unfake`/`revision`/`recolor.picked`) → curation.md
+- frame **clones** (duplicate instances, `source_frame_index`) → curation.md + compose consumers
+- `frame_layout`, `manifest.json` runtime contract → run-contract.md + this SKILL.md "Runtime Contract"
+- Aseprite-compatible Phaser / Flame JSON export → [`docs/engine-export.md`](docs/engine-export.md)
+- pixel-unfake `fit`, `.plain.png`/`orig/` twins → pixel-unfake.md
+- recolor spec / report / `variants/` bake + colourway adopt → recolor.md
+- `rig` profiles / landmarks, row `track` kinds, composite `layers` stack + `layers/` bake (`sprite-gen compose-layers`) → [`docs/layer-tracks.md`](docs/layer-tracks.md) (`sprite_gen/compose/layers.py` validates the declaration, `sprite_gen/compose/compose_layers.py` bakes it)
+- webview interactions (title-drag reorder, 넣기/빼기 toggle, 2-tier card, custom `data-tip` tooltip, recolor blink-compare) → `sprite_gen/curator/` (도메인 분할 `src/*.js` — 로드 순서 SSoT 는 index.html — + curator.css), described in curation.md + recolor.md
diff --git a/docs/architecture.md b/docs/architecture.md
new file mode 100644
index 0000000..e5f8260
--- /dev/null
+++ b/docs/architecture.md
@@ -0,0 +1,402 @@
+# sprite-gen — Implemented Architecture
+
+> Status: reference (describes the code as it actually is, v1.56.x, 2026-07-11).
+> Canonical behavior contract lives in [`../SKILL.md`](../SKILL.md); this doc
+> explains *how* the scripts realize that contract. If this doc and `SKILL.md`
+> ever disagree, `SKILL.md` wins and this doc is the bug.
+
+## 1. One sentence
+
+A character image plus a numeric request becomes a transparent sprite atlas by
+generating **one horizontal strip per animation state**, cleaning chroma,
+extracting poses as connected components, refitting each pose into a fixed cell
+(optionally through the deterministic pixel-unfake path), and packing the
+cells into a single sheet described by a runtime manifest.
+
+```mermaid
+flowchart TD
+ REQ["sprite-request.json<br/>(numeric SSoT)"] --> PREP["prepare_sprite_run.py"]
+ PREP --> GUIDES["references/layout-guides/&lt;state&gt;.png<br/>prompts/&lt;state&gt;.txt"]
+ GUIDES --> GEN["sprite-gen gen<br/>(codex or grok; one image per state — the only AI step)"]
+ GEN --> RAW["raw/&lt;state&gt;.png<br/>(one horizontal strip per state)"]
+ RAW --> EXTRACT["extract_sprite_row_frames.py<br/>chroma removal → connected components<br/>→ fit_to_cell or pixel-unfake path"]
+ EXTRACT --> FRAMES["frames/&lt;state&gt;/frame-N.png (+ frame-N.plain.png twin)<br/>frames/frames-manifest.json"]
+ FRAMES --> CURATE["serve_curation.py (optional webview)<br/>curation.json (non-destructive sidecar)"]
+ FRAMES --> COMPOSE["compose_sprite_atlas.py"]
+ CURATE -. "selected / transforms / pixel_unfake" .-> COMPOSE
+ COMPOSE --> ATLAS["sprite-sheet-alpha.png + manifest.json<br/>(frame_layout = runtime SSoT)"]
+ FRAMES --> QA["preview_animation.py<br/>qa/&lt;state&gt;-contact.png · qa/&lt;state&gt;.gif"]
+```
+
+## 2. Stage ownership (each script does one job)
+
+The canonical stage → script → input → output table is owned by
+[`run-contract.md`](run-contract.md) §1. This section explains the shared-import
+and locking behavior *behind* that table.
+
+The scripts are explicit pipeline commands, not hidden imports. The shared
+imports are `curation.py` (schema + transform math + the `frame_variant`/
+`frame_filename` resolver, kept single-source so the webview server and the
+compose scripts cannot drift) and `runio.py` (safe run-dir IO: a single-writer
+lock file `.sprite-gen.lock` taken by the extract/compose/export/unpack
+writers, plus atomic temp+`os.replace` writes for frames, atlas, manifests, and
+inspect/score/loop reports). The lock enforces the "one worker owns one
+character folder" rule at runtime — a second writer on the same run dir fails
+loudly with the holder's pid; a dead holder's lock is reclaimed automatically.
+`curation.json` stays outside the pipeline write lock: the webview writes it
+atomically and compose reads one consistent snapshot, so human edit sessions never
+block on a running compose. The curation write is, however, serialized against a
+`--force` re-import publish via the separate publish rwlock (`read_guard`/
+`publish_guard`), and a curation POST whose echoed run generation (`runRevision`)
+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`
+turns only that report into scores and correction hints, and
+`correction_loop.py` preserves the best candidate while optionally invoking an
+explicit provider command. In dry-run mode it never generates new pixels; it
+only proves the defect → score → hint path.
+
+## 3. The numeric SSoT: `sprite-request.json`
+
+Every run starts here. It owns the recipe consumed by both prompts and scripts:
+
+```json
+{
+ "version": 1,
+ "kind": "sprite-gen-request",
+ "engine": "component-row",
+ "character": { "id": "demo-hero", "description": "...", "base_image": "base-source.png" },
+ "cell": { "shape": "square", "size": 256, "safe_margin": 24 },
+ "chroma_key": { "name": "magenta", "hex": "#FF00FF", "rgb": [255, 0, 255] },
+ "chroma": { "mode": "rgb" },
+ "states": { "idle": { "frames": 4, "fps": 4, "loop": true, "action": "..." } },
+ "fit": { "pixel_unfake": true, "logical_height": 64, "palette_size": 24, "align_x": "foot-centroid", "align_y": "bottom", "segmentation": "components" },
+ "style": "...",
+ "motion_phase_guides": false
+}
+```
+
+- `character.base_image` is the canonical identity source for the *pre-idle*
+ phase only (see §5).
+- `chroma_key` is chosen by sampling the base image (`--chroma-key auto`) unless
+ forced. The key is picked **away from the subject's dominant hue** because
+ extraction eats chroma-adjacent tint (behavior contract:
+ [`chroma-alpha.md`](chroma-alpha.md)).
+- `states` is a free map; `frames`/`fps`/`loop`/`action` per state.
+- `fit` is optional (absent = legacy behavior): `resample`/`align_x`/`align_y`
+ tuning, or the full deterministic `pixel_unfake` mode (§6.1). Behavior
+ contract: [`pixel-unfake.md`](pixel-unfake.md).
+- `fit.segmentation` is `components` by default; opt-in `projection` is the
+ fused-pose recovery path (§6). The extract CLI can explicitly override it.
+- `chroma.mode` is `rgb` by default; opt-in `ycbcr` is owned by
+ [`chroma-alpha.md`](chroma-alpha.md). The extract and inspect CLIs can
+ explicitly override it.
+- `motion_phase_guides` only does something for 8-frame locomotion states.
+
+## 4. The cell model (read this — it is the most misunderstood part)
+
+There is exactly **one** `cell` object, and it drives **all three** geometry
+stages identically:
+
+1. **Generation** — `draw_guide()` renders a guide of `frames * cell_width`
+ wide × `cell_height` tall, and `row_prompt()` tells the model to treat the
+ strip as "invisible `cell_width`×`cell_height` frame slots".
+2. **Extraction** — `fit_to_cell()` refits each extracted pose into a
+ `cell_width`×`cell_height` transparent cell.
+3. **Atlas** — `compose_sprite_atlas.py` places every frame into a
+ `cell_width`×`cell_height` slot; the sheet is
+ `max_frames*cell_width` × `num_states*cell_height`.
+
+### 4.1 Square vs rect — variabilized, but a single shape
+
+`size` is a variable, not a hidden constant. The cell may be square or rect:
+
+```json
+"cell": { "shape": "square", "size": 256, "safe_margin": 24 }
+"cell": { "shape": "rect", "width": 192, "height": 208, "safe_margin_x": 18, "safe_margin_y": 16 }
+```
+
+`normalize_cell()` derives `shape` from `width == height`. **Default is square
+256.** Picking `rect` makes the cell taller (hatch-pet-style) — but that one
+shape is then used end-to-end, generation *and* output alike.
+
+### 4.2 Design note: one cell, NOT a two-stage tall→square transform
+
+A common mental model is "generate in a tall/portrait cell to save image area,
+then cut/place into a square cell for the final atlas." **The code does not do
+this.** There is no separate `gen_cell` vs `atlas_cell`; the generated strip and
+the final atlas share the same `cell`. If you generate rect, the atlas is rect;
+if you generate square, the atlas is square.
+
+What *is* true, and what makes a two-stage model only a small step away:
+extraction is **content-based, not slot-based**. `connected_components()` finds
+each pose blob, groups blobs by x-center, and `fit_to_cell()` crops the content
+bbox, rescales it preserving aspect ratio (`scale = min(...) ≤ 1.0`), and
+centers it in the target cell. So the refit already decouples a pose from the
+strip's pixel dimensions — a future change could feed a tall `gen_cell` to the
+guide/prompt and a square `atlas_cell` to `fit_to_cell`/compose without touching
+the extraction core. Today, that separation is not wired.
+
+## 5. Idle-anchor architecture (identity ownership)
+
+Stage 0 is a BLOCKING gate (the gate question and the five lock criteria live
+in [`../SKILL.md`](../SKILL.md)). The ownership rule:
+
+```text
+identity truth = accepted idle anchor
+motion truth = layout guide + paired/basis row when needed
+base truth = used only to create idle anchors, then dropped from row inputs
+```
+
+Base character images, original character sheets, and broad style references
+are allowed **only** before idle anchors are accepted. Once an idle anchor
+exists for the requested direction, later state rows must not attach the base
+character image as insurance. Re-attaching base makes the row model solve
+identity again and weakens the purpose of the idle-anchor workflow.
+
+Reference ownership flow:
+
+```mermaid
+flowchart TD
+ REFS["USER REFS / CHARACTER SHEET"] --> BASE["0. BASE IDLE 생성<br/>원본/캐릭터시트는 여기서만 사용<br/>비율/스타일/색/소품 고정"]
+ BASE --> ANCHORS["1. 방향별 IDLE ANCHOR 생성<br/>idle-front-right · idle-front-left<br/>idle-back-right · idle-back-left"]
+ ANCHORS --> DROP["BASE CHARACTER 폐기<br/>original refs 폐기 · character sheet 폐기<br/>이후 row 입력 금지"]
+ DROP --> BASIS["2. BASIS ROW 생성<br/>input: target-direction idle<br/>+ target-state layout only<br/>output: basis row"]
+ BASIS --> PAIRED["3. PAIRED ROW 생성<br/>input: paired-direction idle<br/>+ paired-state layout only + basis row<br/>output: paired row"]
+ PAIRED --> ASSEMBLE["4. GIF / SHEET 조립<br/>row crop · gif preview · frame-index QA"]
+```
+
+- The prompt text in `row_prompt()` enforces this ("Anchor lock" block):
+ identity comes from the anchor, the row owns motion only.
+- **Which image is "the accepted anchor" is code, not judgment** (`sprite_gen/curate/anchor.py`,
+ `sprite-gen anchor`): it resolves the human's pin (`curation.json` `anchors.<direction>`)
+ or, absent one, the anchor row's curated sequence head; bakes that instance with the
+ same primitives compose/export use (clone → pixel edits → transform → pixel-unfake
+ re-quantization); and writes the derived cache
+ `references/anchors/<dir>-anchor-x8.png` that row generation attaches. Reroll, the
+ generation plan, and the curation view's anchor chip all go through it, so the picture
+ the human approved on screen is the picture the next row inherits.
+- Default/simple states (`idle`/`jump`/`attack`/`wave`) skip the multi-anchor
+ chain. Directional / 45° / locomotion use the chain documented in
+ [`directional-anchor-workflow.md`](directional-anchor-workflow.md).
+
+## 6. Extraction internals (`extract_sprite_row_frames.py`)
+
+1. `remove_chroma_background()` — drop near-key pixels (color-distance ball,
+ `--key-threshold` default 96), clear fully-transparent RGB, then solve
+ chroma-tinted boundary blends into despilled RGB + soft alpha. In-band
+ blends are limited to key-distance `<= 2`; out-of-band blends use
+ `--fringe-unmix-reach` (default 4). Small trapped spill clusters are
+ despilled in place, while deeper key-tinted subject material survives.
+ With request `chroma.mode: "ycbcr"` or CLI `--chroma-mode ycbcr`, the
+ extractor uses `remove_chroma_background_ycbcr()` instead: border-mode key
+ detection and chrominance-plane flood fill tolerate shaded keys and JPEG
+ chroma noise. RGB remains the default.
+2. `connected_components()` — flood-fill alpha blobs, record bbox + area +
+ x-center.
+3. `separate_fused_poses()` — only when `fit.segmentation: "projection"` or
+ `--segmentation projection` is selected, projection profiles plus dynamic
+ programming find the minimum-cost vertical cuts for poses joined by thin
+ bridges. The default `components` path stays byte-identical and fails
+ loudly when the declared pose count cannot be recovered.
+4. `extract_component_frames()` — pick `frame_count` seed blobs by area, sort by
+ x-center, attach smaller noise blobs to the nearest seed; one group = one
+ pose. If it cannot find `frame_count` poses, the row is **blocked** (no
+ silent fallback). `--allow-slot-fallback` exists for debugging only and is
+ reported as `method: slots-explicit`.
+5. `fit_to_cell()` — crop, aspect-preserving downscale (`resample`:
+ lanczos | nearest | kcentroid), `align_x`/`align_y` placement, into the
+ cell. On `fit.pixel_unfake` runs this legacy path still runs once per
+ frame to produce the `.plain.png` twin (§6.1); the canonical frame goes
+ through the pixel-unfake path instead.
+6. `inspect_frames()` — per-frame QA: empty/sparse, edge bleed, chroma-adjacent
+ pixels, size outliers → `frames-manifest.json`.
+
+This is intentionally closer to hatch-pet's cleanup than to a plain
+`magick -transparent`.
+
+### 6.1 Pixel-unfake path (`fit.pixel_unfake`, deterministic)
+
+The behavior contract is [`pixel-unfake.md`](pixel-unfake.md); this is how
+the code realizes it. The path is unfake.js/pixeldetector-style and contains
+**no model call and no non-integer resampling** — same input, same output:
+
+1. **Pitch detection** — `detect_pixel_pitch()` scores each candidate pitch by
+ edge-to-gridline alignment (the fraction of color boundaries landing within
+ ±w of grid lines, minus the chance expectation `(2w+1)/p`) and takes the
+ argmax. Detection runs **per frame** and **each frame is snapped with its
+ own detected pitch** (maintainer 2026-07-20, plan `sprite-gen/per-frame-pixel-grid`:
+ forcing a strip-wide pitch onto a frame accumulates the measurement gap
+ across the width and cuts through block centers). The **median** across
+ confident frames (collapse-filtered) is kept only as the fallback for frames
+ whose own detection is inconclusive — applying it emits a per-frame warning,
+ and a frame whose own pitch deviates from the consensus is warned, never
+ overridden. If every frame fails, `fit.pitch_hint` (usually the base
+ image's detected pitch) is used. `estimate_pixel_grid_runlen()` then
+ derives an independent modal run-length estimate; `crosscheck_pitch_runlen()`
+ records divisor/harmonic or axis-ratio disagreement as observable warnings.
+ The run-length estimate is a crosscheck only and never silently replaces the
+ canonical grid score.
+2. **Grid-phase snap** — the phase is **measured, not inferred from the pitch
+ detector**: `_best_phase()` scores real cell uniformity per frame and picks
+ the best offset, `refine_edges_to_boundaries()` then pulls each interior cut
+ onto a real colour boundary (±pitch/3), and `snap_by_edges()` collapses each
+ block to one output pixel via `_dominant_block_color()` voting. The
+ histogram phase that `_axis_refine()` returns alongside the pitch is **not**
+ used here — it can sit up to pitch/2 off the true phase, which is outside the
+ ±pitch/3 recovery window and merged a character's eye from 4 rows into 3
+ (plan `sprite-gen/frame-pitch-consensus-eats-a-row`; see
+ [`pixel-unfake.md`](pixel-unfake.md) "위상은 근사가 아니라 실측으로 고른다").
+ `detail_bias` (default true) prefers a near-black minority cluster
+ (share ≥ 0.40, luma < 70/255) so eyes and 1px outlines survive dominant voting.
+3. **Physical cap only — no conform squash** — `conform_row_logical()` keeps the
+ snapped native logical size and only enforces the physical cell cap
+ (kCentroid, `_kcentroid_downscale()`), warning observably when a frame hits
+ it. Squashing to a declared `logical_height` was removed (maintainer
+ 2026-07-14/17: it merges cells and eats detail); `fit.conform` is now
+ rejected loudly if present in a request.
+4. **Alpha binarization** — `binarize_alpha()`, applied on the outputs of steps
+ 2-3 (snap, then cap) so every logical pixel is fully opaque or fully
+ transparent.
+5. **Inter-frame registration** — `register_row_frames()` aligns frames on the
+ stable upper body (alpha overlap, small slack), so locomotion rows don't
+ jitter on per-frame content changes.
+6. **Shared palette** — `build_shared_palette()` + `apply_palette()`: one
+ run-wide median-cut palette (`palette_size`) kills frame-to-frame color
+ flicker.
+7. **Outline** — `enforce_outline()` draws a uniform 1px silhouette outline.
+8. **Integer placement** — `fit_pixel_unfake()` / `row_placement()` upscale by
+ the integer factor `cell_height // logical_height` (NEAREST) and place with
+ offsets honoring `align_x`/`align_y`. `align_x: "alpha-centroid"` computes
+ the fringe-insensitive alpha-weighted centroid per frame (alpha ≤ 10 is
+ ignored), cancelling residual horizontal registration jitter without
+ flattening vertical motion arcs.
+
+Alongside each canonical `frame-N.png`, the extractor writes two pre-pixel-
+perfect twins (same strip through the legacy fit path; if twin production fails
+it is a warning, only that twin is dropped): the cell-sized `frame-N.plain.png`
+and the hi-res `orig/frame-N.png` (legacy fit at S×cell, `S = min(4, 1024//cell)`,
+display-only). The curation webview toggles the display to `orig/` when present
+(crisp "off = original", else `.plain.png`), while `curation.json.pixel_unfake:
+false` makes compose/GIF/PNG export bake the cell-sized `.plain.png` variant —
+missing plain files are a hard error, not a silent fallback. The hi-res twin
+lives in a subdir so non-recursive `frame-*.png` globs (inspect, measure) never
+pick it up. The chosen variant is recorded as `frame_variant` in reports and the
+manifest. Display-contract SSoT: [`run-contract.md`](run-contract.md) §3.
+
+## 7. Curation sidecar (`curation.json`)
+
+Optional, **non-destructive**. Written by the webview (`serve_curation.py`),
+consumed by `compose_sprite_atlas.py` and `compose_selected_cycle.py`. The
+original `frames/<state>/frame-N.png` files are never rewritten.
+
+```json
+{ "version": 1, "kind": "sprite-gen-curation", "run_revision": "9f3c1a0b7e2d4c58",
+ "pixel_unfake": true,
+ "states": { "idle": { "selected": [0,2,3], "order": [0,2,3,1],
+ "transforms": { "0": { "rotate": 15, "scale": 1.2, "dx": 10, "dy": -8, "flipX": 0 } } } } }
+```
+
+- `run_revision` — **required** frame-generation stamp. `load_curation` applies the
+ sidecar only when it matches the current run; a mismatched **or missing** stamp is
+ stale and ignored (all-frames default, stderr-warned) — a re-import/re-extract or a
+ legacy/hand-written sidecar never applies to frames it isn't proven to belong to.
+- `pixel_unfake` — top-level bake decision: `false` → compose/export bake the
+ `.plain.png` twins (§6.1); absent/`true` → canonical `frame-N.png`.
+- `selected` — 0-based indices in play order; absent → all frames in order.
+- `order` — webview-owned full display order (sequence row then candidate-pool
+ row) so reopening the curator restores both rows; compose ignores it and
+ keys off `selected`.
+- `transforms` — per-index affine (`rotate`, `scale`, `dx`/`dy`, `shx`/`shy`
+ shear, `flipX`), applied at compose time **inside** the cell so atlas
+ geometry never changes.
+- A state missing from the sidecar uses the all-frames identity default — an
+ explicit default, not a silent fallback.
+- `curation.py` owns the schema + transform math (single source for server and
+ compose). Full field semantics: [`curation.md`](curation.md).
+
+## 8. Runtime contract (`manifest.json`)
+
+`manifest.json.frame_layout` is the runtime SSoT. Game code consumes absolute
+rectangles and must not recover frame rects from alpha at runtime.
+
+Required fields:
+
+- `game_input: "sprite-sheet-alpha.png"`
+- `degraded_static_fallback: false`
+- `animation.rows.<state>` → `{ row, frames, fps, loop }`
+- `frame_layout.rows.<state>[i]` → `{ x, y, w, h }` absolute atlas rects
+- `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.
+
+## 9. Output directory (one worker owns one character folder)
+
+The canonical run-dir folder tree (every input/output file, plus which files drive
+the curation view) is owned by [`run-contract.md`](run-contract.md) §2. The
+single-writer lock that enforces "one worker owns one character folder" at runtime is
+`runio.py`'s `.sprite-gen.lock` (§2 above).
+
+## 10. Inverse paths (editing finished assets)
+
+- `unpack_atlas_run.py` rebuilds a curator-ready run dir from a finished atlas
+ (layout source priority: `--grid` > `--manifest` > auto-detect), or imports a
+ folder of separate PNGs via `--pngs-dir` (carries a sibling `meta.json` for
+ iso tile/anchor grid overlay).
+- `export_curated_pngs.py` bakes the curation transform back into named PNGs
+ (the deliverable for imported still sets like furniture); the single atlas is
+ the deliverable for animation frames / runtime perf.
+
+## 11. Relationship to hatch-pet
+
+`sprite-gen` is inspired by the Apache-2.0 `hatch-pet` skill but ships no pet
+assets. Shared DNA: one image-gen job **per row/state**, layout-guide grounding,
+chroma cleanup, deterministic assembly scripts, contact-sheet/video QA.
+
+Key differences:
+
+| | hatch-pet | sprite-gen |
+|---|---|---|
+| Atlas | fixed 8×9, fixed 192×208 cell, 9 fixed pet states | variable state list, variable cell (square default 256) |
+| Cell shape | fixed rect 192×208 | square or rect, one config end-to-end (§4) |
+| Frame cut | slot-based geometry | content-based connected components + refit (+ pixel-unfake path) |
+| Identity | canonical base reference reused on every row | idle-anchor ownership; base dropped after anchors |
+| Curation | n/a | non-destructive `curation.json` + webview |
+| Inverse | n/a | unpack atlas / import PNG pack / export stills |
+| Packaging | `pet.json` + `spritesheet.webp` into `~/.codex/pets/` | runtime `manifest.json` `frame_layout` |
+
+Both generate **row-by-row, one state per image-gen call** — neither produces a
+whole atlas in a single generation.
+
+## Related
+
+- [`../SKILL.md`](../SKILL.md) — canonical behavior contract
+- [`pixel-unfake.md`](pixel-unfake.md) — `fit`/`pixel_unfake` behavior contract
+- [`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/assets/breathe-editor.png b/docs/assets/breathe-editor.png
new file mode 100644
index 0000000..8c8c3bd
Binary files /dev/null and b/docs/assets/breathe-editor.png differ
diff --git a/docs/assets/chroma-fullbody-illustration-green.png b/docs/assets/chroma-fullbody-illustration-green.png
new file mode 100644
index 0000000..48cf90b
Binary files /dev/null and b/docs/assets/chroma-fullbody-illustration-green.png differ
diff --git a/docs/assets/chroma-fullbody-illustration-magenta.png b/docs/assets/chroma-fullbody-illustration-magenta.png
new file mode 100644
index 0000000..42ca557
Binary files /dev/null and b/docs/assets/chroma-fullbody-illustration-magenta.png differ
diff --git a/docs/assets/chroma-fullbody-pixelart-green.png b/docs/assets/chroma-fullbody-pixelart-green.png
new file mode 100644
index 0000000..bcc5af6
Binary files /dev/null and b/docs/assets/chroma-fullbody-pixelart-green.png differ
diff --git a/docs/assets/chroma-fullbody-pixelart-magenta.png b/docs/assets/chroma-fullbody-pixelart-magenta.png
new file mode 100644
index 0000000..131398e
Binary files /dev/null and b/docs/assets/chroma-fullbody-pixelart-magenta.png differ
diff --git a/docs/assets/chroma-peel-illustration-before-after.png b/docs/assets/chroma-peel-illustration-before-after.png
new file mode 100644
index 0000000..7c552b9
Binary files /dev/null and b/docs/assets/chroma-peel-illustration-before-after.png differ
diff --git a/docs/assets/chroma-peel-pixelart-before-after.png b/docs/assets/chroma-peel-pixelart-before-after.png
new file mode 100644
index 0000000..f219e28
Binary files /dev/null and b/docs/assets/chroma-peel-pixelart-before-after.png differ
diff --git a/docs/assets/curator-drag-update.gif b/docs/assets/curator-drag-update.gif
new file mode 100644
index 0000000..5eaf16b
Binary files /dev/null and b/docs/assets/curator-drag-update.gif differ
diff --git a/docs/assets/curator-iso.png b/docs/assets/curator-iso.png
new file mode 100644
index 0000000..7db5e76
Binary files /dev/null and b/docs/assets/curator-iso.png differ
diff --git a/docs/assets/cutout-demo.png b/docs/assets/cutout-demo.png
new file mode 100644
index 0000000..272748a
Binary files /dev/null and b/docs/assets/cutout-demo.png differ
diff --git a/docs/assets/demo-character.gif b/docs/assets/demo-character.gif
new file mode 100644
index 0000000..840716a
Binary files /dev/null and b/docs/assets/demo-character.gif differ
diff --git a/docs/assets/demo-furniture.gif b/docs/assets/demo-furniture.gif
new file mode 100644
index 0000000..9575682
Binary files /dev/null and b/docs/assets/demo-furniture.gif differ
diff --git a/docs/assets/subject-effect-ember.gif b/docs/assets/subject-effect-ember.gif
new file mode 100644
index 0000000..0188b3b
Binary files /dev/null and b/docs/assets/subject-effect-ember.gif differ
diff --git a/docs/assets/subject-effect-sigil.gif b/docs/assets/subject-effect-sigil.gif
new file mode 100644
index 0000000..9fb6c47
Binary files /dev/null and b/docs/assets/subject-effect-sigil.gif differ
diff --git a/docs/assets/subject-effect-venom.gif b/docs/assets/subject-effect-venom.gif
new file mode 100644
index 0000000..318a388
Binary files /dev/null and b/docs/assets/subject-effect-venom.gif differ
diff --git a/docs/assets/subject-effect-wisp.gif b/docs/assets/subject-effect-wisp.gif
new file mode 100644
index 0000000..f9b61f9
Binary files /dev/null and b/docs/assets/subject-effect-wisp.gif differ
diff --git a/docs/assets/subject-effects-gallery.png b/docs/assets/subject-effects-gallery.png
new file mode 100644
index 0000000..ce058f3
Binary files /dev/null and b/docs/assets/subject-effects-gallery.png differ
diff --git a/docs/chroma-alpha.md b/docs/chroma-alpha.md
new file mode 100644
index 0000000..4d04a42
--- /dev/null
+++ b/docs/chroma-alpha.md
@@ -0,0 +1,48 @@
+# Chroma Key & Alpha Cleanup — sprite-gen reference
+
+> `SKILL.md` 허브에서 분리한 시나리오 상세. 크로마 키를 고르거나(특히 소재색이 키와 인접할 때), 추출 후 소재색 손실을 진단할 때 이 문서를 따른다. 분기표 SSoT 는 image-gen SKILL.md 최상단 게이트이고, 이 문서는 그 규칙의 sprite-gen 쪽 상세다.
+
+## Key selection
+
+`prepare_sprite_run.py` chooses a chroma key by sampling the base image unless the request forces one. The generated character must not use the chroma color or chroma-adjacent colors.
+
+**Choose the chroma away from the subject's dominant hue — do not blindly default to magenta.** The hard key erase is a color-distance ball around the key (`--key-threshold`, default 96): a subject color inside that radius is deleted no matter where it sits. Antialias fringe is no longer erased by a separate peel; key/subject boundary blends are **unmixed into despilled RGB + partial alpha** when they are close enough to the keyed region. In-band blends are limited to key-distance `<= 2`, out-of-band blends use `--fringe-unmix-reach` (default 4), and deeper key-tinted *interior* subject colors (hot pink / purple under a magenta key) survive byte-identical. Small strongly key-tinted clusters buried inside the subject (generator spill) are despilled in place — see below. Key choice still decides quality:
+
+- Pink / purple / magenta-family subjects (꽃, 씨앗봉투) → use **green** `#00FF00`; their edge blend under a magenta key wastes real silhouette pixels.
+- Deep-red / crimson / wine hair or clothing is **magenta-adjacent** (both high R). Use **green** for red/crimson/warm subjects.
+- Green/teal/olive subjects → use **magenta**.
+- Blue subjects → avoid cyan/blue keys; magenta or green.
+- Both pink *and* green in one subject → pick the key farther from the larger/more important material, verify both survive after extraction, and prefer `--chroma-key auto` (distance-scored).
+
+## `--chroma-key auto`
+
+When unsure, let `--chroma-key auto` sample the base. It excludes the detected flat opaque chroma background from subject scoring, then scores candidates by distance from the remaining subject pixels. `auto` refuses a key whose nearest subject pixel falls inside the erase radius when a safer candidate exists, records candidate `score`, `min_subject_distance`, `clears_erase_radius`, and `background` metadata in the request, and warns (stderr) when no candidate clears the subject — so a small but critical feature (eyes, a gem, an ear lamp) under 1% of the pixels is not silently deleted. Only force a key when you know the subject hue is safely far from it. Verify after extraction that the dominant subject color survived — a black-where-it-should-be-colored frame means the key was adjacent to the subject.
+
+## Extraction-side alpha cleanup
+
+`extract_sprite_row_frames.py` owns alpha cleanup for sprite rows. Three passes, in order:
+
+1. **Hard key cut** — pixels within `--key-threshold` of the key (and already-transparent input) are erased; alpha=0 pixels get their RGB cleared to `(0,0,0)` (no halo).
+2. **Soft-alpha unmix** — key-tinted blends near the keyed region are separated into despilled RGB + **partial alpha**: the blend model `observed = (1-k)·subject + k·key` is solved from the key-tint score, so antialiased silhouettes keep their coverage ramp instead of collapsing into a binary staircase. In-band blends (inside `--fringe-key-threshold`) are eligible only at key-distance `<= 2`; out-of-band blends use `--fringe-unmix-reach` (default 4). This preserves deeper key-tinted material while fixing trapped blend pockets between hair strands.
+3. **Trapped-spill despill** — a small connected cluster of key-tinted pixels (≤ `--spill-max-fraction` of the subject, default 0.005) containing at least one strongly tinted pixel is generator spill, wherever it sits: its color is corrected in place with alpha kept (no pinholes). Large key-tinted regions are intentional material and are never touched; marginally warm subject colors (skin) never qualify.
+
+The unmix/spill tunables live in the run's `sprite-request.json` under `chroma` (`unmix_reach`, `spill_max_fraction`) — the extractor reads them from there, CLI flags override, and the effective values are written back to the request so every run records what produced it. Then it extracts connected components and writes fresh transparent cells. The pixel-unfake path is unaffected: it binarizes alpha downstream (α ≥ 128 → opaque), so soft-alpha input degrades gracefully. This is intentionally closer to hatch-pet than to simple `magick -transparent`.
+
+If component extraction cannot find the declared frame count, the row is blocked. `--allow-slot-fallback` exists for explicit debugging only; it must be reported as `slots-explicit` and is not the default path.
+
+## `chroma.mode: "ycbcr"` — chrominance-plane matting (opt-in)
+
+Port of perfectpixel-studio's `chroma.go` (MIT, see NOTICE). The default RGB path above classifies pixels by RGB distance to the key, so a *shaded or gradient* key background (dark green under a green key) or JPEG 4:2:0 chroma noise can drift past the erase radius and survive. The ycbcr path ignores luma entirely and separates on the CbCr plane, where shading does not move the key cluster:
+
+1. **Key detection** — CbCr histogram *mode* of corner patches + thin borders (never a mean — a mean drifts on gradients); when enough border samples sit in the declared key's chroma family, that cluster wins outright.
+2. **Soft matte** — Hermite smoothstep alpha ramp over CbCr distance (24 → 72).
+3. **Despill** — subtracts only the key-direction chroma component inside the despill band; colors orthogonal to the key keep their saturation.
+4. **Border flood fill** — 4-connected from the image borders through lenient key-chroma pixels; interior key-family pixels (gems, highlights) never connect and survive.
+5. **Self-diagnostic rematte** — an opaque-fraction spike (subject erased) or declared-key residue spike (background survived) triggers a rematte with the declared pure key; the better result wins and the fallback is reported via extraction warnings (never silent).
+
+Select with request `chroma.mode: "ycbcr"` or `--chroma-mode ycbcr`. **The default stays `"rgb"`**: on clean flat-key raws the RGB path's exact-solve unmix already removes key tint completely, while ycbcr's fixed-scale despill leaves a small tinted soft-edge halo — ycbcr is for degraded sources (shaded/gradient backgrounds, JPEG chroma noise), not a general upgrade.
+
+## Related
+
+- [`../SKILL.md`](../SKILL.md) — 필수 게이트 (크로마 키 소재색 분기 + 변환 후 소재색 보존 검증)
+- [`architecture.md`](architecture.md) — `remove_chroma_background` 추출 내부 단계
diff --git a/docs/curation.md b/docs/curation.md
new file mode 100644
index 0000000..9c7f70e
--- /dev/null
+++ b/docs/curation.md
@@ -0,0 +1,258 @@
+# Curation — webview, standalone view, finished-sheet editing, `curation.json` — sprite-gen reference
+
+> `SKILL.md` 허브에서 분리한 시나리오 상세. 큐레이션뷰를 띄우거나(파이프라인 스텝 3.5 / 클로징 스텝 5), 임의 이미지 후보군을 비교·선택하거나, 완성된 시트를 다시 편집하거나, `curation.json` 스키마를 다뤄야 할 때 이 문서를 따른다.
+
+## Standalone Curation View (이미지 후보 큐레이션 — 스프라이트 아님)
+
+"큐레이션(뷰) 해줘 / 이미지 후보 보여줘 / 나란히 비교 / 골라볼게" 로 진입했고 대상이 **애니메이션 프레임이
+아니라 임의 이미지 후보군**(아이콘 시안, 로고, 생성 초안)이면, 파이프라인 없이 이 단독 경로만 쓴다.
+에이전트 채팅 surface 는 이미지를 못 보여주는 경우가 많다 — 이 웹뷰가 그 표시 수단이다.
+
+```bash
+export SPRITE_GEN_ROOT=/path/to/sprite-gen
+SG=$SPRITE_GEN_ROOT
+STAGE=$(mktemp -d); mkdir -p "$STAGE/pngs"
+cp <후보들> "$STAGE/pngs/" # 의미 있는 이름으로: 1-hub-cube.png, 2-hook-plug.png ... (timestamp/uuid 파일명 금지)
+# 성격이 다른 이미지를 한 통에 붓지 마라 — 하위폴더 = 큐레이터 줄(state) 하나.
+# 예: pngs/portraits/ (표정 세트 줄) + pngs/idle/ (idle 줄).
+# 셀 크기는 전 그룹 공유 최대치이므로, 거대한 레퍼런스는 미리 다른 후보 크기대로 축소해 넣는다.
+# 소스 1급 수용(run-contract.md §4): pngs/_base/<img> → 베이스 참조 줄, pngs/<group>/_refs/<role>-<name>.png
+# (role=anchor|basis|guide) → 그 줄의 생성 재료 칩. _base·_refs 는 예약 폴더라 큐레이터 줄이 되지 않는다.
+"$SG/.venv/bin/python" "$SG/scripts/unpack_atlas_run.py" --pngs-dir "$STAGE/pngs" --out-dir "$STAGE/run" --force
+nohup "$SG/.venv/bin/sprite-gen" curation --run-dir "$STAGE/run" --lang ko > "$STAGE/server.log" 2>&1 &
+sleep 2
+PORT=$(lsof -nP -a -p $! -iTCP -sTCP:LISTEN | awk 'END{sub(".*:","",$9); print $9}') # stdout 버퍼링 때문에 log 대신 lsof 로 포트 확보
+curl -s -o /dev/null -w "%{http_code}" "http://127.0.0.1:$PORT/" # 200 = positive proof, 그 후 URL 보고
+```
+
+- **캐릭터/스프라이트 세트 표시 기본지침 = "실제 사용하는 컷"** (maintainer 확정 2026-07-12 — "대표컷"
+ 아님). 줄(state)은 `base`, `anchor-idle-down`, `idle`, `walk` … 처럼 개념 단위로 만들고, 각 줄의
+ 내용은 그 개념의 **실물**이다: base·방향 앵커처럼 실물이 1장이면 그 1장, 런타임 상태면 매니페스트가
+ 실제 재생하는 프레임들을 재생 순서대로 **전부**. 임의 대표컷 발췌(예: `frame-0` 한 장만) 금지 —
+ 게임이 행 전체를 돌리는데 한 장만 보여주면 검수 대상이 왜곡된다. 아틀라스 시트 통짜·raw
+ 멀티프레임 row 이미지·비교용 합성 시트를 그대로 붓는 것도 금지 (셀 크기 폭발 + 선택 단위 흐림).
+ 파이프라인 산출물 검수는 이 standalone 경로가 아니라 run dir 를 직접 서빙하는 파이프라인
+ 큐레이션(아래 스텝 3.5)이 우선이다.
+- 사용자 로컬이면 브라우저 자동 오픈이 기본, headless/원격이면 `--no-open` + URL 전달.
+- 선택 회수는 `"$STAGE/run/curation.json"` 의 `selected` 인덱스를 파일명으로 역매핑. 비어 있으면 다시 묻는다 — 추측 진행 금지.
+- 결정 후 서버 kill + `$STAGE` 정리. 후보가 1장이면 큐레이션이 아니다 — 경로만 보고하고 끝.
+
+## Curation Webview (파이프라인 스텝 3.5) — 캐릭터 검수의 정식 뷰
+
+**캐릭터/스프라이트 검수의 정식 뷰 = run dir 를 직접 서빙하는 이 파이프라인 뷰다** (maintainer 채택 2026-07-12).
+이 뷰의 네 표시 요소(베이스 참조 줄 · 생성 재료 ref 칩 · 픽셀 격자 · 원본 화질 토글)와 그것을
+채우는 `/api/run` payload 는 [`run-contract.md`](run-contract.md) §3 이 계약으로 소유한다 — 어떤
+에이전트가 뷰를 차려도 같은 경험이 나오도록 스크립트가 강제한다. 아래는 그 뷰의 상호작용(선택/재배열/
+변형)과 시나리오다.
+
+```bash
+$SPRITE_GEN_ROOT/.venv/bin/sprite-gen curation \
+ --run-dir <target>/assets/generated/sprites/<character-id>
+```
+
+**세 진입 형식이 전부 살아 있다** — 위 콘솔 스크립트, 모듈 형식, 그리고 파일 이름을 이미 쓰고
+있는 호출자를 위한 래퍼:
+
+```bash
+$SPRITE_GEN_ROOT/.venv/bin/python -m sprite_gen.serve.serve_curation --run-dir <run-dir>
+$SPRITE_GEN_ROOT/.venv/bin/python $SPRITE_GEN_ROOT/scripts/serve_curation.py --run-dir <run-dir>
+```
+
+셋은 인자 선언 하나(`add_arguments`)와 구현 하나(`run`)를 공유하므로 플래그도 기본값도 갈릴 수
+없다 (`tests/test_curation_cli_entrypoint.py`). 콘솔 스크립트를 먼저 쓰는 이유는 기능이 아니라
+인터프리터다 — shebang 이 자기 venv 를 가리켜서 고를 것이 없다. 이 변경 이전에 만든 venv 에는
+`bin/sprite-gen` 이 없으니 `pip install -e .` 를 한 번 다시 돌리거나 위 두 형식을 쓴다.
+
+This launches a standalone local webview (no orchestrator dependency — usable from Claude Code Desktop, the Codex app, or any host with the skill installed). It shows every state's frames side by side so you can compare them in parallel. Two rows per state: a **sequence** row (the selected play order, saved to `curation.json.selected`, baked left-to-right by compose) and a **candidate pool** row below it (unselected frames, e.g. an extra generated take). A per-frame transform (drag the stage = move, bottom-right magnifier = scale, top handle = rotate, side handle = shear) corrects an off angle/position. A live preview animates the selected frames at the state fps, with play/pause, frame stepping, and a 0.25×–4× speed control.
+
+### Colourway (recolor) compare and pick
+
+When the run has a bake under `variants/` (`recolor.report.json` present), the view
+adds a colourway section above the state rows (`curator/src/recolor.js`):
+
+- **Blink comparison** — one stacked stage holds every variant sheet; hovering a
+ list row swaps the visible sheet in place. Side-by-side eye travel loses small
+ palette shifts; blink does not.
+- **Frame-cell thumbnails** — one cell cropped from the sheet via
+ `manifest.frame_layout` (first frame of the first state). Origin assumptions
+ are forbidden; no layout → no crop style.
+- **Adopt** writes `curation.json.recolor.picked` as the variant **name**. A name
+ the current bake no longer produces is kept and flagged (`pickedKnown: false`),
+ never silently cleared. A save from a run without a recolor section does not
+ author the field; the server carries the existing pick over (same carry
+ contract as `anchors`).
+
+Bake the colourways first with `sprite-gen recolor` — command, spec, and report
+schema: [`recolor.md`](recolor.md).
+
+**Card interaction model** (maintainer 2026-07-15 — a stray click must never add/remove a frame):
+
+- **Move between rows / reorder = grab the card TITLE and drag** (the whole header strip is the handle; there is no separate ⠿ grip). A plain click on the card does nothing.
+- **넣기/빼기 (add/remove) button** in the card footer is the only click-toggle between sequence ⇄ pool (up arrow = add to sequence, down arrow = remove to pool). No color emphasis — direction icon only.
+- **Duplicate = the ⧉ button in the card header.** A clone is a full instance (own transform/pixels/order slot) that bakes the source frame's image; its footer archive button deletes the clone. See the `clones` field below.
+- **Card layout**: header = title (drag handle) + duplicate/zoom icons; footer tier 1 = size + transform readout (info); footer tier 2 = flip/reset + 넣기·빼기/archive. Hovering the title shows the full frame name in a **custom `data-tip` tooltip** (not native `title=`) whose text is selectable/copyable — so a collaborating agent can lift the exact frame path.
+
+The webview UI is bilingual (English / Korean). Pass `--lang en|ko` to match the user's language (it is also toggleable in the app); default is `en`. For isometric sets imported with `--pngs-dir`, a sibling `meta.json` tile/anchor adds a ground-grid overlay for aligning furniture with the shear handle.
+
+All edits are **non-destructive**: they are saved to `curation.json` in the run dir, and the original `frames/<state>/frame-N.png` files are never rewritten. The compose step bakes `curation.json` deterministically, so any curation decision is reversible by editing or deleting that file.
+
+**실시간 계약 (maintainer 확정 2026-07-14/15)** — 뷰에는 '재추출' 개념이 없다. 뷰가 보여주는 것은
+항상 (raw + request + 현재 엔진 + 큐레이션)의 실시간 결과다: `/api/run`·`/api/progress` 가
+요청마다 stale 프레임 캐시를 자가치유(heal)하고, 엔진이 바뀌면 열려 있는 페이지도 다음 폴에서
+자동 재계산·리로드된다 (자세한 캐시 키 계약은 run-contract.md §2 frames-manifest 절).
+상단 버튼 3종(**아틀라스/PNG/GIF 다운로드**, `GET /download/{atlas,pngs,gifs}`)은 '게임에 적용'이
+아니라 지금 보이는 라이브 상태를 그 자리에서 계산해 zip 으로 내려주는 **다운로드**다 — 계산
+산출물은 런 폴더에도 남는다 (런 폴더 = 작업장, 다운로드 = 핸드오프).
+
+This step is optional. When there is no `curation.json`, every state uses all extracted frames in order with identity transform — an explicit default, not a silent fallback.
+
+### 생성 트리거 관용구 (SSoT = `src/gen-trigger.js`)
+
+서버에서 생성이 도는 모든 버튼(보간 `tween.js`, 리롤 `row-controls.js`, 이후 추가되는 것)은
+한 가지 표면 계약만 쓴다 — **클릭 = 파라미터 팝오버(`.gen-pop`) 토글 → 공용 모델
+select(GPT=codex / Grok=grok, `makeProviderSelect`) → 생성 버튼 → `runServerGeneration`**
+(스피너 → 진행도 워치 → POST → 에러 언랩 → 성공 시 뷰 새로고침). 모델 표기·실행 시퀀스의
+유일한 소유자는 `gen-trigger.js` 다. 트리거마다 다른 제스처(Alt클릭 모델 선택 등)를 만들지
+않는다 (maintainer 2026-07-19 통일 확정 — 회귀: 보간=팝오버 select, 리롤=Alt클릭으로 갈라져
+있었다). 줄 단위 다운로드(저장 팝오버)는 생성이 아니므로 별도 파일 `row-export.js` 소유.
+
+## Editing a finished sprite sheet (no `frames/` source)
+
+When only the combined sheet survives (a deployed asset whose run dir is gone), rebuild a curator-ready run dir with the inverse step before curating:
+
+```bash
+# default: auto-detect the grid by reading the atlas alpha
+$SPRITE_GEN_ROOT/.venv/bin/python $SPRITE_GEN_ROOT/scripts/unpack_atlas_run.py \
+ --atlas <sheet>.png --out-dir <run-dir> --force
+
+# when a manifest carries exact rectangles (position-faithful)
+.venv/bin/python .../unpack_atlas_run.py --manifest <manifest>.json [--direction <dir>] --out-dir <run-dir>
+
+# when a human states the grid, e.g. "8x9"
+.venv/bin/python .../unpack_atlas_run.py --atlas <sheet>.png --grid 8x9 --out-dir <run-dir>
+```
+
+The chosen layout source is always reported (`manifest` / `grid-explicit` / `auto-detect`) and stored in `unpack-source.json` for a later writeback. Then point `sprite-gen curation` at the new run dir. Auto-detect is the no-instruction default; `--grid` and `--manifest` are position-faithful (they crop full cells), while auto-detect crops each blob's content bbox and centers it in the cell.
+
+## Multi-agent rules for the auto-launch (클로징 스텝 5)
+
+- The server picks a free port per launch (`--port 0` default) and serves exactly one run dir, so several agents curating different characters can each keep a webview open with no port or state conflicts.
+- One curator webview per run dir. Two webviews on the same run dir are last-write-wins on `curation.json`; if one is already serving that run dir, reuse its URL instead of launching another.
+- Pipeline writes are guarded by a run-dir lock (`.sprite-gen.lock`): extract/compose/export/unpack fail loudly when another sprite-gen process is writing the same run dir. Treat that error as "wait or pick another run dir", not as a retry-until-success loop.
+- In a headless/remote session add `--no-open` and give the user the URL; on the user's own machine the default auto-opens their browser.
+- Skip the auto-launch only when the user explicitly asked for an unattended batch run.
+
+## Curation Sidecar (`curation.json`)
+
+`curation.json` is an optional, non-destructive sidecar written by the curation webview (`sprite_gen/serve/serve_curation.py`) and consumed by `compose_sprite_atlas.py` and `compose_selected_cycle.py`. It records a human selection plus a per-frame affine transform; the original frame PNGs are never modified.
+
+```json
+{
+ "version": 1,
+ "kind": "sprite-gen-curation",
+ "run_revision": "9f3c1a0b7e2d4c58",
+ "pixel_unfake": true,
+ "anchors": { "down": { "state": "down_idle", "index": 2 } },
+ "recolor": { "picked": "moss" },
+ "states": {
+ "idle": {
+ "revision": ["a1b2c3d4e5f6"],
+ "pixel_unfake": false,
+ "selected": [0, 2, 3, 7],
+ "order": [0, 2, 3, 7, 1],
+ "clones": { "7": 0 },
+ "transforms": {
+ "0": { "rotate": 15, "scale": 1.2, "dx": 10, "dy": -8, "flipX": 0 }
+ }
+ }
+ }
+}
+```
+
+- `run_revision` — top-level, **required**; stamped at write: the frame generation (request +
+ frames-manifest + each frame's name/size/mtime) this curation was made for. When it matches
+ the current run, the whole sidecar applies (fast path). The `POST /api/curation` autosave
+ echoes it as `runRevision` and the server rejects a mismatched write (`HTTP 409`). See
+ [`run-contract.md`](run-contract.md) §4.
+- `states.<state>.revision` — 행 단위 세대 스탬프 (`curation.state_revision`): 그 행의 프레임
+ 인덱스 공간을 만드는 **원료** 세그먼트(primary raw + 선언 순서의 take raw; raw 없는 임포트
+ 행은 프레임 파일 내용) 다이제스트의 순서 리스트. frames/ 캐시의 mtime 과 엔진 리비전은
+ 입력이 아니다. top-level `run_revision` 이 어긋나면(재추출·heal·재임포트) 행별 구제로
+ 넘어간다: 저장된 리스트가 현재 리스트의 **접두(prefix)** 인 행만 유지(테이크 append 는
+ 인덱스 공간을 밀지 않으므로 유효), 나머지 행과 스탬프 없는 레거시 행은 드롭. 드롭은
+ stderr + 웹뷰 배너(`/api/run` 의 `curationDropped`)로 보고된다. **로드는 아무것도 쓰지
+ 않는다** — 드롭은 "이번 로드가 무엇을 적용하지 않는가" 이지 파일 삭제가 아니고,
+ `curation.json` 은 디스크에 그대로 남는다. 원문이 실제로 덮이는 순간(`write_curation_atomic`)
+ 에만 `curation.stale-<hash>.json` 백업이 난다(내용 해시 파일명, 멱등). 같은 raw 의 엔진
+ 업그레이드 재유도에는 선택이 살아남고, raw 리롤은 그 행만 리셋되며, 무엇도 조용히
+ 소실되지 않는다. 다이제스트의 기하 세그먼트는 셀 크기 + `pixel_unfake` +
+ **파생 격자 배율**(`pixel_snap_scale`)이다 — `fit.logical_height` 선언값 자체가 아니다.
+ 출력이 한 픽셀도 안 바뀌는 선언 편집(무효값 제거 등)이 전 행을 무효화하지 않게 하기 위해서다
+ (회귀 hero synthetic_fixture_b 2026-07-25, 계약 = `tests/test_logical_height_contract.py`).
+- `clones` — 프레임 복제 인스턴스 맵 `{복제 인덱스: 원본 프레임 인덱스}` (웹뷰 카드의 ⧉
+ 버튼). 복제 인덱스는 물리 범위(0..N-1) 밖의 정수이고 `selected`/`order`/`transforms`/
+ `pixels` 에 자기 인덱스로 참여하는 정식 인스턴스다 — 자기만의 변형/픽셀편집/순서를 갖고,
+ compose/export/GIF 는 파일만 원본 프레임(`source_frame_index`)에서 읽는다. `frames/` 는
+ 파생 캐시이므로 복제 파일을 만들지 않는다(복제 의도는 사이드카 소유). 웹뷰에서 복제
+ 카드의 보관 버튼은 보관함이 아니라 인스턴스 삭제다.
+- `pixel_unfake` — **두 층위**. top-level = 런 전체 기본값(웹뷰 우측 상단 "전체 토글" — 모든 줄을 한번에 설정; 줄별 값이 섞이면 웹뷰는 이 필드를 생략한다). `states.<state>.pixel_unfake` = 줄별 override(각 줄 헤더의 토글). 해석 순서는 `curation.frame_variant(curation, state)` 가 SSoT: 줄별 값 > top-level > 기본 `true`. `false` 인 줄은 compose/export/GIF 가 적용 전 쌍둥이(`frame-N.plain.png`)를 굽고, 없거나 `true` 인 줄은 canonical `frame-N.png`. plain 쌍둥이가 없는 런에서는 **굽기에** 무의미(플래그와 무관하게 canonical 을 굽는다) — 웹뷰의 이런 줄 퍼펙 토글은 **표시 렌즈**다: 표시 렌더러가 측정 격자 `pixelScale`(격자 오버레이와 같은 k)로 재양자화해 보여줄 뿐, sidecar 로 저장되지 않고 **파이썬 파이프라인 굽기**(compose/export_pngs/compose_gif — 사이드카만 읽는다)에 영향이 없다. 단 **웹뷰 줄 GIF/WebM/MP4**(`row-export.js`)는 화면 그대로(WYSIWYG) 굽므로 토글 상태가 반영된다 (구 서버 `.pixel-preview` 온디맨드 스냅은 표시 격자와 다른 검출기로 스냅해 폐기, v1.56.91). manifest 는 줄별 `animation.rows.<state>.frame_variant` 와 top-level 요약(`pixel`/`plain`/`mixed`)을 기록한다. 상세는 [`pixel-unfake.md`](pixel-unfake.md).
+- `anchors` — 방향 앵커 **프레임 지정** `{<direction>: {state, index}}` (maintainer 2026-07-25). 그
+ 방향의 다른 행을 생성할 때 identity 로 붙는 인스턴스 하나다 — 카드의 앵커(핀) 버튼(또는
+ `sprite-gen anchor --pick <state>#<index>`)이 쓰고, 지정이 없는 방향은 **앵커 행
+ (`<dir>_<anchor_suffix>`)의 시퀀스 첫 인스턴스**가 앵커다(index 0 이 아니다 — 삭제/재정렬을
+ 존중한다). 같은 방향이면 다른 행의 프레임도, 시퀀스에 없는 후보 풀 프레임도 지정할 수 있다.
+ 각 지정은 **핀한 행의 `state_revision`** 을 함께 들고(쓰기 시 스탬프, 이월 시 재스탬프
+ 금지) 그 행이 리롤·재추출되면 게이트가 `stale` 표식을 붙인다 — 같은 인덱스가 다른 그림이
+ 되므로 조용히 따라가지 않고, 지정을 지워 기본값으로 되돌리지도 않는다. 그 상태의 생성은
+ `pick-stale-generation` 으로 fail-loud 하고 뷰가 이유를 띄운다(재지정 한 번으로 풀린다).
+ 전 행이 드롭돼도 지정은 남는다 — 남아 있어야 오류를 낼 수 있다.
+ 해석·베이크 SSoT 는 `sprite_gen/curate/anchor.py`, 생성에 붙는 파일은 그 함수가 매번 다시 굽는
+ 파생 캐시 `references/anchors/<dir>-anchor-x8.png` 이고, 뷰의 앵커 칩은 낡을 수 없게
+ `GET /api/anchor?direction=<dir>` 라이브 베이크를 본다. 사라진 인스턴스를 가리키는 지정은
+ 생성 시 fail-loud (조용한 기본값 복귀 금지) — 뷰는 로드 시 그 이유를 상태줄에 띄운다.
+- `recolor` — optional adopted colourway `{ "picked": "<variant-name>" }`. Written by the
+ curation view's colourway Adopt button after `sprite-gen recolor` has baked sheets into
+ `<run-dir>/variants/`. Keyed by **name** (a colour decision, not a frame generation), so
+ re-baking does not stamp it stale the way anchors do. A name the current bake no longer
+ produces is kept and reported as `pickedKnown: false` — never silently cleared. A save
+ that does not author this field carries the existing value over (same contract as
+ `anchors`). Reader: `curation.recolor_pick()`. Full bake + view contract:
+ [`recolor.md`](recolor.md).
+- `selected` — 0-based frame indices in play order. Absent/empty → all extracted frames in order.
+- `order` — optional, webview-owned: the full display order (sequence row then candidate-pool row) so reopening the curator restores the exact arrangement of both rows. `compose` / `state_plan` ignore it and key off `selected`.
+- `transforms` — keyed by 0-based frame index. `rotate` degrees (counter-clockwise positive, PIL convention), `scale` multiplier about center, `dx`/`dy` pixel offsets in the cell (+x right, +y down), `shx`/`shy` shear, `flipX` (0|1) horizontal mirror. Absent → identity. On a `fit.pixel_unfake` run, rows baking the pixel variant re-snap the transformed result onto the fixed logical grid (`apply_transform(snap_scale=…)`, mirrored live by the webview) — see [`pixel-unfake.md`](pixel-unfake.md).
+- A state missing from the sidecar uses the all-frames identity default.
+- The transform is applied at compose time inside the request-sized cell, so atlas geometry never changes. `manifest.json.animation.rows.<state>.frames` reflects the curated frame count, and `manifest.json.curation_applied` records whether a sidecar was used.
+
+`curation.py` owns this schema and the transform math so the server and the compose scripts cannot drift. If a folder exists from a previous run, create a timestamped sibling unless the user explicitly says to replace it.
+
+## Related
+
+- [`../SKILL.md`](../SKILL.md) — canonical behavior contract (Workflow 스텝 3.5/4.5/5)
+- [`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
+- [`pixel-unfake.md`](pixel-unfake.md) — 전/후 쌍둥이 토글과 `pixel_unfake` 굽기 결정
+
+
+## Base editing (same component as frames)
+
+The base reference row's edit button opens the **same zoom modal** used for frame
+editing (maintainer 2026-07-17: no parallel editor). What differs is only the target:
+
+- The edit space is a **logical image built from the detected base grid** — each
+ detected block's center pixel sampled from the raw (`/api/base-grid` cut lines).
+ Display quantization, painting, marquee, eyedropper, palette, and the grid
+ overlay all live in this uniform logical space; a uniform grid over the raw
+ would drift (non-uniform fractional pitch + origin offset), so the raw view
+ (pixel-unfake toggle OFF) shows no uniform grid — same rule as frames' plain view.
+- Edits/transforms accumulate client-side and bake into `base-source` only via the
+ explicit **save-to-base** button (`POST /api/base-edit`, `space: "logical"`;
+ pixel ops expand to raw blocks and the transform bakes after edits with
+ `curation.apply_transform` math, re-composited onto the chroma background).
+ The original is backed up once as `.orig`. Nothing about the base ever enters
+ `curation.json` (the `__base__` virtual state is excluded from the payload).
+- Base edits affect FUTURE generation (anchors/rerolls) — already-extracted frames
+ derive from raw strips and do not change.
+- The palette dock merges near-identical raw shades (Manhattan tol 24) and excludes
+ the chroma background; frames show their exact quantized colors unmerged.
diff --git a/docs/directional-anchor-workflow.md b/docs/directional-anchor-workflow.md
new file mode 100644
index 0000000..a7f7a3e
--- /dev/null
+++ b/docs/directional-anchor-workflow.md
@@ -0,0 +1,318 @@
+# Directional / 45° Anchor Workflow — sprite-gen reference
+
+> `SKILL.md` 에서 분리한 시나리오 상세. 방향성·45도·locomotion 행 생성 시 이 문서를 따른다. 기본 simple sprite (`idle`/`jump`/`attack`/`wave`) 에는 필요 없다. 내용은 손실 없이 `SKILL.md` 본문에서 그대로 옮겨졌다.
+
+### 전체 체인 한눈에 (그림)
+
+```text
+[0] 유저 입력
+ ref 이미지 ──(생성)──▶ base 또는 유저가 base 직접 지정
+ │
+ ▼
+[1] base — 딱 1장. down(정면) 기본자세. identity 의 최초 truth.
+ │
+ │ base 를 ref 로 붙여 방향별 idle "행" 생성 (stage 1)
+ ┌──────────────────────┼──────────────────────┐
+ ▼ ▼ ▼
+[2] down_idle 행 side_idle 행 up_idle 행 ← 4프레임 idle 애니메이션.
+ (정면, 숨쉬기) (우측 프로필) (뒷모습) 게임의 idle 로도 그대로 쓴다.
+ │ │ │
+ │ frame-0 을 1장 크롭 = 그 방향의 앵커 ("앵커 = 1장" 규칙)
+ ▼ ▼ ▼
+ down 앵커 1장 side 앵커 1장 up 앵커 1장 ← 사실상 "방향별 base".
+ │ │ │ 이 시점부터 원래 base 는 은퇴
+ │ │ │ (행 생성에 재부착 금지).
+ ▼ ▼ ▼
+[3] down_walk/run/... side_walk/run/... up_walk/run/... ← 각 행 = 자기 방향 앵커(identity)
+ + 레이아웃 가이드(모션 슬롯)로 생성 (stage 2)
+[4] left 방향 = side 의 런타임 미러 — 생성하지 않는 것이 기본 (계약으로 기록).
+ └ 미러 품질이 부족해 재생성할 때만: side 행을 timing/scale 참조로만 부착하고,
+ left 앵커(1장)를 먼저 새로 뽑은 뒤 그 앵커를 identity 로 left 행을 생성.
+```
+
+각 층의 소유권: base = 최초 identity(앵커 생성까지만) · 방향 앵커 1장 = 그 방향의 identity+facing · idle 행 = 앵커의 원천이자 게임 idle 애니메이션 · 각 행 = 모션만 · 미러 방향 = 생성 생략 계약. 이 그림이 곧 `references/generation-plan.json` 의 stage 1 → stage 2 → mirrored_directions 이다.
+
+### Prepare 스캐폴딩 (`--directions`, 2026-07-14)
+
+이 워크플로는 이제 문서 절차만이 아니라 **prepare 가 구조로 스캐폴딩**한다 (maintainer 확정 — base = down 정면 기본자세, 방향 앵커를 base 에서 뽑고 각 행은 자기 앵커에서 뽑는다):
+
+```bash
+prepare_sprite_run.py ... --directions down,side,up --mirror left=side
+```
+
+- request 에 `directions` 블록(`{set, mirror, anchor_suffix}`)이 기록되고, 모든 state 는 `<direction>_<state>` 네이밍이 강제된다 (아니면 fail-loud).
+- 방향 앵커 상태(`<dir>_idle`)가 요청에 없으면 **합성**된다 — 앵커 없는 방향 행 생성 금지. 앵커 프롬프트는 base 기반 + 방향 잠금(canonical direction anchor 문구), 일반 행 프롬프트는 "accepted direction anchor 에서 identity" 문구가 자동으로 들어간다.
+- `--mirror left=side` 처럼 미러 방향은 **생성을 생략**하는 것이 기본이고(런타임 미러), 그 사실이 계약으로 기록된다. 미러로 부족해 재생성할 때는 반대편 행을 timing/scale 참조로만 부착하고 대상 방향 앵커를 새로 뽑는다 (아래 좌우 게이트).
+- 생성 체인 SSoT 는 `references/generation-plan.json` — 1단계 direction-anchors(base 기반), 2단계 action-rows(앵커 기반), mirrored_directions(생략 계약). 워커는 이 플랜 순서대로 생성한다.
+- 큐레이션 뷰는 `directions` 런을 **방향 그룹**(앵커 줄 맨 앞 + "방향 앵커" 배지 + 미러 방향 스트립)으로 렌더한다.
+
+### Hatch-Pet Locomotion Pattern
+
+For compact mascot or pet-like locomotion, use the hatch-pet-proven pattern instead of treating `run`/`walk` as a generic humanoid row:
+
+- Make the base image small-runtime readable first. Compact silhouette and clear limb shapes matter more than high-detail character fidelity.
+- Prefer rectangular 192x208-ish row cells for chibi/pet locomotion, then let the manifest expose the final atlas rectangles. Do not force the generation row to be square just because a game engine later uses square texture regions.
+- Use 8 frames for directional run rows only when the base is simple enough and motion QA is part of the output.
+- Generate `running-right` first and inspect it before generating `running-left`.
+- When generating `running-left`, attach `raw/running-right.png` as a gait row input. Use it as a **gait rhythm reference only**; identity remains owned by `base-source.*`.
+- Do not mirror `running-right` into `running-left` unless the user explicitly approves and the design is symmetric enough. Mirroring is observable derivation, not a silent fallback.
+
+This pattern is not a skeleton. The layout guide still only provides slot count, spacing, centering, and safe padding. The gait row reference gives the image model a visual example of limb phase and body rhythm.
+
+### Directional Chain Default
+
+Directional states must default to a chained reference plan, not independent per-direction generation. This applies to locomotion (`running`, `walking`) and non-locomotion action rows (`working`, `talking`, `success`, `idle`, etc.) whenever the state name encodes a facing direction such as `*-front-right`, `*-front-left`, `*-back-right`, or `*-back-left`. Independent generation is allowed only as an explicit experiment and must be labeled that way in `qa-notes.md`.
+
+### Checklist Direction-Anchor Workflow
+
+For humanoid or direction-sensitive sprites, use this staged checklist before
+generating any final sheet row. The goal is to reduce the model's choices at
+each step instead of asking it to solve identity, direction, state, and motion
+in one image.
+
+0. **Input gate** — collect what the user already has. If information is
+ missing, ask for only the next blocking choice:
+ - base character image / character sheet / style reference
+ - target direction set: front only, horizontal/vertical 4-way, or 45-degree
+ 4-way
+ - requested states and frame counts
+ - style contract and cell size
+
+1. **Base idle gate** — create or accept one canonical base idle. It owns the
+ first identity lock only. Do not proceed if the base is cropped, wrong style,
+ or identity-weak. After direction idle anchors are accepted, this base must
+ not be attached to final action rows.
+
+2. **Direction gate** — create direction anchors before action rows:
+ - front-only: one accepted front idle anchor
+ - horizontal/vertical 4-way: accepted `idle-front`, `idle-left`,
+ `idle-right`, `idle-back`
+ - 45-degree 4-way: accepted `idle-front-right`, `idle-front-left`,
+ `idle-back-right`, `idle-back-left`
+
+ **A direction anchor is exactly ONE single-pose image (앵커 = 1장).**
+ A multi-frame idle row is NOT a valid direction anchor: attaching a row
+ makes the model read frame-to-frame micro-motion as identity variance and
+ dilutes the facing lock. If only an idle row exists, crop one pose
+ deterministically (frame 0 by default) and lock that single image as the
+ anchor; the row itself stays a motion/timing artifact, never an anchor.
+ (maintainer 확정 2026-07-12 — hero 5-anchor 사고에서 도출.)
+
+ **The anchor image is the CURATED frame, and one command bakes it.**
+ Never hand-pick a crop: run
+
+ ```bash
+ sprite-gen anchor --run-dir <run> --direction <dir> # writes references/anchors/<dir>-anchor-x8.png
+ sprite-gen anchor --run-dir <run> --for-state <state> # prints the ref path to attach for that row
+ ```
+
+ That command bakes the anchor frame exactly as the curation view shows it
+ (pixel edits → transform → pixel-unfake re-quantization) and upscales it ×8
+ NEAREST for legibility (pixel data unchanged). It is a **derived cache**:
+ re-run it immediately before every generation, because a later edit in the
+ view silently invalidates the file. Rationale: the accepted identity is what
+ the human approved on screen; generating variations from the un-edited raw
+ leaks the pre-approval look into every downstream row. (maintainer 확정 2026-07-19,
+ 결정론 커맨드화 2026-07-25.)
+
+ **Which frame is the anchor** (`sprite_gen/curate/anchor.py` owns the rule):
+
+ - default: the **curated sequence head** of `<dir>_<anchor_suffix>` — the
+ first frame of the played sequence, *not* index 0. Deleting/reordering
+ frames moves it, so an archived pre-edit frame can never become the anchor.
+ - override: the frame the human pinned in the curation view (pin button on the
+ frame card) or via `sprite-gen anchor --pick <state>#<index>`. Any instance
+ of any row of that direction is allowed, including a candidate-pool frame
+ that is not in the played sequence — the best facing pose is not always in
+ the idle sequence. Stored in `curation.json` as
+ `anchors.<direction> = {state, index}`; `--clear` drops it back to the default.
+ - a pin that points at a vanished instance (archived) is a **hard error** on
+ generation, not a silent fall back to the default.
+ - a pin whose row was later **regenerated** (reroll / re-extract) is equally a
+ hard error (`pick-stale-generation`): the pin carries the pinned row's
+ `state_revision`, so when that row is re-derived the same index is a
+ *different image*, and following it would make a frame the human never saw
+ the direction's identity. The pin is neither re-stamped nor dropped — it is
+ kept and marked stale, so the view can say why and one re-pick clears it.
+
+ Two failure classes, deliberately distinct (`AnchorUnavailable.code`): *pending*
+ (`no-frames`, `row-not-extracted`) means the anchor row is simply not generated
+ yet — the normal state during stage 1, so the curation view stays quiet and
+ `--pick` still records the pin; everything else is *broken* (a pin the human must
+ re-make) and the view reports it. The anchor consumer runs **mid-generation** by
+ definition, so it gates on the manifest row it actually needs
+ (`load_consistent_frames_manifest(allow_pending_states=True)`), never on the
+ finished-generation gate — the strict gate demands a manifest row for every
+ requested state, which is never true at the moment an action row is about to be
+ generated.
+
+3. **State anchor gate** — for each requested non-locomotion state and
+ direction, create one representative state anchor before generating the
+ multi-frame row. For example, `working-front-right-anchor` can show the
+ approved desk/computer pose while `idle-front-right` still owns facing.
+ For cyclic locomotion (`running`, `walking`, `run`, `walk`, and directional
+ variants), do **not** feed a single peak-pose state anchor into the final
+ row. A single contact pose causes the model to repeat that same leg phase
+ across every frame. Locomotion needs a motion-phase reference that contains
+ both opposite contacts, such as a contact sheet, selected cycle, or layout
+ phase guide.
+
+4. **Asymmetric identity gate** — lock side-specific character features before
+ paired direction generation. Hairpins, earrings, scars, logos, handed props,
+ one-sided markings, asymmetric clothing, and lighting cues are identity
+ invariants, not direction controls. A paired left/right row may rotate the
+ body, feet, shoulders, face angle, and gaze, but it must not silently mirror
+ these features onto the wrong physical side of the character. If a feature
+ would become wrong under a horizontal flip, write that explicitly into the
+ row prompt and fail QA if it flips.
+
+5. **Row generation gate** — generate the final row only after the matching
+ direction idle anchor and state anchor exist. Reference ownership is:
+ - base image: pre-idle source only, not a row-generation input
+ - direction idle anchor: identity, facing/orientation, and visible
+ side-specific identity details for that direction — always a
+ **single-pose single image**, never a multi-frame row
+ - state anchor: pose/state vocabulary plus the approved state-specific
+ identity rendering, for non-locomotion states only
+ - locomotion motion sheet/contact sheet: foot-contact phase and gait rhythm
+ - paired basis row: timing, scale, and animation intensity
+ - layout guide: frame count, slots, margins, optional motion phase
+ The row prompt must keep character detail as an already-approved idle-anchor input and
+ spend its degrees of freedom on animation only: limb contacts, arm
+ counter-swing, body height, torso lean, head bob, hair bounce, and loop seam.
+ Do not ask the row to decide hairpin side, outfit details, colors, face
+ design, or other identity features from scratch.
+ For locomotion rows, a single running/walking pose anchor is not valid row
+ grounding unless it is part of a multi-pose contact sheet with both
+ left-forward and right-forward contacts visible.
+
+6. **Hatch-pet left/right gate** — preserve the hatch-pet-proven left/right
+ pattern. Generate the right/basis row first, inspect it, then generate the
+ left/paired row with the basis row attached. The paired row must obey its own
+ target-direction idle anchor for facing; the basis row is only gait rhythm,
+ scale, and animation intensity.
+
+7. **QA gate** — do not advance silently. Record pass/fail per stage:
+ - base idle QA
+ - direction anchor QA
+ - asymmetric identity QA
+ - state anchor QA
+ - extraction and atlas QA
+ - motion continuity / loop seam / direction readability QA
+
+If any gate fails, stop at that stage or mark the output `experimental`.
+
+For 45-degree state packs, make direction a separate visual SSoT:
+
+- Preferred default: create and accept four canonical idle direction anchors first: `idle-front-right`, `idle-front-left`, `idle-back-right`, and `idle-back-left`.
+- Generate every later action row from its matching idle direction anchor. For example, `working-front-left`, `running-front-left`, and `walking-front-left` all attach the accepted `idle-front-left` anchor.
+- The base image owns only the pre-idle source stage. The direction idle anchor owns row identity and facing/orientation. The action row owns motion/state. Do not collapse these truths into one prompt burden.
+- If four direction idle anchors do not exist yet, create or reuse one accepted 4-direction direction sheet/contact sheet before generating action rows.
+- Attach that direction sheet to **every** 45-degree row. Use it only for facing/orientation, not pose, state, identity, or timing.
+- Also attach one **single target-direction anchor** for the requested row direction (`front-right`, `front-left`, `back-right`, or `back-left`). Prefer the accepted idle anchor for that direction. This anchor is the highest-priority facing reference for that row.
+- Each row prompt must name the exact facing: `front-right`, `front-left`, `back-right`, or `back-left`.
+- If the generated row averages into straight front/back or pure side view, mark it `direction-failed`; do not silently rename it to a different direction.
+
+For a left/right side pair:
+
+1. Generate the basis row first: `running-right`.
+2. Inspect the basis row before continuing.
+3. Generate `running-left` with the basis row attached as a gait rhythm reference.
+
+Reference order for the basis side row:
+
+```text
+idle-right.png -> references/layout-guides/running-right.png
+```
+
+Reference order for the paired side row:
+
+```text
+idle-left.png -> raw/running-right.png -> references/layout-guides/running-left.png
+```
+
+For any four-direction 45-degree state, use two basis rows and two paired rows:
+
+1. Generate `<state>-front-right` first.
+2. Generate `<state>-front-left` with `raw/<state>-front-right.png` attached as the paired-row reference.
+3. Generate `<state>-back-right` first.
+4. Generate `<state>-back-left` with `raw/<state>-back-right.png` attached as the paired-row reference.
+
+For locomotion rows, the paired-row reference is a gait rhythm reference. Do
+not attach a single running/walking state pose as the main row reference; it
+will bias every frame toward that one leg phase. Use a motion contact sheet,
+selected cycle, or the previously approved basis row for timing. For
+non-locomotion rows, the paired-row reference is a pose-family and scale
+reference: keep the same prop scale, body size, frame occupancy, and animation
+intensity while changing the facing direction.
+
+The direction sheet is still required for both basis and paired rows. The paired row is not allowed to copy the basis facing.
+
+Reference order for a 45-degree basis row:
+
+```text
+idle-<basis-direction>.png -> references/layout-guides/<basis-state>.png
+```
+
+Reference order for a 45-degree paired row:
+
+```text
+idle-<paired-direction>.png -> raw/<basis-state>.png -> references/layout-guides/<paired-state>.png
+```
+
+If the target-direction anchor and paired basis row conflict, obey the target-direction anchor for facing and the paired basis row only for timing, scale, and animation intensity.
+
+Use this state set for a 45-degree run request:
+
+Use this state set for the 45-degree request:
+
+```json
+{
+ "states": {
+ "running-front-right": { "frames": 8, "fps": 8, "loop": true, "action": "45-degree diagonal run toward camera-right and slightly toward the viewer; alternating foot contacts, arms counter-swing, ponytail bounces, continuous loop" },
+ "running-front-left": { "frames": 8, "fps": 8, "loop": true, "action": "45-degree diagonal run toward camera-left and slightly toward the viewer; use the attached front-right row only as gait timing and mirrored phase reference, not identity; alternating foot contacts, arms counter-swing, ponytail bounces, continuous loop" },
+ "running-back-right": { "frames": 8, "fps": 8, "loop": true, "action": "45-degree diagonal run away from viewer toward camera-right; three-quarter-back view, alternating foot contacts, arms counter-swing, ponytail bounces, continuous loop" },
+ "running-back-left": { "frames": 8, "fps": 8, "loop": true, "action": "45-degree diagonal run away from viewer toward camera-left; use the attached back-right row only as gait timing and mirrored phase reference, not identity; three-quarter-back view, alternating foot contacts, arms counter-swing, ponytail bounces, continuous loop" }
+ }
+}
+```
+
+Use this state set for a 45-degree working request:
+
+```json
+{
+ "states": {
+ "working-front-right": { "frames": 6, "fps": 6, "loop": true, "action": "45-degree three-quarter-front view facing camera-right and slightly toward the viewer; working at a compact laptop or tablet held close and touching both hands; subtle typing, eye, and hair motion" },
+ "working-front-left": { "frames": 6, "fps": 6, "loop": true, "action": "45-degree three-quarter-front view facing camera-left and slightly toward the viewer; use the attached front-right row only for scale, prop size, and motion intensity; working at a compact laptop or tablet held close and touching both hands; subtle typing, eye, and hair motion" },
+ "working-back-right": { "frames": 6, "fps": 6, "loop": true, "action": "45-degree three-quarter-back view facing away toward camera-right; working at a compact laptop or tablet held close and touching both hands; subtle typing, shoulder, and hair motion" },
+ "working-back-left": { "frames": 6, "fps": 6, "loop": true, "action": "45-degree three-quarter-back view facing away toward camera-left; use the attached back-right row only for scale, prop size, and motion intensity; working at a compact laptop or tablet held close and touching both hands; subtle typing, shoulder, and hair motion" }
+ }
+}
+```
+
+Use this state set for a 45-degree walk experiment:
+
+```json
+{
+ "states": {
+ "walking-front-right": { "frames": 8, "fps": 6, "loop": true, "action": "45-degree diagonal walk toward camera-right and slightly toward the viewer; smaller stride than running; alternating foot contacts, gentle arm counter-swing, ponytail sway, continuous loop" },
+ "walking-front-left": { "frames": 8, "fps": 6, "loop": true, "action": "45-degree diagonal walk toward camera-left and slightly toward the viewer; use the attached front-right row only as timing and mirrored phase reference, not identity; smaller stride than running; alternating foot contacts, gentle arm counter-swing, ponytail sway, continuous loop" },
+ "walking-back-right": { "frames": 8, "fps": 6, "loop": true, "action": "45-degree diagonal walk away from viewer toward camera-right; three-quarter-back view; smaller stride than running; alternating foot contacts, gentle arm counter-swing, ponytail sway, continuous loop" },
+ "walking-back-left": { "frames": 8, "fps": 6, "loop": true, "action": "45-degree diagonal walk away from viewer toward camera-left; use the attached back-right row only as timing and mirrored phase reference, not identity; three-quarter-back view; smaller stride than running; alternating foot contacts, gentle arm counter-swing, ponytail sway, continuous loop" }
+ }
+}
+```
+
+Record the exact reference stack for every row in `qa-notes.md`. The generated basis row is not a second identity truth; it is only a paired-row input. If the paired row copies the wrong facing direction, report the row as `direction-failed` instead of silently mirroring or renaming it.
+
+### Advanced Gates
+
+Expose only these gates to the caller for advanced hatch-style runs:
+
+- **pose/state gate** — requested state row, frame count, fps, and loop flag
+- **cell gate** — cell width, cell height, and safe margins
+- **style gate** — one explicit style contract such as `pixel-art-adjacent`, `2.5D chibi`, or `3D-to-sprite`
+- **reference gate** — base/canonical/original/gait references used for that row
+
+All prompt text, guides, extraction, atlas composition, and QA must be regenerated from `sprite-request.json`. Do not keep a separate prompt fork as a second truth surface. If an advanced gate fails QA, report the state as failed or experimental rather than silently falling back to a static or mirrored result.
+
diff --git a/docs/engine-export.md b/docs/engine-export.md
new file mode 100644
index 0000000..b17d81e
--- /dev/null
+++ b/docs/engine-export.md
@@ -0,0 +1,52 @@
+# Engine export
+
+`sprite-gen export-aseprite` describes a composed sprite-gen atlas using the JSON schema consumed by Aseprite loaders. It does not create an editable `.aseprite` source file and it does not re-encode the PNG.
+
+Run it after `compose-atlas`:
+
+```bash
+$SPRITE_GEN_ROOT/.venv/bin/sprite-gen export-aseprite --run-dir <run-dir>
+```
+
+The default output is `<run-dir>/exports/aseprite.json`. It pairs with the existing `sprite-sheet-alpha.png` named by `manifest.json.game_input`. Because compose already applied `curation.json`, the export includes the final selected order, reused cells, transforms, pixel edits, clones, and breathe cells through the atlas rectangles it references.
+
+## Mapping
+
+| sprite-gen manifest | Aseprite-compatible JSON |
+|---|---|
+| `frame_layout.rows.<state>[i]` | `frames[]` rectangle in playback order |
+| `animation.rows.<state>.durations_ms[i]` | frame `duration` in milliseconds |
+| state name and global frame range | `meta.frameTags[]` |
+| `game_input` | `meta.image` |
+| `frame_layout.sheetWidth` / `sheetHeight` | `meta.size` |
+
+Repeated playback instances keep repeated rectangles under distinct numeric frame keys. This preserves sprite-gen's shared-cell representation while presenting the sequential frame keys expected by engine loaders.
+
+## Phaser
+
+Phaser accepts Aseprite JSON in array or hash form and creates animations from `meta.frameTags`. The default `json-array` output uses stringified global frame indices, the tag ranges, and each frame's own duration.
+
+```javascript
+this.load.aseprite('hero', 'sprite-sheet-alpha.png', 'aseprite.json');
+this.anims.createFromAseprite('hero');
+this.add.sprite(100, 100, 'hero').play('idle');
+```
+
+Phaser's official API documents `load.aseprite` and `createFromAseprite`; its implementation looks up each tagged frame by the stringified numeric index and reads each frame's duration. Sources: [Phaser AnimationManager](https://docs.phaser.io/api-documentation/4.0.0/class/animations-animationmanager), [Phaser source](https://github.com/phaserjs/phaser/blob/master/src/animations/AnimationManager.js).
+
+## Flutter and Flame
+
+Flame's `SpriteAnimation.fromAsepriteData` expects `frames` to be a map and builds one animation from every value in that map. It does not read `meta.frameTags`. Export one hash file per state:
+
+```bash
+$SPRITE_GEN_ROOT/.venv/bin/sprite-gen export-aseprite --run-dir <run-dir> --format json-hash --split-states
+```
+
+This writes `exports/aseprite/idle.json`, `walk.json`, and so on. Every file uses local indices beginning at `0`, points to the same atlas PNG, and preserves millisecond frame durations. The relevant behavior is visible in Flame's official [`SpriteAnimation.fromAsepriteData` source](https://github.com/flame-engine/flame/blob/main/packages/flame/lib/src/sprite_animation.dart).
+
+## Limits
+
+- The exporter is structurally tested against the fields the loaders consume, but the repository does not run a browser Phaser app or Flutter runtime in CI.
+- `loop` remains in `manifest.json`. Aseprite frame tags carry direction and range but no sprite-gen loop policy, and Flame's Aseprite factory constructs its default looping animation without reading tags.
+- The curation webview is unchanged. This is a post-compose CLI export, not a new webview download button.
+- The exporter refuses malformed row mappings and output paths outside the run directory. Split-state files are staged as a complete directory and then published together.
diff --git a/docs/frame-interpolation.md b/docs/frame-interpolation.md
new file mode 100644
index 0000000..d5a821b
--- /dev/null
+++ b/docs/frame-interpolation.md
@@ -0,0 +1,92 @@
+# AI Frame Interpolation (in-betweens)
+
+`sprite_gen/effects/interpolate.py` (`scripts/interpolate_frames.py`) makes an **in-between
+frame** between two frames of one state — a half-closed eyelid between open/closed
+idle frames, a mid-swing arm between windup and strike.
+
+## Doctrine position
+
+"AI touches raw generation only" applies here too: interpolation is a raw-stage AI
+step. The output is never a final frame — it is recorded as a **take**
+(`raw/<state>.takes/<label>.png` + `states.<state>.takes` in `sprite-request.json`),
+and logical frames are always baked by the deterministic extraction path (chroma
+removal → components → grid snap → shared palette). The curator orders the new frame
+in the play sequence like any other take frame.
+
+## Backend: generative (codex / grok) — flow-based VFI retired
+
+The backend is the engine's own generation layer (`sprite_gen.gen`): the two aligned
+frames go in as reference images and the model **draws** the in-between pose.
+Default provider `codex` (GPT `image_gen`); `--provider grok` selects xAI Imagine.
+
+Flow-based VFI (RIFE) was retired (maintainer, 2026-07-17). Rationale, measured on a
+real 3-way comparison (hero down_action arm swing, sheet `tween-3way-compare.png`
+in the tray): VFI interpolates *motion* photometrically, so appearance
+changes come out as a blurry cross-fade; generative in-betweens drew the mid-pose in
+clean discrete pixels. codex preserved identity best; grok drifted; RIFE smeared.
+
+## Auth prerequisites (applies to the curator Tween button too)
+
+Generation always runs on the **server machine's provider CLI** — the browser/webview
+never sees or carries any credential. The Tween button POSTs to the local curation
+server, which spawns `codex`/`grok` as a subprocess; those CLIs use their own
+machine-local OAuth sessions.
+
+- Required on the machine running the curation server / CLI:
+ - `codex` CLI installed and logged in (ChatGPT OAuth) for `--provider codex`
+ - `grok` CLI installed and logged in (xAI OAuth) for `--provider grok`
+- Setup and provider topology: [`docs/gen.md`](gen.md) (the SKILL's
+ `required_bins` names both CLIs).
+- Not authenticated / CLI missing → the provider fails loudly and the message
+ surfaces as-is (CLI stderr / curator status bar). No silent fallback between
+ providers.
+
+## Usage
+
+```bash
+$SPRITE_GEN_ROOT/.venv/bin/python $SPRITE_GEN_ROOT/scripts/interpolate_frames.py \
+ --run-dir <run> --state down_idle --between 1 2 \
+ [--provider codex|grok] [--t 0.5] [--label blink_mid] [--extract]
+```
+
+- `--between A B` — frame indices on the state's primary strip (component order).
+- `--provider` — generation backend; default `codex` (3-way comparison winner).
+- `--t` — interpolation time inside (0, 1); default 0.5. Non-midpoint values are
+ expressed in the prompt ("closer to A/B").
+- `--label` — take label; default `tween_<A>_<B>_t<t>`. Re-running the same label
+ overwrites the same take file and does not duplicate the `takes` entry (idempotent).
+- `--extract` — run a **full-batch** re-extraction afterwards. Partial extraction is
+ deliberately not offered: the run-wide shared palette is built per extraction batch
+ (CHANGELOG v1.56.17 known limitation), so a single-state extract would shade that row
+ from a different palette.
+
+In the curator, the row-header **Tween** button does the same thing: open the
+popover, click two cards to pick the pair (blue border), choose GPT/Grok, Generate.
+While the follow-up full-batch re-extraction runs, `/api/run` reports busy (503)
+instead of a manifest-consistency error.
+
+## Pipeline internals
+
+1. Chroma-remove the primary strip, extract components, tighten to solid bbox.
+2. **Registration** (`register_row_frames`) puts both frames on one canvas aligned by
+ upper-body alpha overlap — static pixels coincide, so the model reads the pair as
+ "same drawing, only the moving part differs".
+3. Canvas pads to /32 on the request chroma color; the prompt requires the same flat
+ chroma background so the extractor keys it out later.
+4. `tween_prompt` composes the prompt deterministically from request truth (character
+ description, chroma color, t) and `sprite_gen.gen.generate_image` runs the provider
+ with both frames attached as refs.
+5. The generated mid frame is saved as the take raw; extraction re-derives the state
+ row (the frame appears labeled `<label>#0`) and pixel-unfake quantization snaps it
+ onto the logical grid.
+
+Quality note: judge the result **after** pixel-unfake re-quantization, and touch up
+stray pixels with the curator's pixel editor if needed. Identity drift is a reroll
+(regenerate the take), not a local repair.
+
+## Testing
+
+`tests/test_frame_interpolation.py` covers the plumbing with an injected stub
+interpolator (alignment canvas contract, prompt composition, take write, request
+idempotency, loud rejections including unknown providers). Real provider generation
+is exercised manually, not in CI.
diff --git a/docs/gen.md b/docs/gen.md
new file mode 100644
index 0000000..82d8ce8
--- /dev/null
+++ b/docs/gen.md
@@ -0,0 +1,137 @@
+# `sprite-gen gen` — provider-backed image generation (engine SSoT)
+
+Generation is a first-class engine module (`sprite_gen/gen/`), not an external
+skill. One call = a prompt (+ optional reference images) → one **verified** PNG on
+disk, with an optional deterministic transparent-chroma post-process. The general
+`image-gen` skill is a thin shuttle over this command.
+
+Providers (Gemini/OpenRouter/fal/BytePlus are intentionally **not** included):
+
+| Provider | Backend | Auth | Output truth |
+|---|---|---|---|
+| `codex` | codex `image_gen` | ChatGPT OAuth | inline base64 in the session rollout jsonl, decoded deterministically |
+| `grok` | grok Imagine `image_gen` / `image_edit` | xAI OAuth | file grok is told to write, verified by PNG magic |
+
+## Default provider selection
+
+`--provider` is **optional**. When omitted, the backend is resolved by a fixed
+precedence (maintainer 확정 2026-07-17):
+
+1. **`SPRITE_GEN_DEFAULT_PROVIDER`** env var (`codex` or `grok`) — the user override.
+ An unknown value fails loud.
+2. **`codex`** — the hard default (GPT `image_gen`).
+
+If the resolved default is `codex` but codex is unavailable here (CLI not on PATH,
+or `codex login status` reports not-logged-in), the resolution **falls back to
+`grok` — observably, never silently**: a stderr notice is printed and the report
+JSON records `provider_fallback` (`from`/`to`/`reason`/`default_source`). The
+grok default (`SPRITE_GEN_DEFAULT_PROVIDER=grok`) has no reverse fallback — a down
+grok fails loud at generation time.
+
+An **explicit `--provider`** is always honored verbatim — it is never overridden by
+the availability fallback. An explicitly named provider that is down fails loud
+(the provider adapter raises), preserving the operator's stated intent.
+
+Every generation reports which backend actually ran: `provider` (the real
+backend), `provider_resolved_from` (`explicit` / `SPRITE_GEN_DEFAULT_PROVIDER` /
+`hard-default` / `fallback-from-codex`), and `provider_fallback` when a fallback
+happened.
+
+## Provider and visible-worker topology
+
+Provider selection and user-facing worker/agent creation are orthogonal:
+
+| Layer | Canonical path | Responsibility |
+|---|---|---|
+| Generation request | `generate_sprite_image.py --provider grok` | Select the engine provider for one image request. |
+| Provider adapter | `GrokProvider` | Build the prompt, choose Imagine `image_gen` or `image_edit`, and verify the requested PNG. |
+| Headless provider process | `grok -p --sandbox workspace --always-approve` | Execute the xAI-authenticated Imagine tool call. |
+| Image model tool | Imagine `image_gen` / `image_edit` | Generate a new image, or edit from references. |
+| Visible worker/agent | (caller's orchestrator) | Creating a user-facing worker surface that may invoke the generation request is the orchestrator's own concern; it does not select or replace the provider. |
+
+Therefore the direct Grok chain is `generate_sprite_image.py --provider grok`
+→ `GrokProvider` → `grok -p --always-approve` → Imagine
+`image_gen`/`image_edit`. `GrokProvider` owns the headless agent process lifecycle;
+the chain does not require or route through a separate user-facing skill/task, and
+it is not a second visible-worker topology.
+
+## CLI
+
+```bash
+sprite-gen gen \
+ [--provider codex|grok] # optional; default = SPRITE_GEN_DEFAULT_PROVIDER env → codex (observable grok fallback if codex is down)
+ --prompt "…" # or --prompt-file PROMPT.txt
+ --out DEST.png \
+ [--ref REF.png ...] # repeatable; grok routes refs through image_edit
+ [--transparent [--chroma-key magenta|green]] \
+ [--white-check CHECK.png] \
+ [--aspect-ratio 1:1] # grok only (1:1, 16:9, 9:16, 4:3, 3:4, auto)
+ [--model ID] \
+ [--report REPORT.json] \
+ [--keep-session] # codex: keep the rollout jsonl instead of deleting it
+```
+
+Backward-compatible wrapper: `$SPRITE_GEN_ROOT/.venv/bin/python $SPRITE_GEN_ROOT/scripts/generate_sprite_image.py …` (same args).
+
+- **Non-transparent**: the raw PNG (chroma background included) is copied to `--out`.
+- **`--transparent`**: the raw is keyed to clean RGBA via the ported transparent
+ contract (`sprite_gen/gen/chroma.py`). Generate on a solid `#FF00FF` (or `#00FF00`)
+ background — pick the key by subject colour (magenta subjects → green key). Any
+ transparent pixel that still carries non-zero RGB **fails loudly** (No Silent Fallback).
+- The pre-chroma raw is preserved next to the destination as `<out>.raw.png` for audit.
+- `--report` writes a `sprite-gen-image-report` JSON: provider, prompt, out/raw paths,
+ `raw_bytes`, `elapsed_seconds`, `session_id` (codex), the chroma stats, and the
+ provider-resolution fields (`provider_resolved_from`, and `provider_fallback` when a
+ codex→grok default fallback occurred).
+
+## How each provider works
+
+- **codex** — spawns a fresh `codex exec --json` in an empty sandbox
+ (`--sandbox workspace-write`, `--add-dir <Codex state root>/generated_images`,
+ `--skip-git-repo-check`, no `--ephemeral`). A fresh session breaks OpenAI's prompt
+ cache so repeat prompts don't drag in a prior image. The session id comes from the
+ `thread.started` event (older codex: a `session id:` text line — both supported); the
+ inline base64 is decoded from the rollout jsonl (`image_generation_call` /
+ `image_generation_end` records — both supported). The model-reported path is never
+ trusted. The rollout jsonl (which holds the ~1–1.5 MB inline image) is deleted after
+ extraction unless `--keep-session`.
+ The adapter and child process share one Codex state root: when `CODEX_HOME` is set they use only that directory; when it is unset they use Codex's `~/.codex` default.
+ Rollouts are selected by an exact session-id filename suffix.
+ Missing, duplicate, or pre-existing stale matches fail rather than falling back to another root or choosing by modification time.
+ The transport prompt names the skill with codex's official `$imagegen` mention, which is how a codex skill is invoked explicitly. The adapter owns that trigger alone; the caller's sprite-request prompt is passed through verbatim.
+
+### When codex produces no image at all
+
+A run that reaches a rollout but finds zero `image_generation_call` /
+`image_generation_end` records means the built-in `image_gen` tool was never
+offered to the session, not that the model declined to use it. Built-in image
+generation is a **capability of the account behind the active Codex state root**.
+
+A session that is not offered the tool cannot be talked into it. The `$imagegen`
+mention names the skill, it does not create the tool; the model choice does not
+change it; and no `config.toml` feature toggle grants it. The remedy is to point
+`CODEX_HOME` at a Codex state root whose account provides image generation
+(`codex login status`), or to use `--provider grok`. The adapter fails loudly with
+exactly that, rather than falling back on its own.
+- **grok** — runs `grok -p … --sandbox workspace --always-approve` (media/shell must be
+ auto-approved; plain acceptEdits blocks tool execution and returns an empty answer).
+ grok is instructed to write the final PNG to an exact absolute path; we then verify
+ that file's PNG magic. No `--effort` is passed (the grok-build image model 400s on
+ `reasoningEffort`). With `--ref`, grok uses `image_edit` on the reference instead of
+ `image_gen`.
+
+## Sprite-row usage
+
+In the component-row pipeline (SKILL.md §2) generate each state row with
+`--provider codex` (or `grok`) using `prompts/<state>.txt`, writing `raw/<state>.png`.
+Keep the request chroma key on the background; frame extraction removes it downstream.
+The correction loop (`sprite-gen correction-loop --provider-command …`) can drive this
+`gen` command as its regeneration step so inspect → score → hint → regenerate closes
+against a real provider.
+
+## Speed
+
+On a 4-frame idle mushroom row, grok generated
+in ~18.4 s vs codex ~39.0 s (~2.1× faster). codex adhered better to negative constraints
+("no grid lines"); grok added faint cell dividers. Pick per need: grok for speed, codex
+for tighter prompt adherence.
diff --git a/docs/layer-tracks.md b/docs/layer-tracks.md
new file mode 100644
index 0000000..783bd99
--- /dev/null
+++ b/docs/layer-tracks.md
@@ -0,0 +1,465 @@
+# Layer Tracks — rig · track · composite contract (SSoT)
+
+> 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`.
+
+## 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`/`motion_phase_guides`, 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/locomotion-curation.md b/docs/locomotion-curation.md
new file mode 100644
index 0000000..11cca15
--- /dev/null
+++ b/docs/locomotion-curation.md
@@ -0,0 +1,72 @@
+# Locomotion Curation & Clean GIF Export — sprite-gen reference
+
+> `SKILL.md` 에서 분리한 시나리오 상세. motion-phase 실험·수동 selected-cycle·클린 GIF export 가 필요할 때 따른다. 내용은 손실 없이 `SKILL.md` 본문에서 그대로 옮겨졌다.
+
+### Motion Phase Guide Experiment
+
+For 8-frame run rows, `prepare_sprite_run.py --motion-phase-guides` adds simple stick-pose hints to the layout guide:
+
+```text
+contact -> down -> passing -> up -> opposite contact -> down -> passing -> up
+```
+
+Use this only for explicit locomotion experiments. The guide is not final art and must not appear in the generated row. Its purpose is to nudge foot contact, body height, and leg phase. It can improve leg alternation, but it is not a guarantee of a natural run loop; visual motion QA remains blocking.
+
+### Manual Selected Cycle
+
+When a generated locomotion row contains usable frames but the full row fails motion QA, do not pretend the full row passed and do not ask image generation to redraw locked peak frames. Preserve the generated frame truth and make a separate selected-cycle artifact:
+
+```bash
+$SPRITE_GEN_ROOT/.venv/bin/python $SPRITE_GEN_ROOT/scripts/compose_selected_cycle.py \
+ --run-dir <target>/assets/generated/sprites/<character-id> \
+ --state running-right \
+ --frames 2,3,4,5 \
+ --name running-right-selected-2-3-4-5 \
+ --delay-ticks 19 \
+ --note "human QA selected current best right-run loop"
+```
+
+This writes:
+
+```text
+qa/<name>.gif
+qa/<name>-contact.png
+qa/<name>.json
+```
+
+`qa/<name>.json` is the selected-cycle SSoT: it records the source state, exact 1-based selected frame numbers, runtime zero-based frame indices, delay/duration, and SHA-256 for every source frame. Runtime integrations may consume the original atlas with the selected zero-based frame order, or export a derived atlas explicitly from that manifest.
+
+Use this path for user-approved manual locomotion curation. It is not a silent fallback: report that full-row locomotion failed and that the selected subset is the accepted usable loop.
+
+For precise humanoid running today, the most reliable path is candidate generation plus human frame picking. Generate a few candidate rows, keep the best extracted frames, and let the user choose or reorder the 1-based frame sequence for `compose_selected_cycle.py`. Do not promise automatic frame-order selection yet; if the row only works after manual picking, record that as the current limitation in `qa-notes.md`.
+
+### Clean GIF Export
+
+Use `compose_sprite_gif.py` whenever you need a shareable transparent GIF from extracted frames or from a human-picked frame order. Do not hand-roll GIFs with ad-hoc `magick` commands unless you are debugging.
+
+```bash
+$SPRITE_GEN_ROOT/.venv/bin/python $SPRITE_GEN_ROOT/scripts/compose_sprite_gif.py \
+ --frame-dir <target>/assets/generated/sprites/<character-id>/frames/running-right \
+ --frame-order 2,1,5,3 \
+ --delay-ticks 14 \
+ --output <target>/assets/generated/sprites/<character-id>/qa/running-right-picked.gif \
+ --contact-output <target>/assets/generated/sprites/<character-id>/qa/running-right-picked-contact.png \
+ --manifest-output <target>/assets/generated/sprites/<character-id>/qa/running-right-picked-gif.json
+```
+
+Delay ticks are GIF/ImageMagick ticks: `14` means about 140 ms per frame, `20` means about 200 ms, `30` means about 300 ms. State-specific timing is allowed, but it must be explicit in the output manifest or final delivery note. A typical preview profile can be:
+
+```text
+base/idle/rest/working/talking/success = 20 ticks
+running = 14 ticks
+sleep = 30 ticks
+```
+
+Clean GIF invariants:
+
+- Source PNG frames remain the truth. The GIF owns only frame order and timing.
+- Save as transparent GIF with a dedicated transparent palette index.
+- Use disposal method 2 so each frame clears before the next frame draws. This prevents "previous frame showing through" ghosts in browser previews.
+- Use infinite loop (`loop-count 0`) for looped states.
+- Keep contact sheets separate from GIFs. Contact sheets may use checker backgrounds for inspection; runtime/shareable GIFs should preserve transparency.
+- If a loop only works after dropping or reordering frames, record the selected 1-based frame order. Do not hide that as an automatic pass.
diff --git a/docs/pixel-unfake.md b/docs/pixel-unfake.md
new file mode 100644
index 0000000..ab14065
--- /dev/null
+++ b/docs/pixel-unfake.md
@@ -0,0 +1,124 @@
+# Pixel Unfake Fit (`fit` / `pixel_unfake`) — sprite-gen reference
+
+> `SKILL.md` 허브에서 분리한 시나리오 상세. 픽셀아트 타깃, 지터 없는 locomotion, 게임-레디 청키 픽셀 출력이 필요할 때 이 문서를 따른다. 구현 내부(피치 검출·grid-snap·팔레트 단계별 코드 동작)는 [`architecture.md`](architecture.md) §6 참조.
+
+## `fit` object
+
+Optional `fit` object (opt-in; absent means legacy behavior). For pixel-art targets and jitter-free locomotion use:
+
+```json
+"fit": { "resample": "kcentroid", "align_x": "foot-centroid", "align_y": "bottom" }
+```
+
+- `resample` — `lanczos` (default) | `nearest` | `kcentroid`. `kcentroid` (Astropulse-style dominant-cluster downscale) keeps 1px dark outlines readable when the generated art's implied pixel grid does not match the target cell; `nearest` is crisp but drops off-grid outline pixels; `lanczos` blurs pixel art.
+- `align_x` — `bbox-center` | `centroid` | `foot-centroid` (default) | `alpha-centroid`. Bbox-centering shifts the body left/right whenever a pose's content bbox width changes (extended arm/leg), which reads as per-frame horizontal jitter. `centroid` aligns the whole-alpha centroid; `foot-centroid` aligns the bottom-20% alpha (the legs), so trailing hair/capes do not pull the body off the cell axis — use it when the runtime mirrors the cell for left/right facing (flip pivots on the leg axis instead of teleporting the body). `alpha-centroid` (opt-in, perfectpixel-studio port — github.com/gykim80/perfectpixel-studio `internal/sprite/extract.go`, MIT) aligns the alpha-weighted centroid ignoring soft-matte fringe (α ≤ 10); crucially, in the `pixel_unfake` row path it is applied **per frame** instead of once per row union, so residual registration jitter from `register_row_frames` is cancelled (upstream measured σ 27.2px → 0.2px; jump arcs stay preserved via `ground_frames: false`).
+- `align_y` — `center` (default) | `bottom`. Bottom pins feet to a shared baseline (`cell_height - safe_margin_y`).
+
+`prepare_sprite_run.py` exposes these as `--fit-resample`, `--fit-align-x`, `--fit-align-y`, plus the `pixel_unfake` family below as `--fit-pixel-unfake`, `--fit-logical-height`, `--fit-palette-size`, `--fit-detail-bias`, `--fit-outline {on,off,STRENGTH}`, `--fit-pitch-hint`. CLI flags override the same keys in `--request` JSON; either way the merged result is recorded in the run's `sprite-request.json` `fit` object (SSoT).
+
+## `pixel_unfake` mode
+
+For true pixel-unfake output (game-ready chunky pixel art with intact 1px outlines), use the `pixel_unfake` mode instead of `resample` — it removes ALL non-integer resampling:
+
+```json
+"fit": { "pixel_unfake": true, "logical_height": 64, "palette_size": 48, "align_x": "foot-centroid", "align_y": "bottom" }
+```
+
+**눌림 없음 — 유일한 동작** (maintainer 확정 2026-07-14, 옵트인 잔재 완전 제거 2026-07-17): 스냅된 네이티브 논리 크기를 유지한다 — `logical_height` 계약으로의 conform 축소는 칸을 병합해 디테일(눈·아웃라인)을 갈라먹는다. 과거의 `"conform": true` 옵트인은 **제거됐고 선언 시 요란하게 거부된다** — 제거된 결정이 플래그 하나로 되살아나는 회귀 경로였다 (회귀 2026-07-17: 높이 통일 시도가 이 플래그로 재발). 물리 한계(셀 바닥 마진 유지, `(cell_h − margin_y)/scale`)만 캡으로 강제되고 캡에 걸린 프레임은 경고로 관측된다. **안전영역(사방 여백 준수 상한)을 넘었지만 물리캡 이내인 여백 침범은 리롤 대상이 아니다** — 정보성 알림만 남는다(manifest warning + 큐레이터 줄 헤더 "여백 침범" 배지, maintainer 확정 2026-07-14). 계약 키(logical_height)는 생성 목표/경고 기준일 뿐 강제 수단이 아니다.
+
+`logical_height` 를 **생략하면 셀 높이와 동일(1:1)** 이 기본이다 — 생성 프롬프트가 "TRUE `<셀>`x`<셀>` pixel grid" 를 명시하는 현행 레시피에서 원본 그리드 해상도를 그대로 따라간다(권장). 더 청키한 저해상 룩을 원할 때만 작은 값을 명시한다: 셀 64 + 로지컬 32 → 2× 청키 픽셀.
+
+**셀 높이의 정수 약수만 유효하다** (maintainer 2026-07-25). 격자 배율은 정수(`cell_h // logical_height`)라 약수가 아닌 선언은 반올림돼 사라진다 — 셀 64 + 로지컬 48 은 배율 1 로 접혀 **논리 높이가 64 로 되돌아간다**(선언은 아무 픽셀도 바꾸지 않음). 그 상태를 조용히 두지 않는다: 추출이 `fit.logical_height=<값> is not applied as declared` 경고를 남기고, 큐레이터 헤더 라벨과 큐레이션 행 지문은 선언값이 아니라 **파생 유효값**(`curation.effective_logical_height` / `pixel_snap_scale`)을 쓴다. 회귀 (hero synthetic_fixture_a·v8): `conform` 눌림이 제거된 뒤 남은 무효값 48 이 라벨을 "48px" 로 거짓 표기했고, 그 값을 지우는 편집만으로 프레임이 바이트 동일한데도 14행 큐레이션이 통째로 드롭됐다. 배율 식의 소유자는 `pixel_snap_scale` 한 곳이다 — 소비자(extract·웹뷰·compose)가 손으로 다시 유도하지 않는다(`tests/test_logical_height_contract.py`).
+
+Pipeline (unfake.js/pixeldetector-style): 포즈 컴포넌트를 먼저 분리한 뒤 **프레임별** 처리 — 엣지-정렬 스코어링 피치 검출(그리드선 ±w 에 색 경계가 모이는 비율 − 우연 기대치 |잉여류|/p 의 argmax; 창 폭 w 는 모든 p 에 동일하고 잉여류는 집합으로 세어 중복 합산하지 않는다 — w 를 p>=8 에서만 열면 참 피치가 자기 약수에게 져서 k=8,10,12,14 가 k/2 로 붕괴한다, `tests/test_pitch_ground_truth.py`) → 피치는 **소수**로 잰다 (AI 도트의 블록 폭은 정수로 안 떨어진다 — 예: 17.24px; 정수로 반올림하면 그 오차가 폭 전체에 누적돼 셀 경계가 블록 한가운데를 지난다). 격자선은 `_grid_edges` 가 길이를 셀 개수로 등분해 정수 픽셀로 확정하므로 **결과는 항상 정수 격자**다. **프레임 자체 검출 피치가 1순위 진실**이다 (maintainer 2026-07-20, plan `sprite-gen/per-frame-pixel-grid`: 합의를 프레임에 강제하면 측정차 0.5px/셀이 폭 전체에 누적돼 눈이 반쪽 나는 회귀) — 단, own 채택은 **합의 '피치 패밀리'(비율 1.1, `PITCH_FAMILY_RATIO`) 이내에서만**이다. 하모닉/붕괴 오검출(×2/×3·÷2/÷3)까지 own 으로 믿으면 한 프레임의 거대 native 가 행 일관 축소(`conform_row_logical`)의 배율을 끌어내려 행 전체가 콩알로 붕괴한다 (회귀 synthetic_fixture_a up_run frame-2, 2026-07-22: own 3.00 → native 87×162 → 행 전체 0.36배 → sparse 검증 전멸, plan `sprite-gen/pitch-outlier-guard-heal-isolation`). 패밀리 밖 = 합의로 스냅 + 프레임별 warning (`resolve_frame_pitch`, `tests/test_pitch_ground_truth.py`). 프레임별 검출값의 중앙값(붕괴값 필터)은 **자체 검출이 실패한 프레임의 fallback** 이기도 하며 적용 시 프레임별 warning. 전 프레임 검출 실패면 `fit.pitch_hint`(보통 베이스 검출값) → **위상은 프레임마다 셀 균일도 실측(`_best_phase`)으로** 다시 잡아 grid-snap → 네이티브 논리 크기 유지(물리 셀캡만 kCentroid 로 강제, `fit.conform` 은 요란하게 거부 — maintainer 2026-07-14/17: 계약으로의 conform 축소는 칸을 병합해 디테일을 갈아먹는다) → run-wide shared median-cut palette (`palette_size`, kills frame-to-frame color flicker) → alpha binarization → integer NEAREST upscale into the cell. `detail_bias` (default true) prefers a near-black minority cluster (share ≥ 0.40, luma < 70/255) so eyes and outlines survive dominant voting. The final display scale is `cell_height // logical_height` — e.g. cell 64 + logical 32 → crisp 2× chunky pixels. (폐기된 대안과 그 이유는 `CHANGELOG.md` v1.10.0.)
+
+## 위상은 근사가 아니라 실측으로 고른다
+
+피치를 맞게 재도 **위상이 틀리면 격자가 블록을 반으로 가른다.** 위상 출처는
+`_best_phase` — 후보 위상마다 실제 셀 균일도(`_grid_score_edges`)를 채점해 축별 8단계에서
+최선을 고른다. 피치 검출이 부산물로 내놓는 히스토그램 위상(`_axis_refine` 의 최적 창
+가중 무게중심)은 쓰지 않는다.
+
+이유는 그 근사가 **참 위상에서 최대 pitch/2 까지 밀리기 때문**이다 (회귀 maintainer
+2026-07-25, synthetic_fixture_b `down_jump` frame-0: 피치 13.00 에서 히스토그램 위상 y=2.02 vs
+실측 최적 y=8.12, 차이 6.1 ≈ pitch/2). `refine_edges_to_boundaries` 는 절단선을
+**±pitch/3 창 안에서만** 당기므로 이 크기의 위상 오차는 구조적으로 복구되지 않는다 —
+캐릭터 눈 4행이 3행으로 병합돼 8칸이 7칸이 됐다 (plan
+`sprite-gen/frame-pitch-consensus-eats-a-row`).
+
+피치가 고정된 상태에서 위상만 비교하므로, 균일도 지표의 '거친 격자 편애' 편향
+(칸이 클수록 칸 안이 균일해지는 자명한 편향)은 이 판정에 개입하지 않는다.
+
+**이 정책의 범위는 추출 스냅 경로다.** 큐레이터의 베이스 격자(`/api/base-grid`,
+`sprite_gen/serve/serve_curation.py`)는 여전히 `detect_pixel_grid` 가 돌려주는 히스토그램 위상으로
+절단선을 만든다. 그 절단선은 **표시용 오버레이 선 그리기에 그치지 않는다** — 베이스 편집기가
+각 블록의 중심 픽셀을 raw 에서 샘플해 논리 편집 캔버스를 만들고(`sprite_gen/serve/curator/src/base-editor.js`),
+논리 좌표 편집을 되돌릴 때 같은 절단선으로 raw 블록 전체를 채워 `base-source` 파일에 굽는다
+(`space: "logical"` ops). 즉 여기서도 위상이 밀리면 중심 샘플이 이웃 블록으로 넘어가고,
+칠한 칸이 실제 블록 경계를 가로질러 굳는다 — **추출 스냅에서 잡은 것과 같은 실패 계열**이다.
+
+그럼에도 이 정책을 그 경로에 강제하지 않는 이유는 두 가지다: (a) 대상이 `base-source` 라는
+별개 이미지(행의 identity 입력이지 추출 산출물이 아니다), (b) 사람이 화면으로 결과를 보며
+편집하는 경로라 잘못 찍히면 즉시 눈에 띈다. 그 경로의 위상 정확도를 올릴지는 **별건**이다 —
+"위험 없음" 이 아니라 "다른 이미지·다른 경로라 이 플랜에서 다루지 않음" 으로 읽어야 한다.
+
+**위상 출처를 바꿨을 때의 출력 변화** (plan `sprite-gen/frame-pitch-consensus-eats-a-row`):
+히스토그램 위상 → 실측 위상 전환의 전수 회귀는 68프레임 중 동일 53 / 변경 15(전부 ±1칸)다.
+이게 이 절이 말하는 정확도 개선의 실제 크기다.
+
+**비용**: 축별 8단계 = 최대 64조합을 전체 이미지 픽셀로 채점한다. 정확도를 택한 명시
+트레이드오프다 — 실측 위상이 히스토그램 근사보다 비싼 건 여전하고, 등가 최적화로 배수만
+줄었다 (plan `sprite-gen/best-phase-hotspot`: 채점을 정수 정확 산술로 재정식화해 채점 코어
+**7.91×**, `synthetic_fixture_b` 14상태 전체 추출 **4:20 → 1:57 = 2.22×**). 그 최적화는 **출력을 전혀
+바꾸지 않는다** — 프레임 PNG 204장 SHA-256 전부 동일이다. 위의 "변경 15" 와 헷갈리지 마라:
+그건 위상 출처 교체가 만든 변화이고, 최적화가 만든 변화는 0 이다.
+
+## Stage ownership (불변)
+
+픽셀 언페이크는 **row 추출 단계에서만** 적용한다. 베이스/앵커 생성 단계는 타깃 스타일(픽셀 룩 vs 2D 일러스트 vs 3D/실사풍)을 프롬프트·레퍼런스로 잠글 뿐, 픽셀 언페이크 후처리를 하지 않는다 — 베이스는 row 의 identity truth 라 가공 없이 원본으로 쓴다. 생성 프롬프트가 "TRUE NxN pixel grid" 를 명시해도 모델이 완벽한 균일 그리드로 그리지는 않으므로 정렬 강제는 여전히 추출 단계 몫이다.
+
+## 스타일의 SSoT 는 첨부된 베이스/앵커 이미지다
+
+프롬프트 텍스트로 체형·등신·볼살·아웃라인 굵기·디테일 밀도를 재기술하지 마라 — 텍스트가 레퍼런스와 경쟁해 identity 를 되돌린다. 행 프롬프트에는 "첨부 레퍼런스를 정확히 따라라(밀도·비율·아웃라인·팔레트)" + 모션 서술 + 레이아웃/크로마 규칙만 남긴다. `STYLE_DEFAULT` 도 이 원칙으로 고정돼 있다 — 강한 스타일 지시가 필요하면 베이스를 다시 뽑아 확정하는 게 정도다.
+
+## 픽셀 밀도는 프롬프트가 아니라 레퍼런스가 지배한다
+
+image_gen 은 출력 크기가 ~1024px 급 고정이라 "작게 생성"은 불가능하고, "TRUE NxN grid" 문구만으로는 밀도를 못 잠근다. 모델이 실제로 따라가는 것은 **첨부된 스타일 레퍼런스의 픽셀 블록 굵기**다: 진짜 저해상 도트(예: 24~64px 스프라이트를 NEAREST 확대한 것, 데모 스크린샷)를 붙이면 그 굵기로 그리고, 고해상 가짜-도트(1024px+ 생성물)를 붙이면 그 고밀도를 따라가 로지컬 축소에서 뭉개진다. **규칙: 픽셀 타깃 런의 스타일 레퍼런스는 반드시 타깃 로지컬 해상도급의 진짜 저해상 도트로 준비한다.** 가짜-도트 밖에 없으면 한 번 픽셀 언페이크로 잠근 결과물을 레퍼런스로 재사용한다. 단, **베이스 raw 가 이미 그리드-인식 생성물이면 그 raw 가 최상의 앵커다** — 픽셀 언페이크로 잠근 판을 앵커로 재투입하면 이중 열화로 얼굴/디테일이 뭉개진다.
+
+## 역할 계약
+
+AI 개입은 **raw 생성 한 곳뿐**이다 (`SKILL.md` 필수 게이트). 픽셀 언페이크(피치 검출→그리드 스냅→kCentroid→팔레트→아웃라인)는 모델 호출이 없는 **완전 결정론 코드**라 같은 입력이면 항상 같은 출력이다. 에셋 제작의 기본 프로세스 = 변환 후 **큐레이션뷰 자동 런치**, **픽셀 언페이크 적용 여부는 인간이 체크박스로 결정**. 사용자가 "뷰 생략하고 알아서 픽셀 이미지로" 라고 명시했을 때만 무인 처리한다.
+
+## 큐레이터 표시 규칙
+
+확대 표시는 항상 nearest(`image-rendering: pixelated`, 패시브) — 안티앨리어싱 확대가 실픽셀 품질을 뭉개 보이게 하는 착시를 막는다. 헤더의 **"픽셀 언페이크 격자" 체크박스**는 논리 픽셀 격자를 카드 위에 오버레이한다(표시 전용, 굽기 무관). `fit.pixel_unfake` 런은 요청 scale(간격 = `cell_height // logical_height`)로 그리고, 임포트/plain 런은 줄별로 측정한 블록 피치(label `auto`)로 그린다 — 격자를 알 수 있거나 측정 가능한 줄이면 토글이 뜬다. 피치를 측정할 수 없는 줄만 격자를 그리지 않는다(가짜 격자 금지). 표시 계약 SSoT 는 `docs/run-contract.md` §3(Pixel grid 행).
+
+## 전/후 쌍둥이 + 큐레이터 선택
+
+`fit.pixel_unfake` 런에서 추출은 픽셀 언페이크 결과(`frame-N.png`, canonical)와 함께 **적용 전 쌍둥이 두 개**를 저장한다: **셀 크기 `frame-N.plain.png`**(굽기용 — 아틀라스 슬롯이 셀 크기라 compose 가 이걸 읽는다)와 **고해상 `orig/frame-N.png`**(표시 전용 — S×셀, pp 해제 표시가 셀 확대 흐림 없이 원본 화질. S 는 행별 네이티브 배율: 프레임들의 컴포넌트 crop/최종 콘텐츠 bbox 비율 최대값의 ceil, 상한 `2048//cell` — 리샘플이 경미한 업스케일이 되도록 해 다운스케일 뭉갬을 금지한다. 구 고정 ×4 캡은 고피치 raw 를 눌러 "원본" 뷰가 원본이 아니게 됐다, maintainer 2026-07-23). 두 쌍둥이 모두 **픽셀 언페이크 프레임의 최종 콘텐츠 bbox 와 같은 풋프린트**에 앉힌다(`fit_component_to_bbox`) — 토글이 크기 변화 없이 픽셀 처리 품질만 비교하고, plain 굽기도 pp 줄과 같은 캐릭터 크기를 유지한다. (이전엔 legacy fit 이 가용영역을 채워 pp 결과보다 ~8% 크게 앉았고 토글 순간 크기가 튀었다.) 빈 프레임은 warning 으로 관측, 해당 쌍둥이만 빠진다.
+
+**변형 굽기도 격자를 지킨다**: 픽셀 변형을 굽는 줄의 큐레이션 변형(이동/확대/회전/기울이기/반전)은 BICUBIC 이 아니라 **NEAREST 샘플 + 셀 고정 논리 격자 재양자화**(`apply_transform(snap_scale=…)`, 스케일 SSoT = `curation.pixel_snap_scale`)로 굽는다 — 어떤 변형도 픽셀 격자를 뭉갤 수 없다. 큐레이션 웹뷰는 같은 양자화를 캔버스로 미러링해(`drawFrameInto`) **드래그하는 동안에도 스프라이트가 고정 격자에 실시간 스냅되어 보인다** (격자는 셀에 고정, 그림이 격자 단위로 이동). plain 변형을 굽는 줄은 격자 예술이 아니므로 기존 BICUBIC 유지.
+
+토글은 **줄(state) 단위**다: 쌍둥이가 실재하는 각 줄의 "생성 재료" 줄 우측(프레임 이미지 바로 위)에 **줄별 "픽셀 언페이크" 체크박스**가 뜨고, 우측 상단 체크박스는 **전체 토글**(모든 줄을 한번에 설정; 줄별 값이 섞이면 indeterminate 표시)이다. 픽셀 격자 오버레이도 같은 모양이다 — 격자를 아는 줄마다 줄별 "픽셀 격자" 체크박스 + 상단 "픽셀 격자 전체" 토글(표시 전용, 저장 안 함). 각 토글이 그 줄의 **표시와 굽기를 함께 결정**한다(별도 보기 토글 없음; curator `src/display.js`·`src/row-controls.js`, run-contract §3 원본화질 토글 행과 일치). 켠 줄은 canonical `frame-N.png`(픽셀 언페이크)를 표시·굽고, 끈 줄은 표시는 `orig/` 고해상본 우선(없으면 `.plain.png`)·굽기는 셀 크기 `.plain.png` 변형으로 전환하며(끈 줄은 스냅 격자가 아니므로 픽셀 격자 오버레이도 숨긴다) `curation.json` 의 `states.<state>.pixel_unfake`(줄별) + top-level `pixel_unfake`(전줄 균일할 때만 기록되는 런 기본값)에 저장된다. 해석 순서(줄별 > top-level > 기본 on)의 SSoT 는 `curation.frame_variant(curation, state)` 이고 compose·GIF·PNG export 전부 이 리졸버를 쓴다. 끈 줄의 plain 파일이 없으면 조용한 폴백 없이 에러다. report/manifest 에는 줄별 `animation.rows.<state>.frame_variant` 와 top-level 요약(`pixel`/`plain`/`mixed`)이 기록된다. 표시 계약 SSoT 는 [`run-contract.md`](run-contract.md) §3.
+
+## 은퇴 키 (`fit.pixel_perfect`) 와 이관
+
+`fit.pixel_perfect` 는 2026-07-25 에 `fit.pixel_unfake` 로 교체됐다. 기존 런은 무손실로 계속 돈다:
+
+- **읽기** — 로더(`runio.load_request`)가 은퇴 키를 현행 키로 **메모리에서만** 정규화한다. 런 파일은 바이트 그대로 남는다. 두 키가 동시에 있으면 hard fail (어느 쪽이 진실인지 코드가 고를 수 없다).
+- **디스크 이관** — 사용자가 명시적으로 부르는 단일 writer 에서만 한다:
+
+ ```bash
+ $SPRITE_GEN_ROOT/.venv/bin/sprite-gen migrate-request <run-dir> # dry run
+ $SPRITE_GEN_ROOT/.venv/bin/sprite-gen migrate-request <run-dir> --apply # 실제 쓰기
+ ```
+
+ request 편집 writer(리롤·트윈 테이크 기록, 뷰 fps 편집)와 **같은 배타락**(`runio.publish_guard`)을 잡고, 락 획득 후 문서를 fresh 재독한 뒤 원자 교체한다 — 그래서 이관과 편집이 서로의 쓰기를 잃을 수 없다. 값·의미는 그대로고 키 이름만 옮긴다.
+
+이관은 **선택**이다 — 안 해도 파이프라인은 정상 동작한다. 조회가 파일을 바꾸지 않는 이유와 사고 기록은 [`run-contract.md`](run-contract.md) §2-b-2 가 소유한다.
+
+## Related
+
+- [`../SKILL.md`](../SKILL.md) — canonical behavior contract (필수 게이트, SSoT 요청 스키마)
+- [`architecture.md`](architecture.md) — 추출 내부 구현 (피치 검출·grid-snap·팔레트 코드 동작)
+- [`curation.md`](curation.md) — 큐레이션뷰 사용법, `curation.json.pixel_unfake` 플래그
diff --git a/docs/qa-motion.md b/docs/qa-motion.md
new file mode 100644
index 0000000..7be8394
--- /dev/null
+++ b/docs/qa-motion.md
@@ -0,0 +1,36 @@
+# Motion Continuity QA (BLOCKING) — sprite-gen reference
+
+> `SKILL.md` 허브에서 분리한 시나리오 상세. 추출·아틀라스 QA 를 통과한 행을 **모션으로서** 판정할 때 이 문서를 따른다. Motion Continuity 는 BLOCKING 이다 — 판정 기준 전체가 여기 있다.
+
+Static identity QA is not enough. A row can have the right frame count, clean alpha, and consistent identity and still animate as garbage. Review motion **as motion**:
+
+- Build a per-state contact sheet and an animated preview, then watch the loop:
+
+```bash
+$SPRITE_GEN_ROOT/.venv/bin/python $SPRITE_GEN_ROOT/scripts/preview_animation.py \
+ --run-dir <target>/assets/generated/sprites/<character-id>
+```
+
+This writes `qa/<state>-contact.png` (frames left-to-right) and `qa/<state>.gif` (played at the state `fps`).
+The GIF is exported through the clean transparent GIF path (dedicated transparent index + disposal method 2), while the contact sheet uses a checker background for inspection.
+
+## 판정 기준
+
+- **Cyclic locomotion (walk / run):** the motion must read as continuous locomotion, not static bobbing. Review body rhythm, limb motion, foot contact stability, and whether the loop communicates the requested direction and speed.
+- **Experimental locomotion boundary:** walk/run/frontwalk/45-frontwalk are not simple default pass states. They may be generated, but the report must call them experimental unless motion continuity passes cleanly.
+- **Loop seam:** for `loop: true` states, the last frame must flow back into the first. A visible jump at the wrap is a fail.
+- **Non-loop gestures:** for `loop: false` states such as attack, jump, hurt, or wave, judge start/middle/end readability instead of loop seam. Do not force a non-loop gesture into a loop just because it has multiple frames.
+- **Humanoid caution:** humanoid joints (knees, elbows, hips, hands) are where diffusion drifts most. Review **every** frame for broken anatomy, extra/missing limbs, and limb-length changes. Humanoids need stricter per-frame review than blob/creature sprites — do not skim.
+- **Independent second opinion (recommended for humanoids):** hand `qa/<state>.gif` (or the contact sheet) to a fresh independent vision-model pass (e.g. a codex vision session) and ask specifically: "does this read as continuous `<state>` motion; is the loop seamless; is the identity stable across frames; are there anatomy or jitter problems?" Trust a second judge over a single reviewer for motion calls.
+
+## 실패 시
+
+If a row fails motion continuity (static bobbing, jitter, anatomy break, identity drift, or a hard loop seam), **regenerate that row**. Do not repair motion by drawing or re-timing frames locally.
+
+Record the per-state motion verdict in `qa-notes.md`.
+
+## Related
+
+- [`../SKILL.md`](../SKILL.md) — QA 자동 체크 목록 + report 포맷
+- [`states-and-frames.md`](states-and-frames.md) — simple/experimental 상태 구분
+- [`locomotion-curation.md`](locomotion-curation.md) — 부분 프레임만 쓸 만할 때의 selected-cycle 경로
diff --git a/docs/recolor.md b/docs/recolor.md
new file mode 100644
index 0000000..5899d8b
--- /dev/null
+++ b/docs/recolor.md
@@ -0,0 +1,256 @@
+# Recolor — deterministic palette-swap bake + colourway pick — sprite-gen reference
+
+> Split out of the `SKILL.md` hub. Follow this doc when you need to bake N colour
+> variants of one base sheet from a palette map, or when the curation webview is
+> comparing and adopting those baked colourways. Implementation:
+> `sprite_gen/effects/recolor.py`. View surface: `sprite_gen/serve/curator/src/recolor.js` +
+> `serve_curation._recolor_info`.
+
+## Why bake, not tint at runtime
+
+Dot art lives and dies by palette control. A baked sheet is QA-able pixel by
+pixel, costs the renderer nothing, and keeps every colourway under the same
+geometry contract as the base atlas. Runtime shaders/filters are out of scope —
+they reintroduce anti-aliased edge bleed and cannot be diffed as assets.
+
+Same input bytes → same output bytes. The bake does no floating-point
+resampling; it rewrites RGB only and preserves alpha, so a base
+`manifest.json.frame_layout` describes every variant sheet.
+
+## Triggers (agent routing)
+
+Use this path when the user says any of:
+
+- **KR:** 팔레트 스왑, 팔레트 베이크, 리컬러, 색깔 바꾸기, 컬러웨이, 색 변형, 팔레트 맵,
+ 색갈이, recolor 해줘
+- **EN:** palette swap, recolor, colourway / colorway, bake variants, palette map,
+ recolour the sheet
+
+Not this path: live tint filters, shader recolor, one-off hand-painted
+recolours that skip the bake report.
+
+## Commands
+
+Two subcommands share the module. The console script, the module form, and the
+`scripts/recolor.py` wrapper all reach the same `cli.COMMANDS` entry (identity,
+not a copied flag list — see `tests/test_recolor_cli_entrypoint.py`).
+
+### 1. Draft a palette map from a base sheet
+
+```bash
+$SPRITE_GEN_ROOT/.venv/bin/sprite-gen recolor-palette \
+ --base <sheet.png> \
+ --out <palette.json>
+```
+
+- Scans opaque pixels (`alpha > 8` by default — same floor as compose-gif).
+- Emits distinct colours ordered by frequency (desc), then hex (asc) — a total
+ order, so two runs of the same sheet produce the same draft.
+- `--max-colors N` keeps the top-N only and **reports** how many pixels were
+ dropped (`dropped_colors_pixels`) — never a silent cap.
+- Without `--out`, the JSON goes to stdout.
+
+Draft kind: `"kind": "sprite-gen-palette"`. This is authoring scaffolding, not a
+swap. Edit the hex list into a recolor **spec** (next section).
+
+### 2. Bake N variant sheets from a recolor spec
+
+```bash
+# Against a finished run dir (default atlas = sprite-sheet-alpha.png,
+# default out = <run-dir>/variants/, manifest auto-resolved if present):
+$SPRITE_GEN_ROOT/.venv/bin/sprite-gen recolor \
+ --run-dir <run-dir> \
+ --spec <recolor-spec.json>
+
+# Against a free-standing sheet (out-dir required):
+$SPRITE_GEN_ROOT/.venv/bin/sprite-gen recolor \
+ --base <sheet.png> \
+ --spec <recolor-spec.json> \
+ --out-dir <out-dir> \
+ [--manifest <manifest.json>]
+```
+
+Exactly one of `--base` or `--run-dir`. Two truths for one input are refused.
+
+Flags:
+
+| Flag | Default | Role |
+|---|---|---|
+| `--atlas` | `sprite-sheet-alpha.png` | filename inside `--run-dir` |
+| `--out-dir` | `<run-dir>/variants` (with `--run-dir`) | where sheets + report land |
+| `--manifest` | auto `<run-dir>/manifest.json` if present | propagate per-variant, repointing sheet-filename fields |
+| `--alpha-threshold` | `8` | opaque floor; sub-threshold pixels keep RGB, are not targets |
+| `--report` | `recolor.report.json` | report filename inside out-dir |
+
+Also available as:
+
+```bash
+$SPRITE_GEN_ROOT/.venv/bin/python -m sprite_gen.cli recolor ...
+$SPRITE_GEN_ROOT/.venv/bin/python $SPRITE_GEN_ROOT/scripts/recolor.py ...
+```
+
+## Recolor spec
+
+```json
+{
+ "version": 1,
+ "kind": "sprite-gen-recolor",
+ "match": "exact",
+ "tolerance": 0,
+ "variants": [
+ {
+ "name": "moss",
+ "map": {
+ "#b42828": "#3a7a3a",
+ "#f0c000": "#c8a040"
+ }
+ },
+ {
+ "name": "azure",
+ "map": {
+ "#b42828": "#2850b4",
+ "#f0c000": "#80c0e0"
+ }
+ }
+ ]
+}
+```
+
+- `kind` must be `sprite-gen-recolor` — anything else fails loud.
+- `match`:
+ - **`exact`** (default) — a pixel's RGB must equal a source colour to be
+ replaced. Dot art's safe default: anti-aliased edge pixels stay untouched.
+ - **`tolerance`** — opt-in for soft-edged art. An opaque pixel within Chebyshev
+ distance `tolerance` of a source is recoloured to that source's target;
+ nearest source (L2) wins, ties broken by map order. Pure integer arithmetic,
+ so still deterministic.
+- `match: "exact"` with a non-zero `tolerance` is contradictory and refused —
+ two truths for one behaviour.
+- Variant `name`s must be unique; every variant needs a non-empty `map`.
+- Map keys/values are `#RRGGBB` (or `RRGGBB`). A source mapped twice fails loud.
+
+## Bake outputs
+
+Under `--out-dir` (default `<run-dir>/variants/`):
+
+```text
+variants/
+ moss.png
+ azure.png
+ moss.manifest.json # only with --manifest
+ azure.manifest.json
+ recolor.report.json # SSoT for "what the bake did"
+```
+
+Geometry is never touched — only RGB on matching opaque pixels. Alpha is
+byte-identical to the base sheet. Manifest sheet-filename fields that are
+rewritten per variant (when `--manifest` is set): `atlas`, `game_input`,
+`sprite_sheet_alpha`, `sprite_sheet`. Unknown schema keys are copied verbatim.
+
+### Report contract (No Silent Fallback)
+
+`recolor.report.json` (`kind: "sprite-gen-recolor-report"`) is the one truth for
+what the bake did. Per variant it records:
+
+| Field | Meaning |
+|---|---|
+| `substituted_pixels` | total opaque pixels rewritten |
+| `substitutions[]` | per source→target hit count (`pixels: 0` = source never matched) |
+| `unused_sources[]` | the subset of substitutions with `pixels == 0` (typos in the map) |
+| `passthrough_pixels` / `passthrough_color_count` | opaque colours the map did not cover — left unchanged, but **named and counted** |
+| `passthrough_colors[]` | top colours by frequency (capped at 64; over-cap is announced as `passthrough_colors_truncated`, never silent) |
+
+A colour outside the map is never quietly left behind without a name. The
+curation view prints these numbers from the report — it does not re-count
+pixels. Reader: `sprite_gen.effects.recolor.load_report(run_dir)`.
+
+- No report file → `None` ("this run has no variants").
+- A file at the report path with a foreign `kind` → fail loud. Reading it as
+ "no variants" would hide a bake that wrote somewhere unexpected.
+
+## Curation webview — colourway compare and pick
+
+After a bake into `<run-dir>/variants/`, open the ordinary curation view:
+
+```bash
+$SPRITE_GEN_ROOT/.venv/bin/sprite-gen curation --run-dir <run-dir>
+```
+
+The server attaches a `recolor` block to `/api/run` (`serve_curation._recolor_info`).
+The view (`curator/src/recolor.js`) shows:
+
+1. **One stacked stage** — all variant sheets occupy the same place; hovering a
+ list row swaps the visible sheet in place (blink comparison). Side-by-side
+ eye travel loses small palette shifts; blink does not.
+2. **Frame-cell thumbnails** — one cell cropped from the sheet, not the whole
+ atlas. The crop box comes from `manifest.frame_layout` (first frame of the
+ first state). Origin assumptions are forbidden; no layout → no crop style.
+3. **Adopt button** — writes the chosen variant **name** into the curation
+ sidecar.
+
+### Adopted pick SSoT
+
+```json
+{
+ "version": 1,
+ "kind": "sprite-gen-curation",
+ "recolor": { "picked": "moss" }
+}
+```
+
+- Keyed by **variant name**, not a frame index. A colourway is a colour
+ decision, not a frame generation — re-baking does not stamp it stale the way
+ anchors do. Reader: `curation.recolor_pick(curation)`.
+- A name that the current bake no longer produces is **kept** and reported as
+ `pickedKnown: false` (banner in the view). It is never silently cleared.
+- A save from a run that has no recolor section does not author the field; the
+ server carries the existing pick over (same contract as `anchors`). An
+ unrelated edit cannot erase an adopted colourway.
+- File tree shows a `variants/` folder with an adopt badge on the picked name.
+
+Schema detail and the rest of the sidecar live in [`curation.md`](curation.md).
+
+## Typical workflow
+
+```bash
+# 1. Compose the base atlas first (or start from any finished sheet).
+$SPRITE_GEN_ROOT/.venv/bin/python \
+ $SPRITE_GEN_ROOT/scripts/compose_sprite_atlas.py --run-dir <run>
+
+# 2. Draft the palette from the base sheet.
+$SPRITE_GEN_ROOT/.venv/bin/sprite-gen recolor-palette \
+ --base <run>/sprite-sheet-alpha.png \
+ --out <run>/palette.draft.json
+
+# 3. Author the recolor spec (edit the draft hex list into source→target maps).
+# Save as e.g. <run>/recolor.spec.json with kind "sprite-gen-recolor".
+
+# 4. Bake every colourway in one command.
+$SPRITE_GEN_ROOT/.venv/bin/sprite-gen recolor \
+ --run-dir <run> \
+ --spec <run>/recolor.spec.json
+
+# 5. Compare and adopt in the curation view.
+$SPRITE_GEN_ROOT/.venv/bin/sprite-gen curation --run-dir <run>
+```
+
+Ship the adopted sheet from `<run>/variants/<picked>.png` (and its sibling
+manifest if one was propagated). The base atlas stays the geometry SSoT.
+
+## What this is not
+
+- Not a runtime filter. The game loads a baked PNG.
+- Not a second atlas composer. Geometry, cell size, and `frame_layout` come
+ from the base; recolor only rewrites colours.
+- Not a silent repair tool. Unused sources and passthrough colours are always
+ in the report — fix the map, do not paper over a miss.
+
+## Related
+
+- [`../SKILL.md`](../SKILL.md) — hub, trigger routing, script map
+- [`curation.md`](curation.md) — webview + `curation.json` schema (`recolor.picked`)
+- [`run-contract.md`](run-contract.md) — run-dir folder tree (`variants/`)
+- `tests/test_recolor_bake.py` — determinism, exact/tolerance, report contract
+- `tests/test_recolor_curation_view.py` — view payload, pick round-trip, fail-loud foreign report
+- `tests/test_recolor_cli_entrypoint.py` — CLI identity across entry forms
+- `tests/test_recolor_docs.py` — doc surface lock (hub + leaf teach the same commands)
diff --git a/docs/run-contract.md b/docs/run-contract.md
new file mode 100644
index 0000000..2d59698
--- /dev/null
+++ b/docs/run-contract.md
@@ -0,0 +1,553 @@
+# Run Contract — pipeline stages · run-dir folder tree · curation-view display (SSoT)
+
+> Status: **contract** (normative). This doc is the single source of truth for
+> three things every sprite-gen run must satisfy so that **any agent who serves a
+> view gets the same experience** — the base reference row, the per-state
+> generation-material chips, the pixel grid, and the original-quality toggle.
+>
+> Precedence (no overlap, so no contradiction):
+> - [`../SKILL.md`](../SKILL.md) owns the **behavior** contract — what the agent does, step by step.
+> - **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
+> doc wins; architecture.md is the bug.
+
+## 1. Pipeline stages
+
+One image-gen call **per state row** is the only AI step; every stage after it is
+deterministic (same input → same output). Each script does one job and reads/writes
+canonical files, not hidden imports.
+
+| Stage | Script | Input | Output |
+|---|---|---|---|
+| Prepare | `prepare_sprite_run.py` | base image + request flags/JSON | `sprite-request.json`, per-state layout guide, per-state prompt, empty `raw/`+`frames/` |
+| Generate | `sprite-gen gen` (`generate_sprite_image.py`) | `prompts/<state>.txt` + refs | verified `raw/<state>.png` strip + audit raw/report |
+| Extract | `extract_sprite_row_frames.py` | `raw/<state>.png` | on success: `frames/<state>/frame-N.png` (+ `.plain.png` twin on pixel-unfake runs), `frames/frames-manifest.json`; on failure: nothing in `frames/`, `extract-failure.json` instead (§6) |
+| Curate (opt) | `sprite-gen curation` (`serve_curation.py`) + `curation.py` | `frames/` | `curation.json` sidecar |
+| Compose | `compose_sprite_atlas.py` | `frames/` + `curation.json` | `sprite-sheet-alpha.png`, `manifest.json`, `*.report.json` |
+| Engine export (opt) | `sprite-gen export-aseprite` (`sprite_gen/compose/export_aseprite.py`) | composed `manifest.json` + existing atlas | `exports/aseprite.json`, or `exports/aseprite/<state>.json` for Flame |
+| Recolor (opt) | `sprite-gen recolor` / `recolor-palette` (`sprite_gen/effects/recolor.py`) | base sheet (default `sprite-sheet-alpha.png`) + recolor spec | `variants/<name>.png`, optional `variants/<name>.manifest.json`, `variants/recolor.report.json` |
+| 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 |
+| Correction loop | `run_correction_loop.py` | run dir + optional provider command | `correction-loop.report.json`, per-attempt inspect/score/hints |
+| GIF export | `compose_sprite_gif.py`, `gif_utils.py` | selected frames | clean transparent GIF into `exports/` |
+| Selected cycle | `compose_selected_cycle.py` | `curation.json` / `--frames` | selected-cycle manifest + QA |
+| Inverse / import | `unpack_atlas_run.py` | finished atlas **or** `--pngs-dir` | curator-ready run dir (§4) |
+| Export stills | `export_curated_pngs.py` | curated `frames/` | named PNGs under `curated/` |
+| Chroma guard | `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
+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
+is the explanation.
+
+## 2. Run-dir folder contract
+
+**One worker owns exactly one character folder.** This is the canonical tree — do
+not restate it elsewhere; point here.
+
+```text
+<target>/assets/generated/sprites/<character-id>/
+ sprite-request.json # numeric SSoT (cell, chroma, states, fit) — every stage reads this
+ base-source.<ext> # identity truth; drives the view's base reference row (§3)
+ references/layout-guides/<state>.png # per-state layout guide (motion only)
+ references/anchors/<dir>-anchor-x8.png # DERIVED CACHE: the curated direction-anchor frame, baked
+ # ×8 NEAREST for row generation. `sprite-gen anchor`
+ # (SSoT sprite_gen/curate/anchor.py) rewrites it on demand —
+ # never hand-edit it and never treat it as truth.
+ references/imported/<group>/ # imported-run generation material → chips (§4); real runs use raw/ anchors instead
+ prompts/<state>.txt # generated row prompt (frame count, safe margin, anchor lock)
+ raw/<state>.png # one horizontal image-gen strip per state (the only AI output)
+ frames/<state>/frame-N.png # extracted transparent cells — PRE-CURATION.
+ # **Not the deliverable.** These are the extractor's own
+ # output; the human's picks, pixel edits, transforms,
+ # deletions and clones live in `curation.json` and are
+ # applied downstream. An app that copies from here
+ # silently ships the un-edited image (see §2-c).
+ # ── 파일 택소노미 (layout: taxonomy/v1 — 신규 런 기본, maintainer 확정 2026-07-14) ──
+ # 방향 계약(directions) 런은 위 두 경로가 방향/자세 폴더로 나뉜다. 상태 ID 는 그대로
+ # <direction>_<pose>, 파일 경로만 분리. 리졸버 SSoT = sprite_gen/spec/layout.py.
+ # 이미 추출된 프레임을 읽는 소비자는 frames-manifest 의 row.files 경로를 따른다
+ # (row_frame_rel) — 패턴 조립 금지. layout 필드 없는 legacy 런은 flat 유지.
+ # 프로젝트별 정비 방식이 지침으로 오면 지침이 우선한다.
+ raw/<direction>/<pose>.png # 택소노미: 생성 스트립
+ raw/<direction>/<pose>.takes/<label>.png # 테이크: 같은 상태의 추가 후보/보강 스트립 (아래 참조)
+ frames/<direction>/<pose>/frame-N.png # 택소노미: 추출 프레임 (+ .plain / orig/)
+ references/layout-guides/<direction>/<pose>.png
+ prompts/<direction>/<pose>.txt
+ # ── 테이크 (takes 1급 계약, 2026-07-15) ── request `states.<s>.takes: [{label, frames}]`
+ # 가 선언하면 추출이 primary 스트립 뒤에 각 테이크 스트립을 이어붙여 한 행의 프레임
+ # 풀을 만든다 (스트립별로 따로 스냅 — 프레임 자체 검출 격자 1순위, 스트립 합의는
+ # 검출 실패 프레임 fallback 전용. 행 정합·팔레트·배치는 함께).
+ # manifest row 에 labels("blink#0"…)/takes(start·frames·raw)가 남고, 소비자가 행
+ # 크기를 request 에서 셀 때는 layout.state_frame_total(primary+takes 합)을 쓴다.
+ # 어느 스트립 하나라도 실패하면 행 전체가 이전 세대로 남는다 (부분 풀 게시 금지).
+ frames/<state>/frame-N.plain.png # pixel-unfake runs only: cell-sized pre-pixel-unfake twin, baked by compose on pixel_unfake:false (§3)
+ frames/<state>/orig/frame-N.png # pixel-unfake runs only: hi-res original twin (display-only), drives the pp-off toggle at original quality (§3)
+ frames/frames-manifest.json # per-row extract report (files, labels, ok) — only ever a COMPLETE ok generation (§6)
+ # frames/ 는 (raw + request + 엔진)의 파생 캐시다 (실시간 계약, maintainer 확정 2026-07-14):
+ # 행별 engine_revision(엔진 소스 해시) 스탬프가 캐시 키. 소비자(큐레이션 뷰 /api/run·
+ # /api/progress, compose_atlas, /download/*)는 진입 시 extract.heal_run 으로 stale 행을
+ # raw 에서 자동 재유도한다 — 뷰에 '재추출' 개념이 없다. raw 가 없는 행은 보존 + 관측
+ # 노트(kept_stale). manifest 의 extract_args 가 재유도 플래그 재현을 보장한다.
+ extract-failure.json # while any state's extract is unresolved: per-state ok:false diagnostics, OUTSIDE frames/ (§6); merged per state, removed once all resolved
+ curation.json # optional, non-destructive sidecar (selected/order/transforms/pixel_unfake)
+ unpack-source.json # import runs only (unpack_atlas_run.py): provenance — atlas/pngs source, base_source, imported_refs
+ sprite-sheet-alpha.png # composed runtime atlas
+ sprite-sheet-alpha.report.json # compose report
+ manifest.json # runtime SSoT: frame_layout absolute rects
+ variants/ # only when sprite-gen recolor runs — baked colourway sheets
+ # (<name>.png + optional <name>.manifest.json) +
+ # recolor.report.json (SSoT for substituted / unused /
+ # passthrough pixels). Adopted pick lives in
+ # curation.json.recolor.picked (name-keyed). See
+ # docs/recolor.md.
+ 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
+ qa/<state>-contact.png # QA contact sheet
+ qa/<state>.gif # QA state GIF
+ qa/<name>.gif, qa/<name>-contact.png, qa/<name>.json # compose_selected_cycle.py: named selected-frame cycle + its manifest
+ qa-notes.md # per-state motion verdict + reference-plan notes
+ curated/ # only when export_curated_pngs.py runs — CURATION APPLIED.
+ # This is what an external consumer installs (§2-c).
+ exports/ # only when compose_sprite_gif.py --run-dir runs (per-state GIF + gif-manifest.json)
+ .sprite-gen.lock # single-writer lock (runio.py); a live holder blocks a second writer (§7 guarantee boundary)
+ .frames.sg-staging/ # transient: extract builds the new generation here, swapped into frames/ under publish_guard
+```
+Transient publish sidecars exist only during an extract/import commit: `.frames.sg-backup`
+and `.extract-failure.sg-backup` (in-place rollback copies) and `.<name>.sg-rwlock` (in the
+parent dir — the publish reader/writer lock). Their durability/concurrency boundary is §7.
+
+Rules the display depends on:
+
+- **`base-source.*` is the identity truth** and must survive independent of baking —
+ the view shows it as a top reference row (§3) whether or not it was attached to any
+ row. Real runs write it in Prepare; imported runs write it from `pngs/_base/` (§4).
+- **`raw/<direction>_idle.png` and `raw/down_<state>.png`** are what the view resolves
+ into per-state generation-material chips for real (directional-anchor) runs — the
+ chip is "which anchor / basis row / guide generated this state". See
+ [`directional-anchor-workflow.md`](directional-anchor-workflow.md) for the naming.
+- **`references/imported/<group>/`** is the imported-run equivalent of those raw
+ anchors: an imported row carries its generation material here so the view produces
+ the same chips (§4).
+- **`frames/<state>/frame-N.plain.png`** (pixel-unfake runs only) is the *cell-sized*
+ pre-fit twin that `compose` bakes when the sidecar turns pixel-unfake off for that
+ state (`states.<state>.pixel_unfake:false`, or the run-wide `pixel_unfake:false`
+ default — resolver: `curation.frame_variant(curation, state)`) — the
+ atlas slot is cell-sized, so this twin must be too. **`frames/<state>/orig/frame-N.png`**
+ is the *hi-res* (S×cell) pre-fit twin the view displays when the user turns
+ pixel-unfake off, so "off = original" is crisp instead of an upscaled cell blur.
+ S is **per-row native**: the ceil of the largest component-crop / final-content-bbox
+ ratio across the row's frames (bounded by `2048 // cell`), so the twin resample is a
+ mild upscale — never a downscale. The old fixed ×4 cap squeezed high-pitch raws
+ (synthetic_fixture_b down rows, ~14px pitch) ~3.5× and the "original" view stopped being the
+ original (maintainer, 2026-07-23). The
+ view prefers `orig/`, falling back to `.plain.png` when no hi-res twin exists. Both
+ twins are fitted into the pixel-unfake frame's content bbox (same footprint), so the
+ toggle compares pixel treatment at identical size and a plain bake keeps the same
+ character size as pixel rows.
+ Sidecar-baking semantics are owned by [`pixel-unfake.md`](pixel-unfake.md); the
+ display contract for the toggle is §3.
+
+The runtime `manifest.json.frame_layout` contract (absolute rects, no runtime
+alpha-recovery, `degraded_static_fallback: false`) is owned by
+[`../SKILL.md`](../SKILL.md) "Runtime Contract" and is out of scope here.
+
+## 2-b-2. Reading a run never writes to it
+
+`sprite-request.json` has exactly one read gate (`runio.load_request`) and exactly one
+schema writer (`runio.migrate_request_file`, exposed as `sprite-gen migrate-request
+<run-dir> --apply`). They are separate on purpose.
+
+- **Reads are byte-stable.** `load_request`, and everything that goes through it
+ (`state_revision`, `run_revision`, `load_curation`, the view's snapshot endpoints),
+ leave the run directory byte for byte identical. A retired key (`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.
+ The curation sidecar reads the same way: a generation-mismatched `curation.json` is
+ salvaged row by row **in memory** and the file itself is left alone — the load gate
+ writes no backup copy (see the bullet below).
+- **Schema migration is an explicit command.** It is a dry run unless `--apply` is passed.
+ The write takes the **publish rwlock** (`runio.publish_guard`) — the same exclusive lock
+ the request editors take — re-reads the document *after* acquiring it, and replaces the
+ file atomically. It deliberately does not take the pipeline `.sprite-gen.lock`: that lock
+ guards stage outputs (frames, atlas), and extraction/compose never write the request, so
+ holding it would look like protection while the actual competitors (reroll, interpolate,
+ the view's fps edit) walked straight past it. One resource, one isolation domain.
+- **Every request read-modify-write shares that one domain.** Migration, take recording
+ (`reroll.record_take`, `interpolate.write_take`) and the view's fps POST all do
+ *acquire → fresh re-read → atomic replace* inside `publish_guard`, so no pair of them can
+ lose the other's write. Locked by named race tests plus a structural assertion that no
+ production request write sits outside the guard
+ (`tests/test_request_write_isolation.py`).
+- **A stale backup is written by the writer, never by a read.** `curation.stale-<hash>.json`
+ is created only by `curation.write_curation_atomic`, at the moment an overwrite would
+ actually lose rows. The load gate used to write it while merely *judging* a
+ generation-mismatched sidecar — a read that created a file in the run dir, the same class
+ of defect as the incident below. Nothing is lost at drop time: `curation.json` is still
+ on disk, untouched.
+- **Unrelated edits preserve the on-disk key form.** Take recording (reroll / interpolate)
+ and the view's fps edit reload the whole document through the gate and write it back, so
+ they go out through `runio.write_request`, which folds a normalized key back to whatever
+ the file actually carries. Otherwise changing one fps value would migrate the schema as a
+ side effect, and "only the explicit command changes the schema" would be false the moment
+ anyone edited anything.
+
+A synthetic regression fixes the failure mode: normalizing a retired key during a
+`state_revision()` query must not rewrite `sprite-request.json`, move `run_revision`, or
+knock a curation sidecar stale. A query has no business changing what it reports on.
+
+Migration does change the file bytes, so it does move `run_revision`. The curation sidecar
+survives it through per-row `revision` salvage (§ `curation.load_curation_report`); rows
+with no stamp are dropped as usual, and `migrate-request` prints which rows those are
+*before* it writes.
+
+## 2-c. External consumers install from `curated/`, never from `frames/`
+
+`frames/` is the extractor's own output. Everything a human does in the curation view —
+frame picks, play order, **pixel edits**, transforms, deletions, clones — lives in
+`curation.json` and is applied *downstream*, not written back into `frames/`.
+
+So an app that copies `frames/<state>/frame-N.png` into its assets **silently ships the
+un-edited image**. Nothing fails: extract succeeded, the file exists, the copy succeeded.
+The only signal is a human noticing their work is gone.
+
+A synthetic regression fixes this failure mode: copying from `frames/` after a pixel edit
+must not be treated as a curated export, because it would silently discard the edit.
+
+Rules for anything outside this repo:
+
+- **Stills / single frames** → run `export_curated_pngs.py`, install from `curated/`.
+- **Animation** → consume `sprite-sheet-alpha.png` + `manifest.json` from
+ `compose_sprite_atlas.py` (compose already reads `curation.json`).
+- **Never** reach into `frames/` unless you are re-deriving the cache itself.
+- If a tool must accept both, it **prefers `curated/` and says which one it read** — a silent
+ choice between two sources is how the edit disappears.
+
+Inside this repo the compose/GIF/atlas paths already read `frames/` *together with*
+`curation.json`, which is correct; the hazard is external copying.
+
+## 3. Curation-view display contract
+
+`serve_curation.py` serves one run dir and returns the run snapshot at `GET /api/run`.
+The webview (`sprite_gen/serve/curator/*`) renders exactly four contract elements from that
+payload. **A view that omits any element it has the data for is a broken view** — the
+whole point is that the experience does not vary by who launched it.
+
+| Element | Shown when | Payload source | Rule |
+|---|---|---|---|
+| **Base reference row** | `base-source.*` exists | `baseUrl` (null if absent) | Top row, pure image — no preview/select UI. Identity truth, always visible. |
+| **Generation-material chips** | the state has resolvable material | `states[].refs[]` — each `{role, name, url}` | Per-state header shows *what generated this row*. `role ∈ {anchor, basis, guide}`, labelled `방향 앵커` / `basis row` / `레이아웃 가이드` (i18n key `ref_<role>`). Only run-dir files that actually exist appear — **except the anchor chip** (`anchorFrame: true`), which is a live bake (`/api/anchor?direction=<dir>`) named `<state>#<index>`, because the on-disk `references/anchors/*.png` is a derived cache that goes stale the moment the user edits the anchor frame. |
+| **Anchor frame** | request has a `directions` block | `directionGroups[].anchorFrame` `{state, index, source}` + `anchorError`/`anchorErrorCode`/`anchorPending`/`anchorUrl` · `curation.anchors` | The one curated instance that is this direction's identity for generating its other rows. `source: "picked"` = pinned by the human (frame card pin button → `curation.anchors.<dir>`), `"default"` = the anchor row's sequence head. The anchor card carries an `앵커` badge (tinted when pinned); an unresolvable pin surfaces `anchorError` in the status bar instead of silently reverting — archived frame (`pick-missing`) or **regenerated row** (`pick-stale-generation`: the pin carries the pinned row's `state_revision`, so a re-derived row makes the pin stale rather than silently pointing it at a different image). **`anchorPending: true` is not an error** — the anchor row is not generated yet (the normal mid-work state), so the view must not colour it as a failure. Resolution SSoT = `sprite_gen/curate/anchor.py`. |
+| **Pixel grid** | **always** — the measurement cannot fail | `states[].pixelScale` (≥1, never null) + `pixelUnfake{label,scale}` + `states[].frames[].contentBox` | **Per-state** checkbox on every row's refs strip; the top checkbox is a **toggle-all** (indeterminate when mixed). Display only, never persisted. `pixelScale` is an exact test (largest k where the frame is only uniform k×k blocks; k=1 is trivially true — identity), so "unknown grid" does not exist and nothing gates on it. On the pixel-unfake view: the output raster (request scale on `fit.pixel_unfake` runs, measured k labelled `auto` otherwise). On the original (plain) view: the **final correspondence grid** — green, one cell = one result pixel. (The stage-1 cut lattice in `frames-manifest input_grids` stays diagnostic-only.) An identity grid (k=1) is a true grid, not a missing one — density is a property of the fact, not a reason to hide the control. |
+| **Direction groups** | request has a `directions` block | `directionGroups[]` — `{direction, anchor, states, anchorFrame, anchorError}` + mirror entries `{direction, mirrorOf}` | States render grouped per direction with the direction anchor first (badge `방향 앵커`); mirrored directions render as an informational strip (`<src> 런타임 미러 — 생성 없음`), never as silently missing rows. Runs without the block keep the flat request order. |
+| **Original-quality toggle** | **always** — every row has the control | `states[].frames[].plainUrl` + `fitPixelUnfake` | **Per-state** checkbox on every row's refs strip + zoom modal (same contract, no per-surface gating). Twin rows: on = canonical `frame-N.png`, off = `plainUrl` (hi-res `orig/` else `.plain.png`) — a **source** switch, persisted per state. Twin-less rows: on = the display renderer re-quantizes by the measured grid `pixelScale` (the same k the grid overlay draws — grid-based pixel-unfake; k=1 is identity), a **display lens**, never persisted (persisting would make the bake resolver demand a `.plain` variant that does not exist). The top-right checkbox is a toggle-all (indeterminate when mixed). |
+
+`GET /api/run` payload — the display-relevant subset below (the full snapshot,
+including non-display fields like `states[].action`, is assembled by
+`build_run_state`):
+
+```jsonc
+{
+ "characterId": "demo-hero",
+ "runDir": "<abs path>",
+ "baseUrl": "/run/base-source.png", // base reference row; null when no base-source.*
+ "cell": { "width": 256, "height": 256 },
+ "pixelUnfake": { "logicalHeight": 48, "scale": 5, "source": "request", "label": "48px" },
+ // or { "source": "auto", "label": "auto", "scale": <min measured k, ≥1> } — never null
+ "fitPixelUnfake": true, // request opted into the deterministic pixel-unfake path
+ "runRevision": "9f3c1a0b7e2d4c58", // frame-content fingerprint of this generation; POST /api/curation echoes it (stale ⇒ 409)
+ "hasAtlas": true,
+ "iso": null, // sibling meta.json iso tile/anchor → ground-grid overlay
+ "lang": "ko",
+ "schemaVersion": 1,
+ "states": [
+ {
+ "name": "down_walk",
+ "pixelScale": 5, // request scale, or exact measured k — always ≥1, never null (k=1 = identity)
+ "refs": [ // generation-material chips
+ { "role": "anchor", "name": "down_idle#2 · picked", // live bake of the curated anchor frame
+ "url": "/api/anchor?direction=down&v=9f3c1a0b7e2d4c58", "anchorFrame": true },
+ { "role": "guide", "name": "down_walk.png", "url": "/run/references/layout-guides/down_walk.png" }
+ ],
+ "fps": 8, "loop": true, "requestFrames": 6, "extractOk": true,
+ "frames": [
+ { "index": 0, "url": "/frames/down_walk/frame-0.png",
+ "plainUrl": "/frames/down_walk/orig/frame-0.png", // hi-res orig/ twin (else cell-sized .plain.png); present ⇒ toggle available
+ "present": true, "label": "step-1",
+ "size": [256, 256], "contentSize": [120, 210] } // contentSize = alpha bbox, for size-parity review
+ ]
+ }
+ ],
+ "contract": { "base": true, "refs": true, "refsStates": 1, "grid": true, "sourceless": false },
+ // self-report (§3): grid is always true (measurement cannot fail); sourceless=true when base+refs are both absent → server warns at startup
+ "curation": { /* current sidecar snapshot, or empty */ }
+}
+```
+
+`pixelUnfake.scale` is `cell.height // fit.logical_height` (integer floor), so the
+example's `256 // 48 = 5` (not 5.33 — floor); `label` is `"<logical_height>px"` and
+`logicalHeight` echoes `fit.logical_height`. `states[].pixelScale` mirrors that scale
+on a `fit.pixel_unfake` run, or carries the per-row auto-measured block pitch on a
+run with no pixel-unfake contract (import/plain), or `null` when a row's pitch cannot
+be measured. Real runs are usually smaller than this synthetic 256 example — the
+synthetic fixture anchor is `cell 56 / logical 48 → 56 // 48 = 1`.
+
+Display invariants (enforced by the server, not by the launching agent):
+
+- The base row, chips, grid, and toggle are all **derived from run-dir files** — an
+ agent cannot "forget" to set them up. If a source file is missing the element is
+ simply absent; there is no per-agent styling step to get wrong.
+- `contentSize` (alpha bbox) is exposed so a reviewer can spot size-parity drift
+ across a row without opening each frame.
+- Standalone image-candidate curation (icons / logos / drafts — not sprites) and the
+ webview interaction model (select/reorder/transform, `curation.json` schema,
+ multi-agent launch rules) live in [`curation.md`](curation.md); this section owns
+ only the four display-contract elements above.
+
+## 4. Import-run source rule (`--pngs-dir`)
+
+An imported run (a folder of separate PNGs, no generation pipeline) must reach the
+**same** display contract as a real run: a base reference row and per-state
+generation-material chips. The importer treats source material as first-class, not
+just frames.
+
+Import folder layout accepted by `unpack_atlas_run.py --pngs-dir <dir>`:
+
+```text
+pngs/
+ _base/<any>.png # optional — identity/base image for the whole set
+ <group-a>/ # one subfolder = one curator row (state)
+ 1-name.png # frames; numeric prefix sets play order
+ 2-name.png
+ _refs/ # optional — this row's generation material
+ anchor-<name>.png # role = direction anchor
+ basis-<name>.png # role = basis row
+ guide-<name>.png # role = layout guide
+ <group-b>/ ...
+ meta.json # optional — human labels + iso tile/anchor (§3 grid overlay)
+```
+
+Mapping into the run dir (so both view code paths resolve identically):
+
+- `pngs/_base/<img>` → `base-source.png` → drives the base reference row (`baseUrl`).
+- `pngs/<group>/<frames>.png` → `frames/<group>/frame-N.png` → the row's frames.
+- `pngs/<group>/_refs/<role>-<name>.png` → `references/imported/<group>/<role>-<name>.png`
+ → the row's generation-material chips. The role is the filename prefix and **must** be
+ `anchor` / `basis` / `guide` (same vocabulary as §3, owned by `curation.IMPORTED_REF_ROLES`).
+ A `_refs` file with any other prefix is malformed input: the importer **fails loud**
+ (lists the offending files) — it never silently relabels an unknown role as `guide`.
+
+`serve_curation.py`'s `_state_refs` resolves chips from `raw/` anchors for real runs
+and from `references/imported/<group>/` for imported runs — one chip vocabulary, two
+sources, identical rendering. A `_base`/`_refs`-free import still works (frames only,
+no base row, no chips), but then the view honestly shows "no source material" rather
+than a divergent experience.
+
+**`--force` re-import is a writer-isolated, rollback-safe, reader-atomic rebuild.** It
+validates all inputs, builds the new run into a staging dir, then publishes it over the
+run dir. A **successful** re-import reflects **only** the current input — removing a
+`_base`/`_refs` source and re-importing leaves no stale `base-source.png` /
+`references/imported/*` behind, so provenance (`unpack-source.json`) and the served view
+never disagree (Idempotency/SSoT: the result never depends on the prior out-dir state).
+A **failed or invalid** re-import (e.g. a bad `_refs` role) leaves the prior run
+**byte-intact** — it is never cleared-then-failed (write-side Atomicity: a rebuild fully
+succeeds or rolls back). The publish holds the run-dir single-writer lock in place
+throughout, so a concurrent **writer** cannot preempt (writer Isolation).
+
+> **Reader isolation (named strategy: reader/writer locking).** Every operation that
+> republishes frames — a `--force` re-import **and** a re-extract (`extract` builds into a
+> staging dir, then swaps `frames/` into place) — holds the run dir's *exclusive* publish
+> lock (a sidecar `.<name>.sg-rwlock` `flock`, `runio.publish_guard`) around the swap, while
+> `serve_curation` reads (`/api/run` **and** run-dir file requests) under the matching
+> *shared* read lock (`runio.read_guard`). So a webview serving that same run dir
+> concurrently always sees a **complete old-or-new snapshot** —
+> never a half-published (old/new-mixed or missing-file) state, and never a transient
+> `HTTP 500`. The reader blocks only for the brief swap. The rwlock is a sidecar (beside
+> the run dir), so it survives content swaps and is never itself published. Where `fcntl`
+> is unavailable or the sidecar can't be created, the guard **fails loud** (raises
+> `runio.RWLockUnavailable`) rather than degrading to a no-op: a no-op would be a failover
+> that lets canonical truth change inside a read transaction (a reader could observe a
+> half-published run), and the isolation contract permits an availability failover only
+> when it stays observable **and does not change canonical truth**. The pipeline runs on
+> platforms with `fcntl` advisory locks (macOS/Linux); a platform without them refuses the
+> publish/read rather than silently serving a partial run.
+>
+> The curation **write** (`POST /api/curation`) takes the same exclusive publish lock, so
+> a `select`/`reorder`/`transform` autosave is serialized with a concurrent re-import; and
+> the POST must echo the `runRevision` (a frame-content fingerprint) it was loaded with —
+> a POST from a different run generation is **rejected** (`HTTP 409`). So a stale autosave
+> from a webview still on a pre-re-import (or pre-re-extract) run can never apply old
+> selections/transforms to new frames, **even when the re-import keeps the same state
+> names** but swaps the candidate images (Consistency — run identity, not just state
+> membership).
+>
+> **Load** 쪽은 행 단위다: `run_revision` 이 어긋나도 각 행의 `revision`(원료 세그먼트
+> 지문, `curation.state_revision`)이 현재의 접두면 그 행 큐레이션은 유지된다 — 같은 raw
+> 를 새 엔진이 재유도(heal)해도 선택이 살아남는다. 드롭되는 행이 생기면 `/api/run` 의
+> `curationDropped` 로 웹뷰 배너에 보고된다 (조용한 소실 금지). 로드는 아무것도 쓰지
+> 않는다 — 원문은 그대로 남아 있고, 실제로 덮이는 순간 writer 가
+> `curation.stale-<hash>.json` 으로 보존한다.
+> 스키마/규칙 상세: [`curation.md`](curation.md).
+
+## 5. Conformance status
+
+All four contracts are enforced by the shipped scripts today:
+
+- Stage table (§1), folder tree (§2), and the base-row / chips / grid elements of §3.
+- The "off = original quality" toggle (§3): extract writes a hi-res `orig/` twin the
+ view prefers, so pp-off is crisp; the cell-sized `.plain.png` stays for the `compose`
+ bake. Canonical `frame-N.png` bytes are unchanged (deterministic — verified
+ byte-identical on re-extraction of hero v6/v7).
+- The `--pngs-dir` `_base`/`_refs` embedding (§4): imported runs reach the same base
+ row + chips as real runs.
+- The view-contract self-report (§3): serve_curation logs base/refs/grid coverage at
+ startup and warns on a sourceless view.
+
+Verified end-to-end on three views — hero v6 (`base=yes refs=12/12 grid=yes`),
+synthetic fixture (`refs=36/36`, anchor/basis/guide chips across down/side/up), and a
+comprehensive `_base`+`_refs` import — plus a sourceless run that emits the warning.
+
+## 6. Failed extract is atomic — no partial generation in `frames/`
+
+Canonical `frames/` only ever holds a **complete** generation. A failed extract — the
+**first** extract on a fresh run *or* a re-extract — publishes **nothing** to `frames/`
+(strict whole-generation Atomicity: the operation fully succeeds or leaves canonical state
+untouched). A failed re-extract additionally leaves the prior complete generation
+byte-intact, and the frames publish stays reader-atomic under `publish_guard` (§4).
+
+The per-state failure signal is **not** discarded — it is written **outside** `frames/` as
+`extract-failure.json` in the run-dir root, so it stays observable (No Silent Fallback) and
+still drives the automatic correction loop:
+
+- `extract-failure.json` holds the **union of the run's currently-unresolved per-state
+ failures** — `ok:false`, per-state `errors`/`warnings` — and the CLI exits `1`.
+- The **automatic correction loop** consumes it: `inspect._manifest_state_notes` reads the
+ per-state `errors` from `extract-failure.json` (alongside the published
+ `frames/frames-manifest.json` row) to drive inspect → score → correction-hint →
+ regeneration. So error-driven regeneration keeps its *which state failed, and why* signal
+ even though `frames/` holds only complete generations.
+- The evidence is maintained **per state**, because a subset `--states` extract (the formal
+ single-row / auto-correction path) only determines the outcome of the states it targets: a
+ target state that succeeds is removed, a target state that fails is (re)recorded, and states
+ the attempt did not touch keep their prior failure. So a `walk` success never erases an
+ unresolved `idle` failure, and an `idle` failure never overwrites a `walk` one. The file is
+ deleted only once **no** per-state failure remains (Consistency — never re-flag a now-good
+ state, never silently drop a still-broken one).
+- Advancing the two canonical surfaces is **one transaction**: `extract` swaps `frames/`
+ and (re)writes/removes `extract-failure.json` under a single `publish_guard`, rolling
+ **both** back together on any **in-process** I/O failure (a raised exception), so a reader
+ never sees a new generation beside a stale failure record. Readers that combine them
+ (`inspect` / the correction loop, via `inspect_run`) hold the matching `read_guard` for the
+ whole read. (This rollback covers raised exceptions; a hard **process kill** mid-swap is a
+ known durability gap — see the guarantee boundary in §7.)
+- A **complete generation** is enforced beyond JSON schema: a finished-generation consumer
+ (`compose_*` / `export_pngs` / `preview`) calls `extract.require_frames_manifest`, and
+ `serve_curation` / `inspect` call `extract.load_consistent_frames_manifest`, which verify the
+ manifest AGREES with the physical frame tree and the request — every request state has exactly
+ one row, no physical frame dir is an orphan the manifest omits, and every row's canonical
+ frames exist on disk. `{"ok":true,"rows":[]}` over real frames, a deleted frame, or frames with
+ **no** manifest (an orphan, distinct from a fresh scaffold) all fail loud; `compose_gif` /
+ `export_pngs` likewise fail on a missing selected frame instead of silently skipping it. A run
+ with no generation at all (no manifest, no frames) still serves the request/state scaffold.
+- A **corrupt** canonical record fails loud on **every** path — the writer *and* every reader.
+ Extract's subset-seeding + commit, `inspect._manifest_state_notes`, and every
+ finished-generation consumer (`compose_atlas` / `compose_cycle` / `compose_gif` /
+ `export_pngs` / `preview` via `extract.require_frames_manifest`, and `serve_curation` via
+ `extract.load_frames_manifest`) go through the shared typed loaders
+ (`extract.load_frames_manifest` / `load_failure_evidence`) that refuse an unreadable /
+ unparseable / broken-schema record (must be a `dict`; `errors`/`warnings`/`rows` lists whose
+ entries are non-empty strings / `state`-bearing objects; a frames manifest must be `ok:true`,
+ failure evidence `ok:false` with non-empty `state`-scoped `errors`) rather than treating it as
+ empty. Absence still returns empty (a run with no generation yet); only an existing-but-broken
+ record fails loud. Silently reading a corrupt `extract-failure.json` as "no failures", or a corrupt
+ `frames/frames-manifest.json` as "no prior rows" (then publishing an incomplete manifest that
+ disagrees with the carried frame tree), is exactly the No-Silent-Fallback violation this
+ forbids. A corrupt prior manifest fails a subset re-extract loud **before** it stages
+ anything, so the prior generation stays byte-intact.
+- `compose_atlas` requires a complete generation: it fails loud if
+ `frames/frames-manifest.json` is absent (a failed extract published none) and refuses a
+ non-`ok` manifest, so a partial never becomes an atlas.
+
+The curation view tolerates a run with **no generation** (no `frames/`, no manifest):
+`serve_curation` falls back to an empty row set and `curation.run_revision` treats the missing
+manifest as an empty fingerprint, so the view shows the request/state scaffold rather than
+erroring. Physical frames *without* a manifest are an orphan, not a scaffold — that fails loud
+(see the complete-generation bullet above).
+
+## 7. Guarantee boundary — atomicity & concurrency (honest scope)
+
+To avoid claiming guarantees the code does not provide (No Silent Fallback), this is the exact
+boundary of the run-dir's atomicity and concurrency guarantees. What is **in force today**:
+
+- **In-process transaction rollback.** The `frames/` + `extract-failure.json` commit (§6) and
+ the `--force` re-import publish (§4) roll back on any raised exception, leaving the prior
+ generation byte-intact. `atomic_write_text` / `os.replace` make each file write torn-free.
+ `atomic_write_set` extends the same mechanism to a **set** that only means anything
+ together — the layer bake's sheets, manifests and the report naming them: everything is
+ staged before anything is renamed in, so a write error partway through publishes nothing
+ (a `SIGKILL` between renames stays out of scope, below).
+- **Reader isolation.** A publish holds the exclusive `publish_guard` for its swap; a reader
+ sees a complete old-or-new snapshot, never a mix (§4). Where advisory locks are unavailable the
+ guard **fails loud** (`RWLockUnavailable`), never a silent no-op. Every finished-generation
+ consumer has exactly one named isolation strategy against a concurrent extract/import publish:
+ - **shared `read_guard`** wrapping the whole manifest + curation + frame read —
+ `serve_curation` (`/api/run` + static), `inspect`, `preview`, run-dir `compose_gif`,
+ `compose_cycle`. They block only for the brief swap, then read a complete generation.
+ - **writer exclusion** via the run-dir single-writer lock (`acquire_run_dir_lock`) —
+ `compose_atlas`, `export_pngs`. They serialize with the extract writer, so they never overlap
+ a publish at all.
+ A consumer that only calls the manifest gate once but then reads the frame tree unguarded would
+ leave a TOCTOU window; the full read must be inside the strategy.
+- **Cross-process single-writer.** `.sprite-gen.lock` blocks a second **process** from writing
+ the same run dir; the pipeline's **one worker owns one character folder** rule (§2, SKILL.md)
+ is what excludes concurrent writers on the same run dir in the first place. Same-process
+ re-entry is intentionally allowed so one interpreter can run prepare → extract → compose in
+ sequence.
+
+What is **intentionally out of scope** for this local, single-user, re-runnable tool — and so
+not claimed here (a decision, not a deferral: maintainer 2026-07-12):
+
+- **Process-kill durability.** A hard `SIGKILL` *between* the commit's rename steps can leave a
+ new generation beside a stale `extract-failure.json` plus an orphan `.sg-backup`. This is **not
+ silent corruption**: the consistency gate (§6) catches the mixed state and fails loud, and a
+ re-run fixes it (the next extract's cleanup reconciles the leftover `.sg-backup` / `.sg-staging`).
+ A journal / self-heal replay protocol would auto-heal it instead, but that is database-grade
+ durability that a local sprite-curation tool does not need — observable-fail-loud + re-run is
+ the deliberate design. In-process rollback (above) still covers every raised-exception case.
+- **Thread-level write isolation.** `.sprite-gen.lock` re-entry is keyed per process, not per
+ thread. This is a **non-scenario** under the pipeline's one-worker-owns-one-folder rule (§2,
+ SKILL.md): concurrent writers on the same run dir are already excluded, and same-process
+ re-entry is the *intended* path for one interpreter to run prepare → extract → compose in
+ sequence. A thread-aware per-run mutex would only matter for a multi-threaded server host, which
+ is not this tool.
+
+Both are deliberate boundaries, not TODOs; §4/§6's atomicity claims are scoped to the in-process
+cases above and do not contradict this. If sprite-gen is ever re-homed as a multi-user or server
+service, revisit both here.
+
+## Related
+
+- [`../SKILL.md`](../SKILL.md) — behavior contract (Workflow, Base Lock Gate, Runtime Contract)
+- [`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/docs/seamless-video-loop.md b/docs/seamless-video-loop.md
new file mode 100644
index 0000000..bae2634
--- /dev/null
+++ b/docs/seamless-video-loop.md
@@ -0,0 +1,101 @@
+# Seamless Video Loop (ambient clip → infinite loop)
+
+Turn a **non-looping AI-generated ambient video clip** (an `sprite-gen gen` video, a
+Seedance/Veo/Kling i2v clip, a title/hero backdrop) into a clip that loops **forever with
+no visible seam** — for a title-screen background, a hero loop, a store-page ambient shot.
+
+Not to be confused with [`frame-interpolation.md`](frame-interpolation.md): that is a
+**generative** in-between for **sprite** frames (identity-preserving, RIFE deliberately
+retired there). This doc is **RIFE optical-flow interpolation** used to bridge a **video
+loop seam** — a different job, where RIFE's fluid morph is exactly right.
+
+## Why AI clips don't just loop
+
+An image-to-video model paints continuous, non-repeating motion. The last frame is never
+the first frame, and there is usually **no** pair of near-identical frames anywhere. So a
+raw loop cuts hard from the end state back to the start state and the eye catches a "pop".
+
+Common approaches that fail this contract:
+
+- **Crossfade the seam** — the dissolve is *visible as a fade in/out*. Rejected.
+- **Ping-pong / reverse** (`forward + reverse`) — mathematically seamless, but the motion
+ plays **backwards** for half the loop (embers fall, honey un-drips). Rejected.
+- **A model-native first/last-frame loop** — availability and endpoint guarantees vary by
+ provider, and equal endpoint images do not guarantee equal motion. Treat it as an input
+ clip, not proof that the seam is continuous.
+- **Trim to the best single-frame match** — halves the pop but still pops, because matching
+ two frames' *position* ignores their *motion* (see next section).
+
+## The pipeline
+
+Two stages: find the best **forward** loop segment numerically, then **bridge its seam**
+with RIFE so the wrap is continuous motion, not a cut or a fade.
+
+### 1. Find the loop segment — match flow, not two frames
+
+Extract frames (downscaled for speed), then over candidate cuts `(i, j)` minimise a cost
+that matches **both position and motion flow** at the seam. Position-only is not enough:
+these clips flicker, so `velocity[t] = |frame[t+1] - frame[t]|` **alternates every frame**;
+a cut that matches position but lands on the opposite flicker phase jumps in speed.
+
+```
+cost(i, j) = Σ_k w_k · D(frame[i+k], frame[j+k]) # windowed position match (flow shape)
+ + β · Σ_k w_k · |vel[i+k] - vel[j+k]| # windowed velocity match (phase/speed)
+```
+
+- `w_k` = small Gaussian window (radius ~3 frames) so the *trajectory around the seam*
+ matches, not just the boundary frame.
+- `β ≈ 5`. Without it the cut lands on a velocity mismatch (measured on t06: `|Δvel|` 0.28);
+ with it the velocities align (`|Δvel|` 0.04) with the same position quality.
+- Constrain `j - i ≥ minlen` (~2.5 s) so the loop isn't too short.
+
+The chosen segment is `frames[i .. j]`, trimmed hard from the full clip (`ffmpeg -ss i/fps
+-t (j-i)/fps`). Play it forward; the only remaining discontinuity is the wrap `j → i`.
+
+### 2. Bridge the seam with RIFE
+
+Interpolate the wrap `frame_j → frame_i` with **rife-ncnn-vulkan** (neural optical-flow
+frame interpolation) and append those in-between frames after the segment. The loop then
+plays forward, **morphs** `j → i` over the bridge as continuous motion, and wraps to `i`.
+No fade, no reverse.
+
+rife-ncnn-vulkan interpolates **one** midpoint per call, so recurse for N frames
+(depth 3 → 7 frames ≈ 0.29 s at 24 fps):
+
+```bash
+R="rife-ncnn-vulkan"; J=frame_j.png; I=frame_i.png
+"$R" -0 "$J" -1 "$I" -o m.png # 50%
+"$R" -0 "$J" -1 m.png -o q1.png ; "$R" -0 m.png -1 "$I" -o q3.png # 25% / 75%
+"$R" -0 "$J" -1 q1.png -o e1.png ; "$R" -0 q1.png -1 m.png -o e2.png
+"$R" -0 m.png -1 q3.png -o e3.png ; "$R" -0 q3.png -1 "$I" -o e4.png
+# append after the segment frames, in order: e1 q1 e2 m e3 q3 e4, then re-encode at the clip fps
+```
+
+`frame_i` itself is the loop's first frame, so the bridge stops at `e4` (just before `i`) —
+the wrap `e4 → i` is one more small RIFE step.
+
+## Verify with numbers, not one screenshot
+
+A single still cannot tell a playing loop from a paused first frame. Judge numerically:
+
+- **Loop seam**: output `first-vs-last` frame mean-abs-diff should drop (t06: hard cut 1.65
+ → RIFE bridge **0.87**). Frame-diff alone is necessary, not sufficient — the flow-match in
+ stage 1 is what removes the *velocity* jump the eye actually reads.
+- **Motion present**: `first-vs-mid` diff should stay high (a paused clip reads ~0).
+- To confirm a **built** player is actually *playing* (not showing a static fallback of the
+ same scene), capture two frames ~1.5 s apart and diff them — motion ⇒ the video plays.
+
+## Tools
+
+- **rife-ncnn-vulkan** (nihui, prebuilt macOS release) — runs on Apple Silicon via
+ Vulkan/MoltenVK (verified on M4 Max). Ships model sets (`rife-v4`, `rife-anime`, …);
+ the default is fine for fluid ambient motion.
+- **ffmpeg** — frame extract, trim, and re-encode. `minterpolate` (its built-in
+ motion-compensated interpolation) is a fallback but is block-based and fails on isolated
+ 2-frame pairs; prefer RIFE.
+
+## Runtime note
+
+For a game/app, ship the looped clips as the player's native codec and let the player loop
+(Unity `VideoPlayer.isLooping = true`, HTML `<video loop>`). Because the seam is already
+seamless in the file, the engine's plain loop needs no crossfade.
diff --git a/docs/sheet-slicing.md b/docs/sheet-slicing.md
new file mode 100644
index 0000000..4e40937
--- /dev/null
+++ b/docs/sheet-slicing.md
@@ -0,0 +1,93 @@
+# Sheet Slicing — multi-figure grid sheets to per-cell standing cuts (tachi-e)
+
+`slice_sheet_cells.py` (= `sprite_gen.cli slice-sheet`) turns ONE generated
+image containing a COLSxROWS grid of the same character (expressions, poses,
+outfits) into per-cell RGBA cuts on a fixed canvas with a shared feet
+baseline and a normalized subject height. Built for dialogue cut-in
+portraits (立ち絵); works for any "same subject, N variants in one sheet"
+generation.
+
+This is NOT the component-row animation pipeline. Rows animate one state
+over time; a sheet enumerates variants of one standing subject. Use
+`prepare`/`extract`/`compose-atlas` for animation, `slice-sheet` for
+variant sheets.
+
+## Alpha ownership
+
+Alpha truth is `sprite_gen.frames.extract.remove_chroma_background` — the same
+v1.13 4-pass chain the row pipeline uses (hard key cut → key-depth in-band
+unmix → soft-alpha unmix → trapped-spill despill). `slice-sheet` owns only
+cell geometry. Generate sheets on a chroma background chosen by the
+subject-color gate in image-gen's SKILL.md (pink/purple material → green
+key, green material → magenta key). Never generate variant sheets on a
+cream/white background and flood-fill them — background pockets trapped
+between props and legs survive as opaque bands, and light clothing is one
+tolerance away from being punched full of holes (2026-07-09 field
+accident, twice).
+
+## Usage
+
+```bash
+$SPRITE_GEN_ROOT/.venv/bin/python $SPRITE_GEN_ROOT/scripts/slice_sheet_cells.py \
+ --sheet raw/hero_expressions.png \
+ --out-dir portraits/hero \
+ --chroma-key green \
+ --grid 3x2 \
+ --names default,smile,sad,annoyed,angry,pleased \
+ --prefix hero_ \
+ --cell-width 512 --cell-height 768 \
+ --baseline-y 725 --target-height 645
+```
+
+- `--names` count must equal the grid cell count (reading order,
+ left-to-right then top-to-bottom). Omit for `cell-N` names.
+- `--target-height` is the character's canonical body height on the output
+ canvas. Keep one value per character across every sheet so a cast keeps
+ its height hierarchy.
+- Extraction tunables (`--key-threshold`, `--fringe-*`, `--spill-max-fraction`)
+ pass through to `remove_chroma_background` with the same defaults as
+ `extract`.
+
+## Geometry rules (and the field failures they encode)
+
+Each rule below exists because the naive version shipped a visible defect
+during the a cut-in overhaul (2026-07-09):
+
+1. **Component-to-cell assignment by centroid, not grid cropping.** Grid
+ cropping slices a figure's own cape/broom at the cell border and imports
+ the neighbour's overflow. Whole-sheet connected components go to the
+ cell containing their centroid, so a figure keeps everything attached
+ to it.
+2. **Merged-figure split + in-cell re-label.** Adjacent figures fused
+ through a touching prop (kunai tip into the next figure's hair) form one
+ sheet-wide component spanning cells. Pixels split at cell borders, then
+ connectivity is re-run *inside* each cell — without the re-label, the
+ neighbour's hair stays fused to the cell's own figure and ships as a
+ floating clothes/hair fragment.
+3. **Neighbour-debris rule.** After splitting, fragments that touch the
+ cell border and are far smaller than the cell's main figure
+ (`--debris-fraction`, default 0.30) are neighbour overhang — dropped.
+ Detached effects (hearts, sparkles, ZZZ) sit inside the cell and
+ survive.
+4. **Per-cell height normalization.** Generators routinely draw grid rows
+ at different sizes (one sheet shipped a top row ~40% taller than the
+ bottom row). Sheet-wide max-height scaling preserves that jitter; each
+ cell's main figure is scaled independently so every variant's body
+ height equals `--target-height`. Trade-off: a bowed pose (sleep) gets a
+ slightly larger body — runtime cut-in renderers assume one scale, so
+ asset-side height consistency wins.
+5. **Feet on the baseline.** The main figure's lowest pixel lands on
+ `--baseline-y`; effects above the head never shift the feet.
+6. **Fail loud on empty cells.** A cell with no subject after extraction
+ raises instead of writing a blank — a cropped or mis-gridded sheet must
+ be regenerated, not silently absorbed.
+
+## Prompting the sheet
+
+Ask for: exactly COLSxROWS figures, one full body per cell with head and
+feet fully inside the sheet (generators love cropping the top row's feet at
+the row boundary — say "shoe soles fully visible"), identical body size and
+feet line across cells, the flat chroma background, and no grid lines,
+labels, or numbers. Two-arm/anatomy constraints belong in the prompt too:
+the slicer cannot repair a three-armed generation, only regeneration fixes
+bad drawing (same doctrine as the row pipeline).
diff --git a/docs/states-and-frames.md b/docs/states-and-frames.md
new file mode 100644
index 0000000..aaea642
--- /dev/null
+++ b/docs/states-and-frames.md
@@ -0,0 +1,73 @@
+# States & Frame Counts — sprite-gen reference
+
+> `SKILL.md` 허브에서 분리한 시나리오 상세. 요청할 상태(state) 목록과 프레임 수를 정할 때 이 문서를 따른다.
+
+## Simple MVP Scope
+
+The default user promise is deliberately simple:
+
+> A Codex user installs this skill, provides a character/base image and one or more simple actions, then receives a sprite sheet, GIF preview, and QA notes.
+
+Do not frame the default path as game-ready humanoid locomotion. The current Codex/image-gen path is good at short readable pose changes, identity-preserving rows, chroma cleanup, atlas composition, and QA. It is not yet reliable enough to promise precise cyclic locomotion for humanoids.
+
+Default/simple states:
+
+- `idle` — stable default. Use 4 frames, loop true.
+- `jump` — stable default as a short non-loop action. Use 4 frames, loop false.
+- `attack` — stable default as a short non-loop action. Use 4 frames, loop false.
+- `wave` — simple gesture, but only stable as non-loop unless the row includes a return-to-idle frame. Use 4 frames, loop false by default; use 5 frames only when the final frame intentionally returns near frame 1.
+- `talk`, `blink`, `bounce`, `hurt`, `celebrate`, `magic_cast` — allowed simple candidates, but still require motion QA before pass.
+
+Experimental states:
+
+- `walk`, `run`, `frontwalk`, `45_frontwalk`, and other cyclic locomotion.
+- Directional cycles that require exact foot-contact alternation or phase symmetry.
+- Any state where the user needs game-ready locomotion rather than a readable preview animation.
+
+For experimental states, report them as experimental in `qa-notes.md` unless motion QA passes. Never silently promote a weak walk/run row to the same status as simple MVP output.
+
+## Quick Path For Simple Animations
+
+When the user asks for "simple sprite animation", prefer this request shape unless they specify otherwise:
+
+```json
+{
+ "states": {
+ "idle": { "frames": 4, "fps": 4, "loop": true, "action": "subtle breathing and one blink" },
+ "attack": { "frames": 4, "fps": 8, "loop": false, "action": "simple windup, strike, recovery attack pose sequence with no detached effects" },
+ "jump": { "frames": 4, "fps": 8, "loop": false, "action": "simple jump arc: crouch, takeoff, airborne, landing" }
+ }
+}
+```
+
+Add `wave` only as a non-loop gesture by default:
+
+```json
+"wave": { "frames": 4, "fps": 6, "loop": false, "action": "friendly hand wave gesture; arm changes clearly while feet stay planted" }
+```
+
+Simple MVP pass requires:
+
+- automated extraction and atlas reports pass
+- `qa/<state>.gif` reads as the requested simple action
+- loop seam passes for looped states
+- non-loop states have clear start/middle/end pose progression
+- `qa-notes.md` records `pass`, `best-effort`, or `experimental` per state
+
+## Frame Count Guidance
+
+Keep default simple actions short. More frames do not automatically create smoother animation in the current component-row image generation path:
+
+- `4` frames is the default stable range for simple actions.
+- `5` frames is acceptable when a non-loop gesture needs a return-to-idle pose.
+- `6` frames is the conservative upper edge for simple humanoid one-shot defaults.
+- `8` frames is hatch-pet-style advanced territory, not forbidden. Use it for compact mascots, locomotion rows, or explicit experiments only when extraction/motion QA passes.
+- `9` and `12` frames are **not** default simple settings. In validation runs, they increased duplicate bodies, empty/sparse frames, slot collapse, and extraction failure before adding useful in-betweens.
+
+If a user asks for 9 or 12 frames, run it as an explicit experiment and report `duplicate-heavy`, `blur/merge`, or `extract-fail` honestly instead of treating it as a normal pass.
+
+## Related
+
+- [`../SKILL.md`](../SKILL.md) — canonical behavior contract
+- [`directional-anchor-workflow.md`](directional-anchor-workflow.md) — 방향성/45도/locomotion 상태의 앵커 체인
+- [`qa-motion.md`](qa-motion.md) — motion continuity 판정 기준
diff --git a/docs/static-pose-recipe.md b/docs/static-pose-recipe.md
new file mode 100644
index 0000000..e9d2a1e
--- /dev/null
+++ b/docs/static-pose-recipe.md
@@ -0,0 +1,55 @@
+# 정지 자세(Static-Pose) 행 레시피
+
+합성 정지 자세 회귀에서 도출한 결정론적 레시피다.
+
+## 적용 대상
+
+이동/액션이 아닌 모든 "가만히 있는" 상태: `idle`, `sit`, `sit_chair`, `lie`,
+`carry_idle` 등. 로코모션(walk/run/jump)과 action 행에는 적용하지 않는다.
+
+## 레시피
+
+1. **정지 1컷 + 링크 복제**: 추출 프레임 중 최적 정지 포즈 1장을 고르고
+ (사람 검수 대상; 기본 후보 frame 0), 나머지 시퀀스는 전부 그 프레임의
+ **링크 복제**로 채운다 — 편집 truth 1곳, 아틀라스 셀 공유(무비용).
+2. **길이 = 호흡당 최소 프레임 확보** @ 4fps. 시퀀스 길이는
+ `sprite_gen/effects/breathe.py` `recommended_breathe_frames(breathe)` 로 정한다
+ (호흡당 `SMOOTH_CYCLE_FRAMES`=6 프레임): 기본 `breaths: 3` → **18컷**
+ (~4.5s 루프, 호흡당 1.5s). **옛 11컷은 사이클당 ~3.7프레임이라 1px 위상이
+ 거의 매 프레임 토글해 호흡이 아니라 진동으로 읽힌다**. 이 게이트가 그 원인을 막는다. 깜빡임 프레임은 이 길이에
+ 포함되며 별도로 +하지 않는다 (아래 4).
+3. **호흡 레이어**: `breathe = {depth: 0.06, breaths: 3, lag: 0.1}` 만 쓴다.
+ **강체 경계는 선언하지 않는다** — `sprite_gen/effects/anatomy.py` 가 목 병목(없으면 대칭
+ 눈쌍 아래, 그것도 없으면 어깨-기울기)으로 검출해 사이드카 `anatomy` 에 채운다.
+ **굽기는 그 값을 캐시로만 본다** — 매번 자기 기준 프레임에서 다시 재고, 사이드카와
+ 어긋나면 manifest 의 `sidecar_drift` 로 값을 실어 보고한다. 사이드카의 `anatomy` 는
+ 큐레이터 미리보기가 굽기와 같은 경계로 그리려고 들고 있는 것이고, 그게 아직 유효한지는
+ `fingerprint`(기준 프레임의 **입력** 키 — `breathe.reference_key`)로 판정한다.
+ 특정 행에 고정해야 할 때만 `rigid_row`.
+ 위상이 연속값이라 이징을 위한 별도 옵션이 없다 — 부드러움은 프레임 수(위 2)로 얻는다.
+4. **깜빡임은 눈이 보이는 방향만**: 시퀀스 **끝 근처**(맨 끝 아님)에 배치하고
+ 뒤에 눈-뜬 rest 프레임을 **최소 2장** 남긴다 — 그래야 감았다가 루프 이음새
+ 전에 다시 뜨며 이어진다 (맨 끝 1프레임이면 감은 채로 끝나 다음 루프 첫
+ 프레임에서 확 떠 스냅난다). 감은-눈은 rest 위상 프레임에
+ 얹어 몸통은 그대로 두고 눈만 바뀌게 한다.
+ - 정면(down): 독립(unlink) 복제 2장에 감은-눈 픽셀 ops (open→closed→open
+ 읽히게), 뒤에 rest 프레임 ≥2.
+ - 옆(side): 동일 (독립 복제 감은-눈 + 뒤 rest ≥2).
+ - 뒤(up): 깜빡임 없음.
+ 감은-눈 픽셀은 **사람이 깎는다** — 자세마다 눈 위치가 달라 자동 이식
+ 금지 (포즈별 눈 좌표가 다르면 눈이 엉뚱한 데 감긴다).
+5. **변형/픽셀 편집은 정지 원본 프레임에만** — 복제는 링크 동기화로 따라온다.
+
+## 자동 적용 절차 (에이전트)
+
+새 정지 자세 행이 추출되면 (큐레이션 없음 전제):
+
+1. `curation.json` `states.<state>` 에: `selected=[still]`,
+ `order=[still]+클론N`, `clones={새 idx: still}` (링크 기본 — 편집 복사 금지),
+ breathe 위 레시피. **N = `recommended_breathe_frames(breathe) − 1`** (정지
+ 원본 1장 제외; 기본 breaths 3 → 17 클론 → 총 18컷). 링크 복제라 아틀라스
+ 셀은 안 늘어난다 — 호흡 위상당 유니크 셀만 굽는다. 18컷 `breaths: 3` 이면 유니크 칸 6개(위상이 6종만 반복).
+2. fps 4 를 `sprite-request.json` 해당 상태에 기록.
+3. 깜빡임(정면/옆)은 자동 생성하지 않는다 — "깜빡임 추가 대기" 로 보고하고
+ 사람이 정지 프레임 확정 후 눈을 깎는다.
+4. 열린 큐레이션 탭이 있으면 두-작성자 충돌 방지를 위해 새로고침을 안내한다.
diff --git a/docs/subject-profiles.md b/docs/subject-profiles.md
new file mode 100644
index 0000000..18070b7
--- /dev/null
+++ b/docs/subject-profiles.md
@@ -0,0 +1,65 @@
+# Subject profiles - character vs effect
+
+The sparse-frame floor (`--min-used-pixels`) catches empty frames and extraction debris. The right floor depends on what a run draws and on its cell geometry. A character normally fills more of its cell than a spell spark, while users may choose any resolution, so neither profile owns one absolute pixel constant.
+
+```jsonc
+// sprite-request.json
+{ "subject": "effect" } // omit the field for the default character profile
+```
+
+```bash
+sprite-gen prepare --subject effect ...
+```
+
+```text
+equivalent_side = ceil(sqrt(cell_width * cell_height))
+
+character floor = equivalent_side
+effect floor = ceil(equivalent_side / 2)
+```
+
+The geometric mean gives rectangular cells one equivalent side without making either axis canonical. Scaling both axes by `k` scales the floor by `k`, not `k^2`: this guard protects a minimum readable linear footprint instead of imposing one coverage percentage at every resolution. Safe margins are excluded because integer margin rounding could make the floor decrease when a cell grows.
+
+| cell | character | effect |
+|---|---:|---:|
+| 16x16 | 16 | 8 |
+| 32x32 | 32 | 16 |
+| 64x64 | 64 | 32 |
+| 128x128 | 128 | 64 |
+| 256x256 | 256 | 128 |
+| 192x208 | 200 | 100 |
+
+An explicit `--min-used-pixels` always wins. Explicit values are stamped into `extract_args` so heal reproduces them exactly. Profile-derived values are not stamped because frames are a cache of raw input, request, and engine; changing `subject` must re-resolve the formula on heal.
+
+## Synthetic boundary battery
+
+The repository verifies the profile with generated solid-shape strips rather than private production data.
+
+| opaque px/frame at 64x64 | character | effect |
+|---|---|---|
+| 16 | fail | fail |
+| about 36 | fail | pass |
+| 64 and above | pass | pass |
+
+The same tests sweep every square cell size from 16 through 512, rectangular cells, monotonic growth on either axis, unknown subject rejection, explicit overrides, heal behavior, and compose behavior.
+
+## End-to-end public gallery
+
+These public examples were generated through `prepare --subject effect`, `gen`, `extract`, and `compose-atlas` without a floor override.
+
+<p align="center">
+ <img src="assets/subject-effect-ember.gif" width="72" alt="ember burst" />
+ <img src="assets/subject-effect-venom.gif" width="72" alt="venom orb" />
+ <img src="assets/subject-effect-sigil.gif" width="72" alt="spark sigil" />
+ <img src="assets/subject-effect-wisp.gif" width="72" alt="wisp flame" />
+</p>
+
+![subject-profile effect gallery](assets/subject-effects-gallery.png)
+
+## Practices
+
+- Declare `subject` in the request. The request is the run's SSoT and travels with heal, curation, and later maintainers.
+- Read `frames-manifest.json` whenever extraction reports `ok: false`; it records each rejected frame and measured count.
+- Use `--min-used-pixels` only for a deliberate outlier below the derived profile floor.
+- Keep chroma-key hues far from wispy or translucent effect colors so unmixing does not erase the subject into the debris band.
+- Do not lower a global floor for every run. That would disable the debris guard for unrelated subjects.
diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md
new file mode 100644
index 0000000..6b5ed58
--- /dev/null
+++ b/docs/troubleshooting.md
@@ -0,0 +1,54 @@
+# Troubleshooting
+
+파이프라인이 "조용히 이상한" 대표 증상들과 원인·대처. 전부 회귀에서 도출.
+(엔진은 특정 오케스트레이터를 모른다 — 여기의 규칙은 어떤 에이전트 환경에서든 성립.)
+
+## 사이드카(curation.json)를 에이전트가 직접 쓸 때 — 스테일 가드에 드랍됨
+
+- **증상**: 에이전트가 `curation.json` 에 쓴 상태 항목이 compose/뷰에 반영되지
+ 않고, `curation.stale-*.json` 백업이 생기며 항목이 사라진다.
+- **원인**: 사이드카는 세대 도장(`run_revision` + 행별 `revision`)으로 보호된다.
+ 재추출로 런 세대가 바뀐 뒤 도장 없이 raw JSON 을 직접 쓰면, 로더가 "재생성
+ 이전의 낡은 항목"으로 판정해 드랍한다 (per-state salvage — 의도된 방어).
+- **대처**: 에이전트 쓰기는 반드시 정식 경로로 —
+ `sprite_gen.curate.curation.load_curation(run_dir)` 로 읽고 수정한 뒤
+ `stamp_curation(run_dir, payload)` 를 거쳐 저장한다. 웹뷰 API(`/api/curation`)를
+ 쓰면 서버가 도장을 찍는다.
+
+## 열린 큐레이션 탭 + 에이전트 동시 쓰기 (두-작성자 충돌)
+
+- **증상**: 에이전트가 사이드카에 쓴 값이 곧 사라진다.
+- **원인**: 열린 브라우저 탭은 자기 메모리 상태를 디바운스 저장한다 — 에이전트의
+ 디스크 쓰기를 모른 채 덮어쓴다.
+- **대처**: 에이전트가 사이드카를 만진 뒤엔 탭을 새로고침시키라고 안내한다.
+ (서버는 run_revision/HTTP-409 로 세대 충돌만 막는다 — 같은 세대 안의 두-작성자는
+ 마지막 저장이 이긴다.)
+
+## 생성 provider CLI 무출력 행 (auth 정상인데 몇 분째 침묵)
+
+- **증상**: `sprite-gen gen` 자식(provider CLI)이 출력 없이 멈춘다. 인증도 정상.
+- **원인(회귀)**: 에이전트 세션 안에서 스폰된 자식 CLI 가 부모 오케스트레이터의
+ 세션 신분 env 를 상속하면, 오케스트레이터의 훅이 자식을 멤버로 착각해 턴 종료를
+ 차단할 수 있다. 엔진은 `provider_subprocess_env()` 로 알려진 오케스트레이터 env
+ 접두어 가족을 전부 벗겨 자식을 깨끗한 독립 프로세스로 스폰한다 (근본 수리는
+ 해당 오케스트레이터 훅 소유).
+- **대처**: provider 를 엔진 스크립트를 **거치지 않고** 직접 spawn 하는 커스텀
+ 코드를 짰다면 같은 원칙을 적용하라. 진단은 짧은 텍스트 프로브(`codex exec` 에
+ "PONG" 한 줄, 60s 타임아웃)로 — env 상속/스크럽 두 케이스를 비교하면 즉시 갈린다.
+
+## 행 스트립이 세로로 생성됨 → 추출이 빈/희소 프레임으로 전멸
+
+- **증상**: 추출 리포트에 특정 행들이 `empty or too sparse`, `could not extract N
+ components` 로 몰리고 (fail-loud 라 프레임은 미발행), raw 를 보면 가로 스트립이
+ 아니라 **세로/단일 대형** 이미지다.
+- **원인**: provider 가 레이아웃 가이드의 가로 슬롯 배치를 무시함 (grok 로코모션
+ 행에서 관측).
+- **대처**: 해당 행만 재생성 — 가이드 준수가 강한 provider(codex)로 바꾸거나
+ 프롬프트의 슬롯/가로폭 계약을 강조. 로컬에서 자르거나 회전시켜 살리지 않는다
+ (필수 게이트: raw 수리 금지).
+
+## 비교 캔버스 WebM/MP4 저장이 500
+
+- **원인**: WebM/MP4 조립은 서버 머신의 `ffmpeg` 를 쓴다 — 없으면 관측 가능한
+ 500(`ffmpeg not found`)을 준다. GIF 는 ffmpeg 없이 동작.
+- **대처**: 서버 머신에 ffmpeg 설치 (`brew install ffmpeg` 등).
diff --git a/pyproject.toml b/pyproject.toml
new file mode 100644
index 0000000..f697ed6
--- /dev/null
+++ b/pyproject.toml
@@ -0,0 +1,99 @@
+# SPDX-License-Identifier: Apache-2.0
+[build-system]
+# 77, not 68: `license = "Apache-2.0"` below is the PEP 639 string form, which older
+# setuptools rejects outright — measured, backend called directly, this very tree:
+# 76.1.0 dies with "`project.license` must be valid exactly by one definition", 77.0.1
+# builds. Nobody hit it because pip's build isolation always fetches the newest setuptools,
+# but the floor was a claim about a build that could not happen.
+requires = ["setuptools>=77"]
+build-backend = "setuptools.build_meta"
+
+[project]
+name = "sprite-gen"
+# Release discipline: keep this package metadata version synchronized with
+# SKILL.md's `version:` field in the same release commit.
+version = "1.59.0"
+description = "Component-row pipeline for clean 2D game sprites and animation atlases"
+readme = "README.md"
+license = "Apache-2.0"
+requires-python = ">=3.10"
+dependencies = [
+ "pillow>=12.0,<13",
+ # NumPy is a direct dependency, never a transitive ride-along: the chroma
+ # extraction path imports it directly and must not depend on some other
+ # package happening to pull it in.
+ # Floor 2.2.6 is the newest release with CPython 3.10 wheels, so it is the
+ # highest floor that keeps `requires-python = ">=3.10"` honest (2.3.x
+ # requires >=3.11, 2.5.x requires >=3.12 — either would break the 3.10 CI
+ # job outright). It is also >= 2.0, which matters: the byte-identity
+ # contract for the extraction path depends on NEP 50 promotion rules, which
+ # only became the default in NumPy 2.0. The `<3` ceiling is there for the
+ # same reason — a major bump is free to change promotion again.
+ "numpy>=2.2.6,<3",
+]
+
+[project.optional-dependencies]
+dev = [
+ "pytest>=8.0",
+ # The packaging guard builds a wheel and reads what is inside it, because the declarations
+ # below are a claim and only the build is the fact. That needs the declared build backend
+ # importable in the test environment — build isolation puts it somewhere the tests cannot
+ # see, and a modern `python -m venv` no longer provides it. Same floor as build-system.
+ "setuptools>=77",
+ # Many tests shell out to a pipeline step as a subprocess; a wrong path or a
+ # server that never returns would otherwise hang the whole suite silently.
+ # A per-test timeout turns that into a named failure. `signal` method (below)
+ # is required — the default `thread` method cannot interrupt a blocked
+ # subprocess.wait(), which is exactly the case that hangs here.
+ "pytest-timeout>=2.3",
+]
+
+# The console script is what removes the "which python?" question: pip writes it
+# with a shebang naming the interpreter of the environment it was installed
+# into, so `sprite-gen <tool>` runs on that environment's dependencies without
+# anyone naming an interpreter. It fronts the same parser as
+# `python -m sprite_gen.cli`, so the two forms cannot drift.
+[project.scripts]
+sprite-gen = "sprite_gen.cli:main"
+
+[project.urls]
+Repository = "https://github.com/aldegad/sprite-gen"
+
+[tool.pytest.ini_options]
+testpaths = ["tests"]
+# Tests are grouped into per-domain folders (tests/<domain>/) so a domain can be
+# run alone (`pytest tests/effects`). conftest.py stays at the tests/ root and is
+# imported by name (`from conftest import run_script`) from every subfolder, so the
+# tests/ dir must be on sys.path.
+pythonpath = ["tests"]
+# A hung subprocess test must become a named failure, not a silent stall. signal
+# method (SIGALRM) is required — thread method cannot interrupt a blocked
+# subprocess.wait(). 120s is generous for the extract/compose subprocess tests.
+timeout = 120
+timeout_method = "signal"
+
+# The pipeline ships an importable sprite_gen package. The canonical invocation is the
+# console script declared above (`sprite-gen <tool>`); `scripts/<tool>.py` survives as a
+# backwards-compatible wrapper for callers that already name the file, and it is a wrapper
+# only — never the form docs teach, because a bare `python3` in a shell that never activated
+# the venv is a different interpreter than the one holding this file's dependencies
+# (`tests/test_entrypoint_interpreter.py` locks that rule for SKILL.md and docs/).
+#
+# Discovered, not hand-listed: a literal `packages = ["sprite_gen"]` silently dropped the
+# `sprite_gen.gen` subpackage from every built wheel, so `sprite-gen --help` (cli.py imports
+# `gen` at module scope) died on a non-editable install. The filesystem is the truth about
+# which packages exist; this derives from it so a new subpackage cannot go missing again.
+[tool.setuptools.packages.find]
+include = ["sprite_gen*"]
+
+# The curation SPA is package data, not a repo-side script asset: the server resolves it
+# relative to its own module (serve_curation.CURATOR_DIR), so it has to travel inside the
+# wheel or the installed console script serves a 404 shell. One location, no fallback.
+#
+# Whole subtree, not an extension list: setuptools expands these with glob(recursive=True),
+# where a single `*` stops at a directory boundary. A hand-listed `curator/src/*.js` therefore
+# drops `curator/src/<anything>/*.js` from the wheel the day someone nests a folder — measured,
+# not feared: adding curator/src/deep/new.js under the old patterns built a wheel without it.
+# `curator/**/*` derives the answer from the filesystem, the same fix as packages.find above.
+[tool.setuptools.package-data]
+sprite_gen = ["serve/curator/**/*", "serve/composer/**/*"]
diff --git a/scripts/breathe_mutation_battery.py b/scripts/breathe_mutation_battery.py
new file mode 100644
index 0000000..c8883fb
--- /dev/null
+++ b/scripts/breathe_mutation_battery.py
@@ -0,0 +1,213 @@
+"""호흡 계약 변이 배터리 — 그물을 손대면 **전부** 다시 돌린다.
+
+ python scripts/breathe_mutation_battery.py
+
+각 항목은 "이 계약이 깨지면 어떤 코드가 되는가" 를 소스에 잠깐 심고, 그물이 실제로
+무는지(테스트가 FAIL 하는지) 확인한 뒤 되돌린다. 전부 물어야 exit 0 이다.
+
+**왜 스크립트인가.** 검증 라운드 두 번이 같은 형태로 기각됐다: 그물을 고치면서 "새
+변이를 무는가" 만 보고 "원래 잡던 걸 여전히 잡는가" 를 안 물었다. 두 번 다 그물 자신의
+개선(전이 추적 / 선언 추적)이 새 탈출구를 열었다. 배터리로 묶어 그 선택지를 없앤다 —
+그물을 바꾸면 이걸 돌리고, 새 계약을 세우면 여기에 줄을 추가한다.
+
+**범위** (maintainer 결정 2026-07-26): 여기 있는 변이는 **실제로 있었던 회귀**를 재현한다.
+"이렇게 쓰면 그물이 못 잡는다" 는 가상 우회는 추가하지 않는다 — 정규식으로 데이터플로를
+근사하는 한 그런 축은 무한히 나오고, 그걸 좇는 것은 수렴하지 않는다는 것이 열 라운드로
+확인됐다. 소스 스캐너의 한계는 `tests/test_breathe_off_state.py` 모듈 docstring 참조.
+"""
+import os
+import pathlib
+import subprocess
+import sys
+
+REPO = pathlib.Path(__file__).resolve().parent.parent
+PY = os.environ.get("PYTEST_PYTHON", sys.executable)
+
+# 소스를 잠깐 망가뜨렸다 되돌린다 — 남의 변경 위에서 돌리면 복구가 그 변경을 덮는다.
+dirty = subprocess.run(["git", "-C", str(REPO), "status", "--porcelain"],
+ capture_output=True, text=True).stdout.strip()
+if dirty and not os.environ.get("BATTERY_ALLOW_DIRTY"):
+ print("작업트리가 clean 이 아니다 — 변이 복구가 그 변경을 덮을 수 있다.\n"
+ "커밋하거나 stash 한 뒤 다시 돌려라 (강행: BATTERY_ALLOW_DIRTY=1).")
+ print(dirty)
+ sys.exit(2)
+os.chdir(REPO)
+
+# 각 항목: (설명, [(파일, 옛 문자열, 새 문자열), ...])
+# 편집을 **묶을 수 있어야 한다** — "이름을 바꾸고 폴백을 되살린다" 처럼 두 곳을 동시에
+# 건드리는 회귀가 실제 탈출구였다 (노을이 탈출 E, 2026-07-26).
+MUTS = [
+ ("N1 isfinite 게이트 제거", "sprite_gen/spec/migrate_breathe.py",
+ "integral = math.isfinite(raw_breaths) and raw_breaths == int(raw_breaths)",
+ "integral = raw_breaths == int(raw_breaths)"),
+ ("N2 변형 생략", "sprite_gen/serve/serve_curation.py",
+ "return apply_transform(source, transforms.get(edit_idx), cell, snap_scale=snap), key",
+ "return source, key"),
+ ("N2 재생순서 무시", "sprite_gen/serve/serve_curation.py",
+ " for index in (ordered or list(range(total))):",
+ " for index in list(range(total)):"),
+ ("N2 픽셀편집 생략", "sprite_gen/serve/serve_curation.py",
+ ' source = apply_pixel_edits(opened.convert("RGBA"), ops)',
+ ' source = opened.convert("RGBA")'),
+ ("N2 스냅 무시", "sprite_gen/serve/serve_curation.py",
+ ' snap = pixel_snap_scale(request) if variant == "pixel" else None',
+ " snap = None"),
+ ("N3 캐노니컬 폴백", "sprite_gen/serve/curator/src/store.js",
+ "return { url: frame.plainBakeUrl || null, stamp: frame.plainBakeStamp || null };",
+ "return { url: frame.plainBakeUrl || frame.url, stamp: frame.plainBakeStamp || frame.stamp || null };"),
+ ("N4 키없음 통과", "sprite_gen/serve/curator/src/breathe.js",
+ ' throw new BreatheRefused("기준 프레임 키를 만들 수 없다 — 신선도 확인 불가.");',
+ " return;"),
+ ("N5 직접 폴백", "sprite_gen/serve/curator/src/cards.js",
+ " drawFrameInto(baseCtx, canonical,",
+ " drawFrameInto(baseCtx, (canonical && canonical.complete) ? canonical : image,"),
+ ("N5 표시 URL 출처", "sprite_gen/serve/curator/src/cards.js",
+ " const canonSrc = f && bakeFrameUrl(state.name, f);",
+ " const canonSrc = f && frameUrl(state.name, f);"),
+ ("N5 탈출 C: 변수 추출", "sprite_gen/serve/curator/src/cards.js",
+ " const canonical = canonSrc ? img(canonSrc) : null;\n if (!(canonical && canonical.complete && canonical.naturalWidth)) {",
+ " const canonImg = canonSrc ? img(canonSrc) : null;\n const canonical = (canonImg && canonImg.complete && canonImg.naturalWidth) ? canonImg : image;\n if (false) {"),
+ ("N5 탈출 D: let + 재대입", "sprite_gen/serve/curator/src/cards.js",
+ " const canonical = canonSrc ? img(canonSrc) : null;\n if (!(canonical && canonical.complete && canonical.naturalWidth)) {",
+ " let canonical = canonSrc ? img(canonSrc) : null;\n if (!(canonical && canonical.complete && canonical.naturalWidth)) canonical = image;\n if (false) {"),
+ ("N5 탈출 E: ctx 리네임 + 폴백 복원", [
+ ("sprite_gen/serve/curator/src/cards.js",
+ ' const baseCtx = base.getContext("2d");',
+ ' const warpCtx = base.getContext("2d");'),
+ ("sprite_gen/serve/curator/src/cards.js",
+ " baseCtx.imageSmoothingEnabled = false;",
+ " warpCtx.imageSmoothingEnabled = false;"),
+ ("sprite_gen/serve/curator/src/cards.js",
+ " drawFrameInto(baseCtx, canonical,",
+ " drawFrameInto(warpCtx, (canonical && canonical.complete && canonical.naturalWidth) ? canonical : image,"),
+ ]),
+ ("N5 탈출 F: 한 인자 헬퍼에 폴백 은닉", [
+ ("sprite_gen/serve/curator/src/cards.js",
+ " const canonical = canonSrc ? img(canonSrc) : null;\n"
+ " if (!(canonical && canonical.complete && canonical.naturalWidth)) {",
+ " const canonImg = canonSrc ? img(canonSrc) : null;\n"
+ " const readyOr = (c) => (c && c.complete && c.naturalWidth) ? c : image;\n"
+ " const canonical = readyOr(canonImg);\n"
+ " if (false) {"),
+ ]),
+ ("N5 탈출 G: 굽기 소스를 인자로 품은 호출", [
+ ("sprite_gen/serve/curator/src/cards.js",
+ " const canonSrc = f && bakeFrameUrl(state.name, f);\n"
+ " const canonical = canonSrc ? img(canonSrc) : null;\n"
+ " if (!(canonical && canonical.complete && canonical.naturalWidth)) {",
+ " const pick = (u, alt) => { const i = u && img(u); "
+ "return (i && i.complete && i.naturalWidth) ? i : alt; };\n"
+ " const canonical = pick(f && bakeFrameUrl(state.name, f), image);\n"
+ " if (false) {"),
+ ]),
+ ("N5 탈출 H1: drawFrameInto 별칭 + 폴백", [
+ ("sprite_gen/serve/curator/src/zoom-editor.js", ' const b = document.createElement("canvas");\n b.width = cellW;\n b.height = cellH;\n const bx = b.getContext("2d");\n bx.imageSmoothingEnabled = false;\n drawFrameInto(bx, image, getTransform(stateName, frameIdx), cellW, cellH,\n snapScaleFor(stateName), getPixelOps(stateName, frameIdx));', ' const b = document.createElement("canvas");\n b.width = cellW;\n b.height = cellH;\n const bx = b.getContext("2d");\n bx.imageSmoothingEnabled = false;\n const paint = drawFrameInto;\n paint(bx, (image && image.complete && image.naturalWidth) ? image : img(frameUrl(stateName, f)), getTransform(stateName, frameIdx), cellW, cellH,\n snapScaleFor(stateName), getPixelOps(stateName, frameIdx));'),
+ ]),
+ ("N5 탈출 H1b: ctx 바인딩을 헬퍼로 묶기 + 폴백", [
+ ("sprite_gen/serve/curator/src/zoom-editor.js", ' const b = document.createElement("canvas");\n b.width = cellW;\n b.height = cellH;\n const bx = b.getContext("2d");\n bx.imageSmoothingEnabled = false;\n drawFrameInto(bx, image, getTransform(stateName, frameIdx), cellW, cellH,\n snapScaleFor(stateName), getPixelOps(stateName, frameIdx));', ' const makeCell = (w, h) => { const c = document.createElement("canvas"); c.width = w; c.height = h;\n const x = c.getContext("2d"); x.imageSmoothingEnabled = false; return { canvas: c, ctx: x }; };\n const { canvas: b, ctx: bx } = makeCell(cellW, cellH);\n drawFrameInto(bx, (image && image.complete && image.naturalWidth) ? image : img(frameUrl(stateName, f)), getTransform(stateName, frameIdx), cellW, cellH,\n snapScaleFor(stateName), getPixelOps(stateName, frameIdx));'),
+ ]),
+ ("N5 탈출 I: || 폴백을 img 인자 안에", [
+ ("sprite_gen/serve/curator/src/zoom-editor.js", ' const canonImg = refUrl ? img(refUrl) : null;',
+ " const refFrame = frameOf(stateName, refIdx);\n"
+ " const canonImg = img(refUrl || frameUrl(stateName, refFrame));"),
+ ]),
+ ("N5 탈출 I2: 삼항 else 가 표시 파일", [
+ ("sprite_gen/serve/curator/src/zoom-editor.js", ' const canonImg = refUrl ? img(refUrl) : null;',
+ " const refFrame = frameOf(stateName, refIdx);\n"
+ " const canonImg = refUrl ? img(refUrl) : img(frameUrl(stateName, refFrame));"),
+ ]),
+ ("N5 탈출 J: 줄바꿈으로 분기 숨기기", [
+ ("sprite_gen/serve/curator/src/cards.js", ' const canonical = canonSrc ? img(canonSrc) : null;\n if (!(canonical && canonical.complete && canonical.naturalWidth)) {',
+ " const canonImg = canonSrc ? img(canonSrc) : null;\n"
+ " const canonical = (canonImg && canonImg.complete && canonImg.naturalWidth)\n"
+ " ? canonImg\n"
+ " : image;\n"
+ " if (false) {"),
+ ]),
+ ("N5 탈출 J2: || 폴백을 다음 줄로", [
+ ("sprite_gen/serve/curator/src/zoom-editor.js", ' const canonImg = refUrl ? img(refUrl) : null;',
+ " const refFrame = frameOf(stateName, refIdx);\n"
+ " const canonImg = (refUrl && img(refUrl))\n"
+ " || img(frameUrl(stateName, refFrame));"),
+ ]),
+ ("N5 탈출 K: 줄바꿈으로 프리뷰 사이트 증발 + 기준 인자 제거", [
+ ("sprite_gen/serve/curator/src/zoom-editor.js", ' bctx.drawImage(bm.enabled ? breatheComposeForPreview(base, bm.cfg, phase, breatheRef()) : base, 0, 0);',
+ " bctx.drawImage(bm.enabled ? breatheComposeForPreview(base, bm.cfg,\n"
+ " phase) : base, 0, 0);"),
+ ]),
+ ("N5 탈출 L: 내보내기 플러밍을 공용 헬퍼로 + 게이트 제거", [
+ # 흔한 DRY 리팩토링 — compare 와 row-export 가 `/api/compare-gif` POST 를 중복한다.
+ ("sprite_gen/serve/curator/src/util.js",
+ "const IDENTITY = () => ({ rotate: 0, scale: 1, dx: 0, dy: 0, shx: 0, shy: 0, flipX: 0 });",
+ "const IDENTITY = () => ({ rotate: 0, scale: 1, dx: 0, dy: 0, shx: 0, shy: 0, flipX: 0 });\n"
+ "const snapshotPng = (c) => c.toDataURL(\"image/png\");\n"
+ "const postFramesForAssembly = (body) => fetch(\"/api/compare-gif\", "
+ "{ method: \"POST\", headers: { \"Content-Type\": \"application/json\" }, "
+ "body: JSON.stringify(body) });"),
+ ("sprite_gen/serve/curator/src/compare.js",
+ ' frames.push(canvas.toDataURL("image/png"));',
+ " frames.push(snapshotPng(canvas));"),
+ ("sprite_gen/serve/curator/src/compare.js",
+ ' const res = await fetch("/api/compare-gif", {\n'
+ " method: \"POST\",\n"
+ ' headers: { "Content-Type": "application/json" },\n'
+ " body: JSON.stringify({ frames, duration_ms: step, format: fmt }),\n"
+ " });",
+ " const res = await postFramesForAssembly({ frames, duration_ms: step, format: fmt });"),
+ ("sprite_gen/serve/curator/src/compare.js",
+ " const resampled = [];",
+ " const resampled = []; if (false)"),
+ ]),
+ ("N5 탈출 M: ?? 폴백 (cards)", "sprite_gen/serve/curator/src/cards.js",
+ " const canonSrc = f && bakeFrameUrl(state.name, f);",
+ " const canonSrc = f && (bakeFrameUrl(state.name, f) ?? frameUrl(state.name, f));"),
+ ("N5 탈출 M2: ?? 폴백 (row-export, 파일이 나간다)", "sprite_gen/serve/curator/src/row-export.js",
+ " const bakeSrc = f && bakeFrameUrl(stateName, f);",
+ " const bakeSrc = f && (bakeFrameUrl(stateName, f) ?? frameUrl(stateName, f));"),
+ ("N5 탈출 M3: 콤마 연산자 폴백", "sprite_gen/serve/curator/src/compare.js",
+ " const bakeSrc = f && bakeFrameUrl(name, f);",
+ " const bakeSrc = f && (bakeFrameUrl(name, f), frameUrl(name, f));"),
+ ("N5 탈출 N: 그리기를 헬퍼로 빼고 폴백을 호출부에", [
+ ("sprite_gen/serve/curator/src/zoom-editor.js", ' if (image && image.complete && image.naturalWidth) {\n const b = document.createElement("canvas");\n b.width = cellW;\n b.height = cellH;\n const bx = b.getContext("2d");\n bx.imageSmoothingEnabled = false;\n drawFrameInto(bx, image, getTransform(stateName, frameIdx), cellW, cellH,\n snapScaleFor(stateName), getPixelOps(stateName, frameIdx));', ' const paintCell = (bx, image) => {\n drawFrameInto(bx, image, getTransform(stateName, frameIdx), cellW, cellH,\n snapScaleFor(stateName), getPixelOps(stateName, frameIdx));\n };\n if (f) {\n const b = document.createElement("canvas");\n b.width = cellW;\n b.height = cellH;\n const bx = b.getContext("2d");\n bx.imageSmoothingEnabled = false;\n paintCell(bx, (image && image.complete && image.naturalWidth) ? image : img(frameUrl(stateName, f)));'),
+ ]),
+ ("N6 폐기 문구 복원", "CHANGELOG.md",
+ "is frozen into the sidecar as a cache",
+ "is frozen into the sidecar with a fingerprint of the\n frame it came from; a mismatch re-detects and says so. cache"),
+]
+
+TARGET = "tests"
+failed_to_bite = []
+for label, *rest in MUTS:
+ edits = rest[0] if len(rest) == 1 else [(rest[0], rest[1], rest[2])]
+ backups, stale = {}, False
+ for rel, old, new in edits:
+ path = pathlib.Path(rel)
+ text = backups.setdefault(rel, path.read_text(encoding="utf-8"))
+ current = path.read_text(encoding="utf-8")
+ if old not in current:
+ print(f" !! {label}: 변이 대상 문자열을 못 찾았다 ({rel}) — 배터리가 낡았다")
+ stale = True
+ break
+ path.write_text(current.replace(old, new, 1), encoding="utf-8")
+ if stale:
+ for rel, text in backups.items():
+ pathlib.Path(rel).write_text(text, encoding="utf-8")
+ failed_to_bite.append(label + " (대상 없음)")
+ continue
+ try:
+ r = subprocess.run([PY, "-m", "pytest", TARGET, "-q", "--no-header", "-x",
+ "-k", "breathe or migrate"],
+ capture_output=True, text=True)
+ bit = r.returncode != 0
+ print(f" {'물었다' if bit else '!! 안 물었다'} {label}")
+ if not bit:
+ failed_to_bite.append(label)
+ finally:
+ for rel, text in backups.items():
+ pathlib.Path(rel).write_text(text, encoding="utf-8")
+
+print()
+if failed_to_bite:
+ print("무방비:", ", ".join(failed_to_bite))
+ sys.exit(1)
+print(f"변이 {len(MUTS)}건 전부 그물에 걸림")
diff --git a/scripts/check_visible_magenta.py b/scripts/check_visible_magenta.py
new file mode 100644
index 0000000..bf06abc
--- /dev/null
+++ b/scripts/check_visible_magenta.py
@@ -0,0 +1,16 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: Apache-2.0
+"""Backward-compatible wrapper for sprite_gen.frames.check_visible_magenta."""
+
+import sys
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+import sprite_gen.frames.check_visible_magenta 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/scripts/compose_layers.py b/scripts/compose_layers.py
new file mode 100644
index 0000000..8af1bc7
--- /dev/null
+++ b/scripts/compose_layers.py
@@ -0,0 +1,16 @@
+#!/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/scripts/compose_selected_cycle.py b/scripts/compose_selected_cycle.py
new file mode 100755
index 0000000..a03e9be
--- /dev/null
+++ b/scripts/compose_selected_cycle.py
@@ -0,0 +1,16 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: Apache-2.0
+"""Backward-compatible wrapper for sprite_gen.compose.compose_cycle."""
+
+import sys
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+import sprite_gen.compose.compose_cycle 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/scripts/compose_sprite_atlas.py b/scripts/compose_sprite_atlas.py
new file mode 100755
index 0000000..347b691
--- /dev/null
+++ b/scripts/compose_sprite_atlas.py
@@ -0,0 +1,16 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: Apache-2.0
+"""Backward-compatible wrapper for sprite_gen.compose.compose_atlas."""
+
+import sys
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+import sprite_gen.compose.compose_atlas 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/scripts/compose_sprite_gif.py b/scripts/compose_sprite_gif.py
new file mode 100755
index 0000000..2df3b57
--- /dev/null
+++ b/scripts/compose_sprite_gif.py
@@ -0,0 +1,16 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: Apache-2.0
+"""Backward-compatible wrapper for sprite_gen.compose.compose_gif."""
+
+import sys
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+import sprite_gen.compose.compose_gif 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/scripts/curation.py b/scripts/curation.py
new file mode 100644
index 0000000..d2c65e7
--- /dev/null
+++ b/scripts/curation.py
@@ -0,0 +1,12 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: Apache-2.0
+"""Backward-compatible wrapper for sprite_gen.curate.curation."""
+
+import sys
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+import sprite_gen.curate.curation as _impl
+
+globals().update({name: value for name, value in vars(_impl).items() if name not in {"__name__", "__package__", "__loader__", "__spec__"}})
diff --git a/scripts/export_aseprite.py b/scripts/export_aseprite.py
new file mode 100644
index 0000000..d9ee8fb
--- /dev/null
+++ b/scripts/export_aseprite.py
@@ -0,0 +1,15 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: Apache-2.0
+"""Backward-compatible wrapper for sprite_gen.compose.export_aseprite."""
+
+import sys
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+import sprite_gen.compose.export_aseprite 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/scripts/export_curated_pngs.py b/scripts/export_curated_pngs.py
new file mode 100644
index 0000000..d5d804b
--- /dev/null
+++ b/scripts/export_curated_pngs.py
@@ -0,0 +1,16 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: Apache-2.0
+"""Backward-compatible wrapper for sprite_gen.compose.export_pngs."""
+
+import sys
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+import sprite_gen.compose.export_pngs 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/scripts/extract.py b/scripts/extract.py
new file mode 100644
index 0000000..58c7642
--- /dev/null
+++ b/scripts/extract.py
@@ -0,0 +1,12 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: Apache-2.0
+"""Backward-compatible wrapper for sprite_gen.frames.extract."""
+
+import sys
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+import sprite_gen.frames.extract as _impl
+
+globals().update({name: value for name, value in vars(_impl).items() if name not in {"__name__", "__package__", "__loader__", "__spec__"}})
diff --git a/scripts/extract_sprite_row_frames.py b/scripts/extract_sprite_row_frames.py
new file mode 100755
index 0000000..64c2bcd
--- /dev/null
+++ b/scripts/extract_sprite_row_frames.py
@@ -0,0 +1,16 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: Apache-2.0
+"""Backward-compatible wrapper for sprite_gen.frames.extract."""
+
+import sys
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+import sprite_gen.frames.extract 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/scripts/generate_sprite_image.py b/scripts/generate_sprite_image.py
new file mode 100755
index 0000000..65d338e
--- /dev/null
+++ b/scripts/generate_sprite_image.py
@@ -0,0 +1,16 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: Apache-2.0
+"""Backward-compatible wrapper for sprite_gen.gen."""
+
+import sys
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+import sprite_gen.gen 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/scripts/gif_utils.py b/scripts/gif_utils.py
new file mode 100755
index 0000000..bf76bfa
--- /dev/null
+++ b/scripts/gif_utils.py
@@ -0,0 +1,12 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: Apache-2.0
+"""Backward-compatible wrapper for sprite_gen.util.gif_utils."""
+
+import sys
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+import sprite_gen.util.gif_utils as _impl
+
+globals().update({name: value for name, value in vars(_impl).items() if name not in {"__name__", "__package__", "__loader__", "__spec__"}})
diff --git a/scripts/inspect_sprite_run.py b/scripts/inspect_sprite_run.py
new file mode 100644
index 0000000..d44ff51
--- /dev/null
+++ b/scripts/inspect_sprite_run.py
@@ -0,0 +1,16 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: Apache-2.0
+"""Backward-compatible wrapper for sprite_gen.qa.inspect."""
+
+import sys
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+import sprite_gen.qa.inspect 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/scripts/interpolate_frames.py b/scripts/interpolate_frames.py
new file mode 100644
index 0000000..09a1ac8
--- /dev/null
+++ b/scripts/interpolate_frames.py
@@ -0,0 +1,16 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: Apache-2.0
+"""Backward-compatible wrapper for sprite_gen.effects.interpolate."""
+
+import sys
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+import sprite_gen.effects.interpolate 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(_impl.main())
diff --git a/scripts/measure_align_sigma.py b/scripts/measure_align_sigma.py
new file mode 100644
index 0000000..e37e9bd
--- /dev/null
+++ b/scripts/measure_align_sigma.py
@@ -0,0 +1,121 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: Apache-2.0
+"""Measure per-frame horizontal jitter σ for `fit.align_x` variants.
+
+For each variant, copies the source run's `sprite-request.json` + `raw/` strips
+into a scratch work dir (the source run is never written), patches
+`fit.align_x`, re-runs the extraction, and reports the population standard
+deviation of the per-frame alpha-weighted centroid X (full alpha and the
+bottom-20% foot band) inside the final cells. σ is the jitter a player sees as
+the body axis wobbling during playback.
+
+Usage:
+ python3 scripts/measure_align_sigma.py \
+ --run-dir <run with sprite-request.json + raw/> \
+ --states down_walk,down_run \
+ --variants foot-centroid,alpha-centroid
+"""
+
+import argparse
+import json
+import shutil
+import statistics
+import sys
+import tempfile
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+from PIL import Image
+
+import sprite_gen.frames.extract as extract
+from sprite_gen.spec.runio import load_request
+
+
+def _prepare_work_dir(source: Path, work: Path, states: list[str], align_x: str) -> None:
+ (work / "raw").mkdir(parents=True, exist_ok=True)
+ request = load_request(source)
+ fit = dict(request.get("fit") or {})
+ fit["align_x"] = align_x
+ request["fit"] = fit
+ (work / "sprite-request.json").write_text(
+ json.dumps(request, ensure_ascii=False, indent=2) + "\n", encoding="utf-8"
+ )
+ for state in states:
+ raw = source / "raw" / f"{state}.png"
+ if not raw.is_file():
+ raise SystemExit(f"missing raw strip: {raw}")
+ shutil.copyfile(raw, work / "raw" / f"{state}.png")
+
+
+def _measure_state(work: Path, state: str) -> dict:
+ # frame-N.png 만 — frame-N.plain.png (픽셀 언페이크 전 쌍둥이) 는 제외.
+ frame_paths = sorted(
+ (path for path in (work / "frames" / state).glob("frame-*.png") if path.stem.split("-")[1].isdigit()),
+ key=lambda p: int(p.stem.split("-")[1]),
+ )
+ if not frame_paths:
+ raise SystemExit(f"no extracted frames for {state} in {work}")
+ full, foot = [], []
+ for path in frame_paths:
+ with Image.open(path) as frame:
+ cell = frame.convert("RGBA")
+ full.append(extract._alpha_centroid_x(cell, 1.0))
+ foot.append(extract._alpha_centroid_x(cell, 0.2))
+ return {
+ "frames": len(frame_paths),
+ "sigma_centroid": statistics.pstdev(full),
+ "sigma_foot": statistics.pstdev(foot),
+ "centroids": [round(value, 2) for value in full],
+ }
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--run-dir", required=True, type=Path, help="source run (read-only)")
+ parser.add_argument("--states", default="down_walk,down_run")
+ parser.add_argument("--variants", default="foot-centroid,alpha-centroid")
+ parser.add_argument("--work-dir", type=Path, default=None, help="scratch root (default: mkdtemp)")
+ parser.add_argument("--json", action="store_true", help="emit machine-readable JSON instead of the table")
+ args = parser.parse_args()
+
+ source = args.run_dir.expanduser().resolve()
+ states = [state.strip() for state in args.states.split(",") if state.strip()]
+ variants = [variant.strip() for variant in args.variants.split(",") if variant.strip()]
+ work_root = args.work_dir or Path(tempfile.mkdtemp(prefix="align-sigma-"))
+ work_root.mkdir(parents=True, exist_ok=True)
+
+ results: dict = {}
+ for variant in variants:
+ work = work_root / variant
+ if work.exists():
+ shutil.rmtree(work)
+ _prepare_work_dir(source, work, states, variant)
+ code = extract.run(run_dir=work, states=",".join(states))
+ if code != 0:
+ print(f"[warn] extraction for {variant} exited {code} (see warnings above)", file=sys.stderr)
+ results[variant] = {state: _measure_state(work, state) for state in states}
+
+ if args.json:
+ print(json.dumps({"run_dir": str(source), "results": results}, ensure_ascii=False, indent=2))
+ return 0
+
+ print(f"\nrun: {source}")
+ print(f"work dirs kept under: {work_root}\n")
+ print("| state | align_x | frames | σ centroid (px) | σ foot (px) |")
+ print("|---|---|---|---|---|")
+ for state in states:
+ for variant in variants:
+ row = results[variant][state]
+ print(
+ f"| {state} | {variant} | {row['frames']} "
+ f"| {row['sigma_centroid']:.2f} | {row['sigma_foot']:.2f} |"
+ )
+ for state in states:
+ for variant in variants:
+ print(f"{state}/{variant} centroids: {results[variant][state]['centroids']}")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scripts/prepare_sprite_run.py b/scripts/prepare_sprite_run.py
new file mode 100755
index 0000000..600aeb5
--- /dev/null
+++ b/scripts/prepare_sprite_run.py
@@ -0,0 +1,16 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: Apache-2.0
+"""Backward-compatible wrapper for sprite_gen.gen.prepare."""
+
+import sys
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+import sprite_gen.gen.prepare 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/scripts/preview_animation.py b/scripts/preview_animation.py
new file mode 100755
index 0000000..dbacb22
--- /dev/null
+++ b/scripts/preview_animation.py
@@ -0,0 +1,16 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: Apache-2.0
+"""Backward-compatible wrapper for sprite_gen.qa.preview."""
+
+import sys
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+import sprite_gen.qa.preview 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/scripts/recolor.py b/scripts/recolor.py
new file mode 100644
index 0000000..5c5e6cd
--- /dev/null
+++ b/scripts/recolor.py
@@ -0,0 +1,16 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: Apache-2.0
+"""Backward-compatible wrapper for sprite_gen.effects.recolor."""
+
+import sys
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+import sprite_gen.effects.recolor 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/scripts/reroll_state_row.py b/scripts/reroll_state_row.py
new file mode 100644
index 0000000..a3ffba0
--- /dev/null
+++ b/scripts/reroll_state_row.py
@@ -0,0 +1,16 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: Apache-2.0
+"""Backward-compatible wrapper for sprite_gen.effects.reroll."""
+
+import sys
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+import sprite_gen.effects.reroll 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(_impl.main())
diff --git a/scripts/run_correction_loop.py b/scripts/run_correction_loop.py
new file mode 100644
index 0000000..3297e5a
--- /dev/null
+++ b/scripts/run_correction_loop.py
@@ -0,0 +1,16 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: Apache-2.0
+"""Backward-compatible wrapper for sprite_gen.qa.correction_loop."""
+
+import sys
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+import sprite_gen.qa.correction_loop 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/scripts/runio.py b/scripts/runio.py
new file mode 100644
index 0000000..3aa26d3
--- /dev/null
+++ b/scripts/runio.py
@@ -0,0 +1,12 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: Apache-2.0
+"""Backward-compatible wrapper for sprite_gen.spec.runio."""
+
+import sys
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+import sprite_gen.spec.runio as _impl
+
+globals().update({name: value for name, value in vars(_impl).items() if name not in {"__name__", "__package__", "__loader__", "__spec__"}})
diff --git a/scripts/score_sprite_run.py b/scripts/score_sprite_run.py
new file mode 100644
index 0000000..c271c20
--- /dev/null
+++ b/scripts/score_sprite_run.py
@@ -0,0 +1,16 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: Apache-2.0
+"""Backward-compatible wrapper for sprite_gen.qa.score."""
+
+import sys
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+import sprite_gen.qa.score 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/scripts/serve_curation.py b/scripts/serve_curation.py
new file mode 100755
index 0000000..8cbbd39
--- /dev/null
+++ b/scripts/serve_curation.py
@@ -0,0 +1,16 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: Apache-2.0
+"""Backward-compatible wrapper for sprite_gen.serve.serve_curation."""
+
+import sys
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+import sprite_gen.serve.serve_curation 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/scripts/slice_sheet_cells.py b/scripts/slice_sheet_cells.py
new file mode 100755
index 0000000..1c63586
--- /dev/null
+++ b/scripts/slice_sheet_cells.py
@@ -0,0 +1,16 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: Apache-2.0
+"""Backward-compatible wrapper for sprite_gen.frames.slice_sheet."""
+
+import sys
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+import sprite_gen.frames.slice_sheet 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/scripts/unpack_atlas_run.py b/scripts/unpack_atlas_run.py
new file mode 100644
index 0000000..1e7974c
--- /dev/null
+++ b/scripts/unpack_atlas_run.py
@@ -0,0 +1,16 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: Apache-2.0
+"""Backward-compatible wrapper for sprite_gen.frames.unpack_atlas."""
+
+import sys
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+import sprite_gen.frames.unpack_atlas 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/scripts/validate_pr6_subject_profile.py b/scripts/validate_pr6_subject_profile.py
new file mode 100644
index 0000000..950b019
--- /dev/null
+++ b/scripts/validate_pr6_subject_profile.py
@@ -0,0 +1,211 @@
+#!/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[1]
+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",
+ "motion_phase_guides": False,
+ "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/__init__.py b/sprite_gen/__init__.py
new file mode 100644
index 0000000..1e51795
--- /dev/null
+++ b/sprite_gen/__init__.py
@@ -0,0 +1,21 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Importable core for the sprite-gen pipeline."""
+
+# The declared NumPy dependency is gated here, at package import, so that every
+# entrypoint — the 22 `scripts/*.py` wrappers, `-m sprite_gen.cli`, and any
+# downstream importer — fails on a NumPy-less interpreter with the install path
+# instead of a bare ModuleNotFoundError deeper in. See `sprite_gen/_deps.py`.
+from sprite_gen import _deps as _deps # noqa: F401
+
+# Domain subpackages (physical taxonomy). Module domains: sprite_gen/_modules.py.
+__all__ = [
+ "spec", # run dir IO, request/layout, migrations
+ "gen", # provider-backed image generation
+ "frames", # sheet -> frames extraction (+ inverse unpack)
+ "curate", # curation decisions / sidecar / anchors
+ "compose", # bake atlas / cycle / gif / layers / export
+ "effects", # per-frame transforms: breathe, recolor, interpolate, reroll
+ "qa", # inspect / score / correction-loop / preview
+ "serve", # webview servers (curation, compose) + SPAs
+ "util", # shared helpers
+]
diff --git a/sprite_gen/_deps.py b/sprite_gen/_deps.py
new file mode 100644
index 0000000..52a40a2
--- /dev/null
+++ b/sprite_gen/_deps.py
@@ -0,0 +1,62 @@
+# SPDX-License-Identifier: Apache-2.0
+"""The one module that imports NumPy — and the one place its absence is reported.
+
+NumPy is a declared runtime dependency (`pyproject.toml`), materialized by the
+repo-root `.venv` that README quickstart and CI build. An interpreter without it
+is not a degraded environment this package works around: the extraction path
+carries a byte-identity contract, so a second implementation of the same pixel
+math would be two answers to one question (principle 6). There is therefore no
+pure-Python fallback, and there is no `numpy = None` sentinel for callers to
+branch on — importing this module either yields NumPy or raises.
+
+A bare `import numpy` would already fail loudly, but `No module named 'numpy'`
+tells an agent nothing about *which* interpreter it just used or how to get a
+working one, and that is the failure this repo actually hit (homebrew `python3`
+carried Pillow but not NumPy, so the surface looked provisioned). This module
+re-raises with the interpreter it ran under and the exact install command.
+
+Every other shipped module reaches NumPy through here, by importing `np` from
+this module, and `sprite_gen/__init__.py` imports this module, so the gate fires
+at package import — before any entrypoint gets far enough to do partial work.
+`tests/test_numpy_dependency_gate.py` locks both halves.
+"""
+
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+REPO_ROOT = Path(__file__).resolve().parents[1]
+VENV_PYTHON = REPO_ROOT / ".venv" / "bin" / "python"
+
+
+def _missing_numpy_message() -> str:
+ """The install path, spelled out for whoever is reading the traceback.
+
+ Paths are resolved from this file rather than quoted from SKILL.md's
+ `$SPRITE_GEN_ROOT/...` public register so the command is
+ copy-pasteable in the shell that just failed; in a canonical deployment the
+ two name the same directory.
+ """
+ return (
+ "sprite-gen requires NumPy and this interpreter cannot import it.\n"
+ f" interpreter: {sys.executable}\n"
+ f" sprite-gen: {REPO_ROOT}\n"
+ "Install the declared dependencies into the skill venv, then run the skill with "
+ "that interpreter:\n"
+ f" {VENV_PYTHON} -m pip install -e {REPO_ROOT}\n"
+ f" {VENV_PYTHON} <script>.py ...\n"
+ "There is no pure-Python fallback — the extraction path carries a byte-identity "
+ "contract and will not run twice as fast-and-loose scalar code "
+ "(SKILL.md '실행 인터프리터', SECURITY.md 'Current Dependency Surface')."
+ )
+
+
+try:
+ import numpy
+except ModuleNotFoundError as exc: # pragma: no cover - exercised in a subprocess
+ raise ModuleNotFoundError(_missing_numpy_message()) from exc
+
+np = numpy
+
+__all__ = ["np", "numpy", "REPO_ROOT", "VENV_PYTHON"]
diff --git a/sprite_gen/_modules.py b/sprite_gen/_modules.py
new file mode 100644
index 0000000..5943786
--- /dev/null
+++ b/sprite_gen/_modules.py
@@ -0,0 +1,47 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Domain of each pipeline module — the single source for the package taxonomy.
+
+Used at runtime to run a pipeline step as `-m sprite_gen.<domain>.<step>` and by
+the reorg tooling. Keep in sync with the physical folder layout.
+"""
+
+MODULE_DOMAIN = {
+ 'runio': 'spec',
+ 'layout': 'spec',
+ 'migrate_request': 'spec',
+ 'migrate_breathe': 'spec',
+ 'generate_image': 'gen',
+ 'prepare': 'gen',
+ 'extract': 'frames',
+ 'cutout': 'frames',
+ 'segment': 'frames',
+ 'slice_sheet': 'frames',
+ 'check_visible_magenta': 'frames',
+ 'unpack_atlas': 'frames',
+ 'curation': 'curate',
+ 'anchor': 'curate',
+ 'compose_atlas': 'compose',
+ 'compose_cycle': 'compose',
+ 'compose_gif': 'compose',
+ 'compose_layers': 'compose',
+ 'layers': 'compose',
+ 'export_pngs': 'compose',
+ 'export_aseprite': 'compose',
+ 'breathe': 'effects',
+ 'anatomy': 'effects',
+ 'recolor': 'effects',
+ 'interpolate': 'effects',
+ 'reroll': 'effects',
+ 'inspect': 'qa',
+ 'score': 'qa',
+ 'correction_loop': 'qa',
+ 'preview': 'qa',
+ 'serve_curation': 'serve',
+ 'serve_compose': 'serve',
+ 'gif_utils': 'util',
+}
+
+
+def qualified(name: str) -> str:
+ """Fully-qualified module path for a pipeline step basename."""
+ return f"sprite_gen.{MODULE_DOMAIN[name]}.{name}"
diff --git a/sprite_gen/cli.py b/sprite_gen/cli.py
new file mode 100644
index 0000000..4fc92ce
--- /dev/null
+++ b/sprite_gen/cli.py
@@ -0,0 +1,348 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Single sprite-gen CLI entrypoint."""
+
+from __future__ import annotations
+
+import argparse
+from pathlib import Path
+from typing import Callable
+
+from sprite_gen import gen
+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.qa import correction_loop, inspect, preview, score
+from sprite_gen.frames import cutout, extract, slice_sheet, unpack_atlas
+from sprite_gen.gen import prepare
+from sprite_gen.effects import recolor
+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
+
+
+def _parse_frames(value: str) -> list[int]:
+ frames = [int(part.strip()) for part in value.split(",") if part.strip()]
+ if not frames:
+ raise argparse.ArgumentTypeError("at least one frame number is required")
+ if any(frame <= 0 for frame in frames):
+ raise argparse.ArgumentTypeError("frame numbers are 1-based and must be positive")
+ return frames
+
+
+def _parse_frame_order(value: str) -> list[int]:
+ frames = [int(part.strip()) for part in value.split(",") if part.strip()]
+ if not frames:
+ raise argparse.ArgumentTypeError("frame order must contain at least one frame")
+ if any(frame <= 0 for frame in frames):
+ raise argparse.ArgumentTypeError("frame order is 1-based and must be positive")
+ return frames
+
+
+def _parse_grid(value: str) -> tuple[int, int]:
+ cols, rows = value.lower().split("x")
+ return int(cols), int(rows)
+
+
+def _add_prepare(p: argparse.ArgumentParser) -> None:
+ p.add_argument("--out-dir", required=True, type=Path)
+ p.add_argument("--character-id", required=True)
+ p.add_argument("--base-image", type=Path)
+ p.add_argument("--description", default="")
+ p.add_argument("--style", default=STYLE_DEFAULT)
+ p.add_argument("--subject", choices=SUBJECTS, default=None,
+ help="what the run draws: character (default) or effect — "
+ "sets validation defaults like the sparse-frame floor")
+ p.add_argument("--cell-size", type=int, default=256)
+ p.add_argument("--cell-width", type=int)
+ p.add_argument("--cell-height", type=int)
+ p.add_argument("--safe-margin", type=int, default=None, help="absolute px override; default is 9.4%% of the cell dimension, floored")
+ p.add_argument("--chroma-key", default="auto", help="auto or #RRGGBB")
+ p.add_argument("--fit-resample", choices=["lanczos", "nearest", "kcentroid"], default=None)
+ p.add_argument("--fit-align-x", choices=["bbox-center", "centroid", "foot-centroid", "alpha-centroid"], default=None)
+ p.add_argument("--fit-align-y", choices=["center", "bottom"], default=None)
+ p.add_argument("--fit-pixel-unfake", action=argparse.BooleanOptionalAction, default=None)
+ # 은퇴한 이름. 조용한 별칭으로 살려두지 않는다 — 두 이름이 공존하면 문서와 스크립트가
+ # 갈라진다. 대신 무엇으로 바뀌었는지 말하며 죽는다 (숨은 인자라 --help 를 어지럽히지 않음).
+ p.add_argument("--fit-pixel-perfect", "--no-fit-pixel-perfect", dest="_retired_pp",
+ action="store_true", help=argparse.SUPPRESS)
+ p.add_argument("--fit-logical-height", type=int, default=None)
+ p.add_argument("--fit-palette-size", type=int, default=None)
+ p.add_argument("--fit-detail-bias", action=argparse.BooleanOptionalAction, default=None)
+ p.add_argument("--fit-outline", type=_outline_config, default=None, metavar="{on,off,STRENGTH}")
+ p.add_argument("--fit-pitch-hint", type=int, default=None)
+ p.add_argument("--motion-phase-guides", action="store_true")
+ p.add_argument("--request", type=Path)
+ p.add_argument("--request-json")
+ p.add_argument("--force", action="store_true")
+
+
+def _add_extract(p: argparse.ArgumentParser) -> None:
+ p.add_argument("--run-dir", required=True, type=Path)
+ p.add_argument("--states", default="all")
+ p.add_argument("--key-threshold", type=float, default=96.0)
+ p.add_argument("--fringe-key-threshold", type=float, default=180.0)
+ p.add_argument("--fringe-delta", type=float, default=18.0)
+ p.add_argument("--fringe-unmix-reach", type=int, default=None)
+ p.add_argument("--spill-max-fraction", type=float, default=None)
+ p.add_argument("--segmentation", choices=("components", "projection"), default=None)
+ p.add_argument("--allow-slot-fallback", action="store_true")
+ p.add_argument("--min-used-pixels", type=int, default=None)
+ p.add_argument("--edge-margin", type=int, default=2)
+ p.add_argument("--edge-pixel-threshold", type=int, default=24)
+ p.add_argument("--chroma-adjacent-threshold", type=float, default=150.0)
+ p.add_argument("--chroma-adjacent-pixel-threshold", type=int, default=120)
+ p.add_argument("--small-outlier-ratio", type=float, default=0.35)
+ p.add_argument("--large-outlier-ratio", type=float, default=2.75)
+
+
+def _add_compose_atlas(p: argparse.ArgumentParser) -> None:
+ p.add_argument("--run-dir", required=True, type=Path)
+ p.add_argument("--atlas", default="sprite-sheet-alpha.png")
+ p.add_argument("--manifest", default="manifest.json")
+ p.add_argument("--report", default="sprite-sheet-alpha.report.json")
+ p.add_argument("--min-used-pixels", type=int, default=None)
+
+
+def _add_preview(p: argparse.ArgumentParser) -> None:
+ p.add_argument("--run-dir", required=True, type=Path)
+ p.add_argument("--delay-ticks", type=int)
+
+
+def _add_compose_cycle(p: argparse.ArgumentParser) -> None:
+ p.add_argument("--run-dir", required=True, type=Path)
+ p.add_argument("--state", required=True)
+ p.add_argument("--frames", type=_parse_frames)
+ p.add_argument("--name", required=True)
+ p.add_argument("--duration-ms", type=int, default=190)
+ p.add_argument("--delay-ticks", type=int)
+ p.add_argument("--note", default="")
+
+
+def _add_compose_gif(p: argparse.ArgumentParser) -> None:
+ p.add_argument("inputs", nargs="*", type=Path)
+ p.add_argument("--frame-dir", type=Path)
+ p.add_argument("--frame-order", type=_parse_frame_order)
+ p.add_argument("--run-dir", type=Path)
+ p.add_argument("--out-dir", type=Path)
+ p.add_argument("--output", type=Path)
+ p.add_argument("--delay-ticks", type=int, default=17)
+ p.add_argument("--loop-count", type=int, default=0)
+ p.add_argument("--contact-output", type=Path)
+ p.add_argument("--manifest-output", type=Path)
+ p.add_argument("--alpha-threshold", type=int, default=8)
+
+
+def _add_unpack_atlas(p: argparse.ArgumentParser) -> None:
+ p.add_argument("--atlas", type=Path)
+ p.add_argument("--manifest", type=Path)
+ p.add_argument("--pngs-dir", type=Path)
+ p.add_argument("--state-name", default="items")
+ p.add_argument("--out-dir", type=Path)
+ p.add_argument("--grid", type=_parse_grid)
+ p.add_argument("--cell", type=_parse_grid)
+ p.add_argument("--direction")
+ p.add_argument("--states")
+ p.add_argument("--auto", action="store_true")
+ p.add_argument("--force", action="store_true")
+
+
+def _add_export_pngs(p: argparse.ArgumentParser) -> None:
+ p.add_argument("--run-dir", required=True, type=Path)
+ p.add_argument("--state")
+ p.add_argument("--out-dir", type=Path)
+ p.add_argument("--selected-only", action="store_true")
+
+
+def _add_slice_sheet(p: argparse.ArgumentParser) -> None:
+ p.add_argument("--sheet", required=True, type=Path)
+ p.add_argument("--out-dir", required=True, type=Path)
+ p.add_argument("--chroma-key", required=True, help="magenta, green, or #RRGGBB")
+ p.add_argument("--grid", type=_parse_grid, default=(3, 2), help="COLSxROWS, default 3x2")
+ p.add_argument("--names", help="comma-separated output names, one per cell in reading order")
+ p.add_argument("--prefix", default="")
+ p.add_argument("--cell-width", type=int, default=512)
+ p.add_argument("--cell-height", type=int, default=768)
+ p.add_argument("--baseline-y", type=float, default=725.0)
+ p.add_argument("--target-height", type=float, default=645.0)
+ p.add_argument("--key-threshold", type=float, default=slice_sheet.DEFAULT_KEY_THRESHOLD)
+ p.add_argument("--fringe-key-threshold", type=float, default=slice_sheet.DEFAULT_FRINGE_KEY_THRESHOLD)
+ p.add_argument("--fringe-delta", type=float, default=slice_sheet.DEFAULT_FRINGE_DELTA)
+ p.add_argument("--fringe-unmix-reach", type=int, default=4)
+ p.add_argument("--spill-max-fraction", type=float, default=0.005)
+ p.add_argument("--noise-min", type=int, default=slice_sheet.DEFAULT_NOISE_MIN)
+ p.add_argument("--debris-fraction", type=float, default=slice_sheet.DEFAULT_DEBRIS_FRACTION)
+
+
+def _add_inspect(p: argparse.ArgumentParser) -> None:
+ p.add_argument("--run-dir", required=True, type=Path)
+ p.add_argument("--states", default="all")
+ p.add_argument("--report", default="sprite-inspect.report.json")
+ p.add_argument("--histogram-min", type=float, default=inspect.DEFAULT_HISTOGRAM_MIN)
+ p.add_argument("--dhash-min", type=float, default=inspect.DEFAULT_DHASH_MIN)
+ p.add_argument("--motion-min", type=float, default=inspect.DEFAULT_MOTION_MIN)
+ p.add_argument("--key-threshold", type=float, default=96.0)
+ p.add_argument("--fringe-key-threshold", type=float, default=180.0)
+ p.add_argument("--fringe-delta", type=float, default=18.0)
+ p.add_argument("--fringe-unmix-reach", type=int, default=None)
+ p.add_argument("--spill-max-fraction", type=float, default=None)
+ p.add_argument("--chroma-mode", choices=("rgb", "ycbcr"), default=None)
+ p.add_argument("--no-write", action="store_true")
+
+
+def _add_score(p: argparse.ArgumentParser) -> None:
+ p.add_argument("--inspect-report", required=True, type=Path)
+ p.add_argument("--output", default="sprite-score.report.json")
+ p.add_argument("--no-write", action="store_true")
+
+
+def _add_gen(p: argparse.ArgumentParser) -> None:
+ gen.add_arguments(p)
+
+
+def _add_cutout(p: argparse.ArgumentParser) -> None:
+ cutout.add_arguments(p)
+
+
+def _add_anchor(p: argparse.ArgumentParser) -> None:
+ anchor.add_arguments(p)
+
+
+def _add_correction_loop(p: argparse.ArgumentParser) -> None:
+ p.add_argument("--run-dir", required=True, type=Path)
+ p.add_argument("--states", default="all")
+ p.add_argument("--out-dir", type=Path)
+ p.add_argument("--max-passes", type=int, default=3)
+ p.add_argument("--pass-score", type=float, default=90.0)
+ p.add_argument("--provider-command")
+ p.add_argument("--dry-run", action="store_true")
+ p.add_argument("--no-preserve-best", action="store_true")
+
+
+COMMANDS: dict[str, tuple[str, Callable[[argparse.ArgumentParser], None], Callable[..., int]]] = {
+ "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": (
+ "Compose component-row frames into a game atlas and runtime manifest.",
+ _add_compose_atlas,
+ compose_atlas.run,
+ ),
+ "preview": ("Build motion-QA previews for a sprite-gen run.", _add_preview, preview.run),
+ "compose-cycle": (
+ "Compose a QA-approved manual frame subset into a selected cycle.",
+ _add_compose_cycle,
+ 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,
+ unpack_atlas.run,
+ ),
+ "export-pngs": ("Export curated frames back to named PNGs.", _add_export_pngs, export_pngs.run),
+ "export-aseprite": (
+ "Export the composed atlas as Aseprite-compatible JSON metadata.",
+ export_aseprite.add_arguments,
+ export_aseprite.run,
+ ),
+ "anchor": (
+ "Resolve/bake the direction anchor ref from curated truth (or pin which frame is the anchor).",
+ _add_anchor,
+ anchor.run,
+ ),
+ "migrate-breathe": (
+ "Migrate a run's retired split-line breathe sidecar to the envelope schema.",
+ migrate_breathe.add_arguments,
+ migrate_breathe.run,
+ ),
+ # The only writer that changes the request schema on disk. Reads (`runio.load_request`
+ # 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_request.add_arguments,
+ migrate_request.run,
+ ),
+ "slice-sheet": (
+ "Slice a multi-figure grid sheet into per-cell standing cuts (tachi-e).",
+ _add_slice_sheet,
+ slice_sheet.run,
+ ),
+ "gen": (
+ "Generate one image via a provider (codex image_gen / grok Imagine) into a verified PNG.",
+ _add_gen,
+ gen.run,
+ ),
+ "cutout": (
+ "Cut a uniform (white/ivory/solid) background off an imported image into a clean transparent PNG.",
+ _add_cutout,
+ cutout.run,
+ ),
+ # The argument surface is `serve_curation.add_arguments` itself, not a copy of it: the
+ # webview's own `--help` and this subcommand are the same declaration, so `sprite-gen
+ # curation` cannot drift from the launch form the READMEs still document.
+ "curation": (
+ "Serve the curation webview for one run directory.",
+ serve_curation.add_arguments,
+ serve_curation.run,
+ ),
+ # The pre-run half of curation: a blank-screen assembly canvas where a human
+ # mounts a folder and drags files onto rows to compose a sprite, instead of
+ # an agent arranging a --pngs-dir folder by hand. Same declaration-once rule
+ # as `curation` — the subcommand reuses the module's own add_arguments/run.
+ "compose": (
+ "Serve the composition canvas — mount a folder and assemble sprite rows.",
+ serve_compose.add_arguments,
+ serve_compose.run,
+ ),
+ "recolor": (
+ "Bake deterministic palette-swap variant sheets from a base sheet + recolor spec.",
+ recolor.add_recolor_arguments,
+ recolor.run,
+ ),
+ "recolor-palette": (
+ "Draft a palette map (distinct opaque colours by frequency) from a base sheet.",
+ recolor.add_palette_arguments,
+ recolor.run_palette,
+ ),
+ "inspect": ("Inspect sprite rows for frame-count, identity, and motion defects.", _add_inspect, inspect.run),
+ "score": ("Score a sprite inspect report and emit correction hints.", _add_score, score.run),
+ "correction-loop": (
+ "Run a bounded inspect -> score -> correction-hint loop.",
+ _add_correction_loop,
+ correction_loop.run,
+ ),
+}
+
+
+def _build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(prog="sprite-gen", description="Unified CLI for the sprite-gen pipeline.")
+ sub = parser.add_subparsers(dest="command", required=True, metavar="<tool>")
+ for name, (description, add_args, _run) in COMMANDS.items():
+ sp = sub.add_parser(name, description=description, help=description)
+ add_args(sp)
+ return parser
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = _build_parser()
+ args = parser.parse_args(argv)
+ if getattr(args, "_retired_pp", False):
+ from sprite_gen.gen.prepare import RETIRED_PP_MESSAGE
+
+ raise SystemExit(RETIRED_PP_MESSAGE)
+ kwargs = vars(args).copy()
+ kwargs.pop("_retired_pp", None)
+ command = kwargs.pop("command")
+ _description, _add_args, run_fn = COMMANDS[command]
+ return run_fn(**kwargs)
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/sprite_gen/compose/__init__.py b/sprite_gen/compose/__init__.py
new file mode 100644
index 0000000..9881313
--- /dev/null
+++ b/sprite_gen/compose/__init__.py
@@ -0,0 +1 @@
+# SPDX-License-Identifier: Apache-2.0
diff --git a/sprite_gen/compose/compose_atlas.py b/sprite_gen/compose/compose_atlas.py
new file mode 100644
index 0000000..484741f
--- /dev/null
+++ b/sprite_gen/compose/compose_atlas.py
@@ -0,0 +1,331 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Compose component-row frames into a game atlas and runtime manifest."""
+
+from __future__ import annotations
+
+import argparse
+import json
+import sys
+from pathlib import Path
+from typing import Any
+
+from PIL import Image
+
+from sprite_gen.effects.breathe import anatomy_report, fit_breathe_pattern, phase_frame, resolve_anatomy
+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
+
+
+def alpha_nonzero_count(image: Image.Image) -> int:
+ return sum(image.getchannel("A").histogram()[1:])
+
+
+def cell_geometry(cell: dict[str, Any]) -> tuple[int, int]:
+ width = int(cell.get("width", cell.get("size", 0)))
+ height = int(cell.get("height", cell.get("size", 0)))
+ if width <= 0 or height <= 0:
+ raise SystemExit("cell width/height must be positive in sprite-request.json")
+ return width, height
+
+
+def _build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--run-dir", required=True, type=Path)
+ parser.add_argument("--atlas", default="sprite-sheet-alpha.png")
+ parser.add_argument("--manifest", default="manifest.json")
+ parser.add_argument("--report", default="sprite-sheet-alpha.report.json")
+ # None = derive from the request's subject + drawable cell geometry
+ # (sprite_gen.spec.subject); the flag is an explicit override only.
+ parser.add_argument("--min-used-pixels", type=int, default=None)
+ return parser
+
+
+def _namespace_from_kwargs(**kwargs: object) -> argparse.Namespace:
+ parser = _build_parser()
+ values: dict[str, object] = {}
+ remaining = dict(kwargs)
+ for action in parser._actions:
+ if action.dest == "help":
+ continue
+ default = [] if action.nargs == "*" else action.default
+ if default is argparse.SUPPRESS:
+ default = None
+ value = remaining.pop(action.dest, default)
+ if getattr(action, "required", False) and value is None:
+ raise TypeError(f"missing required argument: {action.dest}")
+ values[action.dest] = value
+ if remaining:
+ names = ", ".join(sorted(remaining))
+ raise TypeError(f"unexpected keyword argument(s): {names}")
+ return argparse.Namespace(**values)
+def _run(args: argparse.Namespace):
+
+ run_dir = args.run_dir.expanduser().resolve()
+ # 소비 전 파생 캐시 자가치유 (실시간 계약): 합성이 굽는 것 = 항상 현재 엔진의
+ # 프레임. heal 은 서브프로세스 추출로 락을 따로 잡으므로 compose 락 획득 전에.
+ 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_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
+ rows_by_state = {row["state"]: row for row in frames_manifest.get("rows", [])}
+
+ states = list(request["states"])
+ cell_width, cell_height = cell_geometry(request["cell"])
+ cell_size = (cell_width, cell_height)
+
+ # curation.json is an optional non-destructive sidecar. When absent, every
+ # state uses all extracted frames in order with identity transform.
+ curation = load_curation(run_dir)
+ plans = {
+ state: state_plan(curation, state, state_frame_total(request, state))
+ for state in states
+ }
+ # 'plain' = pre-unfake twin (curator toggle off). Resolved per state
+ # (per-row curator toggle > run-wide default). Fail loud when the twin is
+ # missing — a plain bake must never silently fall back to pixel.
+ variants = {state: frame_variant(curation, state) for state in states}
+ # pixel-variant rows of a fit.pixel_unfake run re-snap curated transforms to the
+ # logical grid (plain rows keep the smooth BICUBIC bake — they are not grid art).
+ snap_scale = pixel_snap_scale(request)
+
+ # 아틀라스 셀 재사용 (maintainer 승인 2026-07-16): 같은 (원본 프레임, 변형, 픽셀편집)으로
+ # 구워지는 인스턴스는 칸 하나를 공유한다 — 프레임 복제·루프딜레이가 텍스처를
+ # 늘리지 않는다. frame_layout.rows 의 rect 목록은 인스턴스(재생) 순서 그대로이고
+ # 재사용 시 같은 rect 가 반복된다 (Aseprite JSON 과 동형 패턴 — 소비자는 지금처럼
+ # 프레임 인덱스 → rect 샘플링만 하면 된다).
+ def _instance_key(state: str, frame_index: int, phase: float = 0.0) -> tuple:
+ source_index = source_frame_index(curation, state, frame_index, state_frame_total(request, state))
+ edit_idx = edit_index(curation, state, frame_index) # 링크 복제 = 원본 편집 truth (셀 공유)
+ transform_key = json.dumps(plans[state][1].get(edit_idx), sort_keys=True)
+ ops_key = json.dumps(state_pixel_ops(curation, state).get(edit_idx), sort_keys=True)
+ return (source_index, transform_key, ops_key, phase)
+
+ # 호흡 후처리 레이어 (사이드카, maintainer 확정 2026-07-18 루프-맞춤): 재생 위치 =
+ # (프레임, 위상), 길이 = 기존 시퀀스 그대로 (루프 불변 — fit_breathe_pattern 이
+ # breaths 회를 시퀀스에 딱 떨어지게 배분). 텍스처 칸은 유니크 (프레임×위상)만.
+ #
+ # 위상은 연속값이지만 **반복된다**: breaths 회가 시퀀스에 딱 떨어지므로 슬롯 i 와
+ # i + seq_len/breaths 는 수학적으로 같은 위상이고, `fit_breathe_pattern` 이 정수
+ # 나머지를 먼저 취해 그 둘을 비트 동일한 double 로 만든다. 그래서 칸 재사용이
+ # 살아 있다 — 18슬롯 3호흡이면 유니크 칸 6개다. (분자를 정수로 접지 않으면 표현
+ # 노이즈로 14칸이 되어 바이트 동일한 칸이 8개 중복 구워졌다, validator 검증 2026-07-25.)
+ def _positions(state: str) -> list[tuple[int, float]]:
+ ordered = plans[state][0]
+ cfg = state_breathe(curation, state)
+ if not cfg or not ordered:
+ return [(i, 0.0) for i in ordered]
+ pattern = fit_breathe_pattern(len(ordered), cfg)
+ return [(ordered[i], pattern[i]) for i in range(len(ordered))]
+
+ positions_by_state = {state: _positions(state) for state in states}
+ breathe_by_state = {state: state_breathe(curation, state) for state in states}
+
+ columns = max(
+ max(1, len({_instance_key(state, i, ph) for i, ph in positions_by_state[state]}))
+ for state in states
+ )
+ atlas = Image.new("RGBA", (columns * cell_width, len(states) * cell_height), (0, 0, 0, 0))
+ frame_layout: dict[str, Any] = {
+ "sheetWidth": atlas.width,
+ "sheetHeight": atlas.height,
+ "cellWidth": cell_width,
+ "cellHeight": cell_height,
+ "rows": {},
+ }
+ animation: dict[str, Any] = {
+ "cellWidth": cell_width,
+ "cellHeight": cell_height,
+ "columns": columns,
+ "rows": {},
+ }
+ errors: list[str] = []
+ cells: list[dict[str, Any]] = []
+
+ for row_index, state in enumerate(states):
+ entry = request["states"][state]
+ ordered, transforms = plans[state]
+ positions = positions_by_state[state]
+ breathe_cfg = breathe_by_state[state]
+ variant = variants[state]
+ frames = []
+ row_source_frames: list[Image.Image] = [] # 호흡 적용 **직전** 프레임 (관측용)
+ row_anatomy = None # 줄 전체가 공유하는 한 벌 (첫 프레임에서 확정)
+ baked: dict[tuple, dict[str, Any]] = {} # instance key -> shared rect
+ for frame_index, breathe_phase in positions:
+ key = _instance_key(state, frame_index, breathe_phase)
+ reused = baked.get(key)
+ if reused is not None:
+ frames.append(reused)
+ cells.append({"state": state, "frame": frame_index, "reuses": True, **reused})
+ continue
+ # 파일 위치의 SSoT 는 manifest row 의 files — 패턴 조립 금지 (택소노미/flat 공용).
+ # 복제 인스턴스는 원본 프레임 파일을 읽는다 (변형/픽셀편집은 인스턴스 인덱스 소유).
+ source_index = source_frame_index(curation, state, frame_index, state_frame_total(request, state))
+ frame_path = run_dir / row_frame_rel(rows_by_state[state], source_index, variant)
+ if not frame_path.is_file():
+ errors.append(f"missing frame ({variant} variant): {frame_path}")
+ continue
+ edit_idx = edit_index(curation, state, frame_index)
+ with Image.open(frame_path) as opened:
+ source = apply_pixel_edits(opened.convert("RGBA"), state_pixel_ops(curation, state).get(edit_idx))
+ if source.size != cell_size:
+ errors.append(f"{frame_path} is {source.width}x{source.height}; expected {cell_width}x{cell_height}")
+ # apply the human curation transform (identity when uncurated)
+ frame = apply_transform(source, transforms.get(edit_idx), cell_size,
+ snap_scale=snap_scale if variant == "pixel" else None)
+ if breathe_cfg:
+ row_source_frames.append(frame)
+ if row_anatomy is None:
+ # 해부는 캐릭터 속성이라 줄 전체가 한 벌을 쓴다 — 프레임마다 다시 재면
+ # 경계가 흔들려 강체 구간이 프레임 간 같은 구간이 아니게 되고,
+ # 사이드카 한 벌로 그리는 프리뷰와도 갈린다 (validator 실측 2026-07-25).
+ row_anatomy = resolve_anatomy(frame, breathe_cfg)
+ # 호흡 위상은 최종 셀 픽셀 위 결정론 봉투 워프 — 팔레트·격자 불변.
+ # **위상 0 도 굽는다.** 구 분할선 방식에선 위상 0 이 항등이라 건너뛰어도
+ # 됐지만 봉투에선 아니다: 진행파 지연(lag) 때문에 t=0 에서도 윗행은
+ # wave(-lag*u) 만큼 변형된다. 건너뛰면 그 칸만 원본이 되어 아틀라스가
+ # 매 루프 시작에서 튀고 GIF 굽기와 그림이 갈린다 (validator 검증 2026-07-25).
+ frame = phase_frame(frame, breathe_cfg, breathe_phase, row_anatomy)
+ nontransparent = alpha_nonzero_count(frame)
+ if nontransparent < args.min_used_pixels:
+ errors.append(f"{state} frame {frame_index} is too sparse ({nontransparent})")
+ left = len(baked) * cell_width
+ top = row_index * cell_height
+ atlas.alpha_composite(frame, (left, top))
+ rect = {"x": left, "y": top, "w": cell_width, "h": cell_height}
+ baked[key] = rect
+ frames.append(rect)
+ cells.append({"state": state, "frame": frame_index, "nontransparent_pixels": nontransparent, **rect})
+
+ frame_layout["rows"][state] = frames
+ # durations_ms: 프레임별 표시 시간 계약 (지금은 fps 등간격 — 프레임별 편집
+ # UI 가 생기면 여기만 비등간격으로 채워진다). 소비자는 이 배열이 있으면
+ # fps 대신 이것을 따른다.
+ duration_ms = max(1, round(1000.0 / (float(entry.get("fps", 6)) or 6.0)))
+ animation["rows"][state] = {
+ "row": row_index,
+ "frames": len(positions),
+ "fps": int(entry.get("fps", 6)),
+ # 프레임별 지속시간은 프레임 복제가 담당한다 (maintainer 확정 2026-07-18 —
+ # 복제는 아틀라스 셀 공유라 부하 0; per-frame duration 이중 진실 금지).
+ # 전체 속도는 state fps 하나로 조정한다.
+ "durations_ms": [duration_ms] * len(positions),
+ "loop": bool(entry.get("loop", True)),
+ "frame_variant": variant,
+ }
+ if breathe_cfg:
+ # 자가 복구가 돌았는지, 프레임마다 경계가 달라졌는지 관측 (원칙 6).
+ 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())
+ variant_summary = unique_variants.pop() if len(unique_variants) == 1 else "mixed"
+
+ report = {
+ "ok": not errors,
+ "engine": "component-row",
+ "curation_applied": curation is not None,
+ "frame_variant": variant_summary,
+ "errors": errors,
+ "atlas": args.atlas,
+ "manifest": args.manifest,
+ "cell": request["cell"],
+ "states": states,
+ "cells": cells,
+ "frame_layout": frame_layout,
+ }
+
+ report_path = run_dir / args.report
+ atomic_write_text(report_path, json.dumps(report, ensure_ascii=False, indent=2) + "\n")
+ if errors:
+ print(json.dumps({k: v for k, v in report.items() if k != "cells"}, ensure_ascii=False, indent=2))
+ return 1
+
+ atlas_path = run_dir / args.atlas
+ atomic_save_image(atlas, atlas_path)
+ manifest = {
+ "characterId": request["character"]["id"],
+ "engine": "component-row",
+ "game_input": args.atlas,
+ "degraded_static_fallback": False,
+ "curation_applied": curation is not None,
+ "frame_variant": variant_summary,
+ "sprite_sheet_alpha": args.atlas,
+ "sprite_sheet_alpha_report": args.report,
+ "base_image": request["character"].get("base_image"),
+ "cell": request["cell"],
+ "chroma_key": request["chroma_key"],
+ "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
+
+
+
+def run(**kwargs: object):
+ return _run(_namespace_from_kwargs(**kwargs))
+
+def main() -> int:
+ parser = _build_parser()
+ args = parser.parse_args()
+ return _run(args)
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/sprite_gen/compose/compose_cycle.py b/sprite_gen/compose/compose_cycle.py
new file mode 100644
index 0000000..35f246d
--- /dev/null
+++ b/sprite_gen/compose/compose_cycle.py
@@ -0,0 +1,238 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Compose a QA-approved manual frame subset into a selected cycle.
+
+This is for cases where generation produces a larger row, but motion QA finds
+that only a human-selected subset is usable. The original extracted frame files
+remain the source; this script writes a small selected-cycle manifest plus GIF
+and contact-sheet previews.
+"""
+
+from __future__ import annotations
+
+import argparse
+import hashlib
+import json
+from pathlib import Path
+
+from PIL import Image, ImageDraw
+
+from sprite_gen.curate.curation import apply_pixel_edits, apply_transform, frame_variant, load_curation, pixel_snap_scale, source_frame_index, state_pixel_ops, state_plan
+from sprite_gen.spec.layout import row_frame_rel, state_frame_total
+from sprite_gen.frames.extract import require_frames_manifest
+from sprite_gen.util.gif_utils import delay_ticks_to_duration_ms, save_clean_gif
+from sprite_gen.spec.runio import read_guard, relative_posix, load_request
+
+
+def sha256(path: Path) -> str:
+ digest = hashlib.sha256()
+ with path.open("rb") as handle:
+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):
+ digest.update(chunk)
+ return digest.hexdigest()
+
+
+def checker(size: tuple[int, int], square: int = 16) -> Image.Image:
+ width, height = size
+ image = Image.new("RGBA", size, (210, 210, 210, 255))
+ pixels = image.load()
+ for y in range(height):
+ for x in range(width):
+ if ((x // square) + (y // square)) % 2 == 0:
+ pixels[x, y] = (235, 235, 235, 255)
+ return image
+
+
+def flatten(frame: Image.Image) -> Image.Image:
+ base = checker(frame.size)
+ base.alpha_composite(frame)
+ return base.convert("RGB")
+
+
+def parse_frames(value: str) -> list[int]:
+ frames = [int(part.strip()) for part in value.split(",") if part.strip()]
+ if not frames:
+ raise argparse.ArgumentTypeError("at least one frame number is required")
+ if any(frame <= 0 for frame in frames):
+ raise argparse.ArgumentTypeError("frame numbers are 1-based and must be positive")
+ return frames
+
+
+def load_frame(
+ run_dir: Path,
+ row: dict,
+ user_frame: int,
+ transform: dict[str, float] | None = None,
+ cell_size: tuple[int, int] | None = None,
+ variant: str = "pixel",
+ snap_scale: int | None = None,
+ pixel_ops: dict | None = None,
+) -> tuple[Path, Image.Image]:
+ path = run_dir / row_frame_rel(row, user_frame - 1, variant)
+ if not path.is_file():
+ raise SystemExit(f"missing selected frame {user_frame}: {path}")
+ image = apply_pixel_edits(Image.open(path).convert("RGBA"), pixel_ops)
+ if transform and cell_size:
+ image = apply_transform(image, transform, cell_size,
+ snap_scale=snap_scale if variant == "pixel" else None)
+ return path, image
+
+
+def contact_sheet(frames: list[tuple[int, Image.Image]], gap: int = 4, label_height: int = 24) -> Image.Image:
+ cell_width = max(frame.width for _number, frame in frames)
+ cell_height = max(frame.height for _number, frame in frames)
+ width = len(frames) * cell_width + (len(frames) + 1) * gap
+ height = cell_height + label_height + gap * 2
+ sheet = Image.new("RGB", (width, height), (255, 255, 255))
+ draw = ImageDraw.Draw(sheet)
+ x = gap
+ for number, frame in frames:
+ draw.rectangle((x, gap, x + cell_width - 1, gap + label_height - 1), fill=(24, 24, 24))
+ draw.text((x + 6, gap + 5), f"frame {number}", fill=(255, 255, 255))
+ sheet.paste(flatten(frame), (x, gap + label_height))
+ x += cell_width + gap
+ return sheet
+
+
+def _build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--run-dir", required=True, type=Path)
+ parser.add_argument("--state", required=True)
+ parser.add_argument("--frames", type=parse_frames, help="1-based frame numbers, for example 2,3,4,5; defaults to curation.json selection")
+ parser.add_argument("--name", required=True, help="output basename under qa/, without extension")
+ parser.add_argument("--duration-ms", type=int, default=190)
+ parser.add_argument("--delay-ticks", type=int, help="GIF delay in 1/100 second ticks; overrides --duration-ms")
+ parser.add_argument("--note", default="")
+ return parser
+
+
+def _namespace_from_kwargs(**kwargs: object) -> argparse.Namespace:
+ parser = _build_parser()
+ values: dict[str, object] = {}
+ remaining = dict(kwargs)
+ for action in parser._actions:
+ if action.dest == "help":
+ continue
+ default = [] if action.nargs == "*" else action.default
+ if default is argparse.SUPPRESS:
+ default = None
+ value = remaining.pop(action.dest, default)
+ if getattr(action, "required", False) and value is None:
+ raise TypeError(f"missing required argument: {action.dest}")
+ values[action.dest] = value
+ if remaining:
+ names = ", ".join(sorted(remaining))
+ raise TypeError(f"unexpected keyword argument(s): {names}")
+ return argparse.Namespace(**values)
+def _run(args: argparse.Namespace):
+
+ run_dir = args.run_dir.expanduser().resolve()
+ # Reader isolation: read manifest + request + curation + frames under one shared read_guard so
+ # a concurrent publish swap never yields a mid-swap/partial read (runio.read_guard ↔ publish_guard).
+ with read_guard(run_dir):
+ return _run_guarded(args, run_dir)
+
+
+def _run_guarded(args, run_dir):
+ frames_manifest = require_frames_manifest(run_dir) # fail loud if this generation's manifest is absent/corrupt
+ rows_by_state = {row["state"]: row for row in frames_manifest.get("rows", [])}
+ qa_dir = run_dir / "qa"
+ qa_dir.mkdir(parents=True, exist_ok=True)
+
+ request = load_request(run_dir)
+ cell = request["cell"]
+ cell_size = (
+ int(cell.get("width", cell.get("size", 0))),
+ int(cell.get("height", cell.get("size", 0))),
+ )
+ default_count = state_frame_total(request, args.state)
+ curation = load_curation(run_dir)
+ ordered, transforms = state_plan(curation, args.state, default_count)
+
+ # explicit --frames (1-based) wins; otherwise use the curation.json selection.
+ if args.frames is not None:
+ user_frames = args.frames
+ else:
+ user_frames = [index + 1 for index in ordered]
+
+ selected = [
+ # 파일은 원본 프레임(복제 인스턴스면 소스)을 읽고, 변형/픽셀편집은 인스턴스 번호로 조회
+ load_frame(run_dir, rows_by_state[args.state],
+ source_frame_index(curation, args.state, number - 1, default_count) + 1,
+ transforms.get(number - 1), cell_size,
+ frame_variant(curation, args.state), pixel_snap_scale(request),
+ state_pixel_ops(curation, args.state).get(number - 1))
+ for number in user_frames
+ ]
+ frame_paths = [path for path, _image in selected]
+ frames = [(number, image) for number, (_path, image) in zip(user_frames, selected)]
+
+ duration_ms = delay_ticks_to_duration_ms(args.delay_ticks) if args.delay_ticks else max(1, args.duration_ms)
+ gif_path = qa_dir / f"{args.name}.gif"
+ save_clean_gif(
+ [frame for _number, frame in frames],
+ gif_path,
+ duration_ms=duration_ms,
+ loop=0,
+ )
+
+ contact_path = qa_dir / f"{args.name}-contact.png"
+ contact_sheet(frames).save(contact_path)
+
+ manifest = {
+ "version": 1,
+ "kind": "sprite-gen-selected-cycle",
+ "run_dir": str(run_dir),
+ "state": args.state,
+ "name": args.name,
+ "selected_user_frames": user_frames,
+ "selected_zero_based_frames": [frame - 1 for frame in user_frames],
+ "selection_source": "explicit-frames" if args.frames is not None else "curation.json",
+ "transforms_applied": {str(n - 1): transforms[n - 1] for n in user_frames if (n - 1) in transforms},
+ "duration_ms": duration_ms,
+ "delay_ticks": round(duration_ms / 10),
+ "loop": True,
+ "note": args.note,
+ "outputs": {
+ "gif": relative_posix(gif_path, run_dir),
+ "contact": relative_posix(contact_path, run_dir),
+ },
+ "source_frames": [
+ {
+ "user_frame": user_frame,
+ "zero_based_frame": user_frame - 1,
+ "path": relative_posix(path, run_dir),
+ "sha256": sha256(path),
+ }
+ for user_frame, path in zip(user_frames, frame_paths)
+ ],
+ }
+ manifest_path = qa_dir / f"{args.name}.json"
+ manifest_path.write_text(json.dumps(manifest, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
+
+ print(
+ json.dumps(
+ {
+ "ok": True,
+ "manifest": str(manifest_path),
+ "gif": str(gif_path),
+ "contact": str(contact_path),
+ },
+ ensure_ascii=False,
+ indent=2,
+ )
+ )
+ return 0
+
+
+
+def run(**kwargs: object):
+ return _run(_namespace_from_kwargs(**kwargs))
+
+def main() -> int:
+ parser = _build_parser()
+ args = parser.parse_args()
+ return _run(args)
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/sprite_gen/compose/compose_gif.py b/sprite_gen/compose/compose_gif.py
new file mode 100644
index 0000000..5233acd
--- /dev/null
+++ b/sprite_gen/compose/compose_gif.py
@@ -0,0 +1,296 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Compose selected sprite frames into a clean transparent GIF.
+
+This is the reusable sprite-gen GIF exporter. It is intentionally small:
+source frame PNGs remain the SSoT, while this script only chooses order and
+timing for preview/runtime GIFs.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+from pathlib import Path
+
+from PIL import Image, ImageDraw
+
+from sprite_gen.effects.breathe import anatomy_report, bake_breathe_sequence
+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 require_frames_manifest
+from sprite_gen.spec.runio import read_guard, load_request
+from sprite_gen.util.gif_utils import delay_ticks_to_duration_ms, gif_report, save_clean_gif
+
+
+def parse_frame_order(value: str) -> list[int]:
+ frames = [int(part.strip()) for part in value.split(",") if part.strip()]
+ if not frames:
+ raise argparse.ArgumentTypeError("frame order must contain at least one frame")
+ if any(frame <= 0 for frame in frames):
+ raise argparse.ArgumentTypeError("frame order is 1-based and must be positive")
+ return frames
+
+
+def checker(size: tuple[int, int], square: int = 16) -> Image.Image:
+ width, height = size
+ image = Image.new("RGBA", size, (210, 210, 210, 255))
+ pixels = image.load()
+ for y in range(height):
+ for x in range(width):
+ if ((x // square) + (y // square)) % 2 == 0:
+ pixels[x, y] = (235, 235, 235, 255)
+ return image
+
+
+def flatten(frame: Image.Image) -> Image.Image:
+ base = checker(frame.size)
+ base.alpha_composite(frame.convert("RGBA"))
+ return base.convert("RGB")
+
+
+def load_frames(args: argparse.Namespace) -> list[tuple[int, Path, Image.Image]]:
+ if args.frame_dir:
+ frame_dir = args.frame_dir.expanduser().resolve()
+ order = args.frame_order
+ frames = []
+ for user_frame in order:
+ path = frame_dir / f"frame-{user_frame - 1}.png"
+ if not path.is_file():
+ raise SystemExit(f"missing frame {user_frame}: {path}")
+ frames.append((user_frame, path, Image.open(path).convert("RGBA")))
+ return frames
+
+ if args.inputs:
+ frames = []
+ for index, path in enumerate(args.inputs, start=1):
+ resolved = path.expanduser().resolve()
+ if not resolved.is_file():
+ raise SystemExit(f"missing input frame: {resolved}")
+ frames.append((index, resolved, Image.open(resolved).convert("RGBA")))
+ return frames
+
+ raise SystemExit("provide either --frame-dir with --frame-order, or input frame files")
+
+
+def contact_sheet(frames: list[tuple[int, Path, Image.Image]], gap: int = 4, label_height: int = 24) -> Image.Image:
+ cell_width = max(frame.width for _number, _path, frame in frames)
+ cell_height = max(frame.height for _number, _path, frame in frames)
+ width = len(frames) * cell_width + (len(frames) + 1) * gap
+ height = cell_height + label_height + gap * 2
+ sheet = Image.new("RGB", (width, height), (255, 255, 255))
+ draw = ImageDraw.Draw(sheet)
+ x = gap
+ for number, _path, frame in frames:
+ draw.rectangle((x, gap, x + cell_width - 1, gap + label_height - 1), fill=(24, 24, 24))
+ draw.text((x + 6, gap + 5), f"frame {number}", fill=(255, 255, 255))
+ sheet.paste(flatten(frame), (x, gap + label_height))
+ x += cell_width + gap
+ return sheet
+
+
+def run_dir_mode(args: argparse.Namespace) -> int:
+ """Export one clean GIF per state from a finished run dir.
+
+ Reads `sprite-request.json` (per-state frames + fps), applies the
+ `curation.json` selection/order/transform via the shared `curation` module
+ (SSoT with the atlas compose), and writes `<out-dir>/<state>.gif` plus a
+ `gif-manifest.json`. This is the path both the v1 webview server and the v2
+ desktop app call so they never reimplement frame selection.
+ """
+ run_dir = args.run_dir.expanduser().resolve()
+ # Reader isolation: read manifest + request + curation + frame tree under one shared read_guard
+ # so a concurrent publish swap never yields a mid-swap/partial read (runio.read_guard ↔ publish_guard).
+ with read_guard(run_dir):
+ return _run_dir_mode_guarded(args, run_dir)
+
+
+def _run_dir_mode_guarded(args, run_dir):
+ frames_manifest = require_frames_manifest(run_dir) # fail loud if this generation's manifest is absent/corrupt
+ rows_by_state = {row["state"]: row for row in frames_manifest.get("rows", [])}
+ request = load_request(run_dir)
+ cell = request.get("cell", {})
+ cell_w = int(cell.get("width") or cell.get("size") or 0)
+ cell_h = int(cell.get("height") or cell.get("size") or 0)
+ states = request.get("states", {})
+ if getattr(args, "state", None):
+ if args.state not in states:
+ raise SystemExit(f"unknown state '{args.state}' — request states: {', '.join(states)}")
+ states = {args.state: states[args.state]}
+ curation = load_curation(run_dir)
+ out_root = (args.out_dir.expanduser().resolve() if args.out_dir else run_dir / "exports")
+ out_root.mkdir(parents=True, exist_ok=True)
+
+ exports: list[dict] = []
+ for state, spec in states.items():
+ count = state_frame_total(request, state)
+ if count <= 0:
+ continue
+ fps = float(spec.get("fps", 8)) or 8.0
+ ordered, transforms = state_plan(curation, state, count)
+ variant = frame_variant(curation, state)
+ images: list[Image.Image] = []
+ for index in ordered:
+ # 복제 인스턴스는 원본 프레임 파일을 읽는다 (변형/픽셀편집은 인스턴스 인덱스).
+ path = run_dir / row_frame_rel(rows_by_state[state], source_frame_index(curation, state, index, count), variant)
+ if not path.is_file():
+ raise SystemExit(
+ f"selected frame {path} is missing — the generation is incomplete or the "
+ f"'{variant}' variant was not baked (re-extract before composing); "
+ f"skipping it would silently produce a shorter GIF."
+ )
+ edit_idx = edit_index(curation, state, index) # 링크 복제 = 원본 편집 truth
+ frame = apply_pixel_edits(Image.open(path).convert("RGBA"), state_pixel_ops(curation, state).get(edit_idx))
+ if cell_w and cell_h:
+ frame = apply_transform(frame, transforms.get(edit_idx), (cell_w, cell_h),
+ snap_scale=pixel_snap_scale(request) if variant == "pixel" else None)
+ images.append(frame)
+ if not images:
+ continue
+ # 호흡 후처리 레이어 (사이드카) — 재생 시퀀스 위에 결정론으로 굽는다.
+ # 깜빡임 프레임도 같은 위상 변조를 받는다 (직교 레이어, maintainer 2026-07-18).
+ breathe_cfg = state_breathe(curation, state)
+ baked_phases: list[float] | None = None
+ breathe_anatomy: dict | None = None
+ if breathe_cfg:
+ # 굽기가 실제로 쓴 해부를 먼저 확정해 manifest 에 싣는다 — 지문 불일치로
+ # 자가 복구가 돌면 사이드카 숫자와 구운 숫자가 다르고, 그게 안 보이면 안 된다.
+ breathe_anatomy = anatomy_report(images, breathe_cfg)
+ images, baked_phases = bake_breathe_sequence(images, breathe_cfg)
+ scale = max(1, int(getattr(args, "scale", 1) or 1))
+ if scale > 1:
+ # 니어리스트 정수배 — 픽셀 데이터는 그대로, 뷰어가 확대 보간으로 뭉개는 것만 막는다
+ images = [im.resize((im.width * scale, im.height * scale), Image.Resampling.NEAREST)
+ for im in images]
+ out_path = out_root / f"{state}.gif"
+ duration_ms = max(1, round(1000.0 / fps))
+ save_clean_gif(images, out_path, duration_ms=duration_ms, loop=args.loop_count, alpha_threshold=args.alpha_threshold)
+ export_entry = {
+ "state": state,
+ "output": str(out_path),
+ "frames": len(images),
+ "fps": fps,
+ "loop": bool(spec.get("loop", True)),
+ "gif_report": gif_report(out_path),
+ }
+ if baked_phases is not None:
+ export_entry["breathe"] = {"config": breathe_cfg, "phases": baked_phases,
+ "resolved": breathe_anatomy}
+ exports.append(export_entry)
+
+ if getattr(args, "state", None):
+ # 단건(--state) 내보내기는 전체 manifest 를 한 상태로 갈아치우지 않는다 —
+ # 기존 exports 에서 그 상태 항목만 교체/추가한다 (Consistency).
+ manifest_path = out_root / "gif-manifest.json"
+ prior: list[dict] = []
+ if manifest_path.is_file():
+ try:
+ prior = json.loads(manifest_path.read_text(encoding="utf-8")).get("exports", [])
+ except ValueError:
+ prior = []
+ merged = [e for e in prior if e.get("state") not in {x["state"] for x in exports}]
+ exports = merged + exports
+ manifest = {"version": 1, "kind": "sprite-gen-gif-run", "run_dir": str(run_dir), "exports": exports}
+ (out_root / "gif-manifest.json").write_text(json.dumps(manifest, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
+ print(json.dumps({"ok": True, **manifest}, ensure_ascii=False, indent=2))
+ return 0
+
+
+def _build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("inputs", nargs="*", type=Path, help="ordered frame PNG files")
+ parser.add_argument("--frame-dir", type=Path, help="directory containing frame-0.png, frame-1.png, ...")
+ parser.add_argument("--frame-order", type=parse_frame_order, help="1-based order, for example 2,1,5,3")
+ parser.add_argument("--run-dir", type=Path, help="run dir: export one GIF per state from sprite-request + curation")
+ parser.add_argument("--state", help="run-dir mode: export only this state (default: all states)")
+ parser.add_argument("--scale", type=int, default=1,
+ help="integer NEAREST upscale baked into the GIF (review/share crispness; "
+ "the pixel data is unchanged, viewers just stop blurring the upscale)")
+ parser.add_argument("--out-dir", type=Path, help="output dir for --run-dir mode (default <run-dir>/exports)")
+ parser.add_argument("--output", type=Path, help="output GIF (required unless --run-dir)")
+ parser.add_argument("--delay-ticks", type=int, default=17, help="GIF delay in 1/100 second ticks")
+ parser.add_argument("--loop-count", type=int, default=0, help="0 means infinite loop")
+ parser.add_argument("--contact-output", type=Path)
+ parser.add_argument("--manifest-output", type=Path)
+ parser.add_argument("--alpha-threshold", type=int, default=8)
+ return parser
+
+
+def _namespace_from_kwargs(**kwargs: object) -> argparse.Namespace:
+ parser = _build_parser()
+ values: dict[str, object] = {}
+ remaining = dict(kwargs)
+ for action in parser._actions:
+ if action.dest == "help":
+ continue
+ default = [] if action.nargs == "*" else action.default
+ if default is argparse.SUPPRESS:
+ default = None
+ value = remaining.pop(action.dest, default)
+ if getattr(action, "required", False) and value is None:
+ raise TypeError(f"missing required argument: {action.dest}")
+ values[action.dest] = value
+ if remaining:
+ names = ", ".join(sorted(remaining))
+ raise TypeError(f"unexpected keyword argument(s): {names}")
+ return argparse.Namespace(**values)
+def _run(args: argparse.Namespace):
+
+ if args.run_dir:
+ return run_dir_mode(args)
+
+ if not args.output:
+ raise SystemExit("--output is required unless --run-dir is used")
+
+ if bool(args.frame_dir) != bool(args.frame_order):
+ raise SystemExit("--frame-dir and --frame-order must be used together")
+
+ frames = load_frames(args)
+ output = args.output.expanduser().resolve()
+ duration_ms = delay_ticks_to_duration_ms(args.delay_ticks)
+ save_clean_gif(
+ [frame for _number, _path, frame in frames],
+ output,
+ duration_ms=duration_ms,
+ loop=args.loop_count,
+ alpha_threshold=args.alpha_threshold,
+ )
+
+ contact_path = args.contact_output.expanduser().resolve() if args.contact_output else None
+ if contact_path:
+ contact_path.parent.mkdir(parents=True, exist_ok=True)
+ contact_sheet(frames).save(contact_path)
+
+ manifest = {
+ "version": 1,
+ "kind": "sprite-gen-gif",
+ "output": str(output),
+ "delay_ticks": args.delay_ticks,
+ "duration_ms": duration_ms,
+ "loop_count": args.loop_count,
+ "selected_user_frames": [number for number, _path, _frame in frames],
+ "source_frames": [str(path) for _number, path, _frame in frames],
+ "contact": str(contact_path) if contact_path else None,
+ "gif_report": gif_report(output),
+ }
+
+ manifest_path = args.manifest_output.expanduser().resolve() if args.manifest_output else None
+ if manifest_path:
+ manifest_path.parent.mkdir(parents=True, exist_ok=True)
+ manifest_path.write_text(json.dumps(manifest, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
+
+ print(json.dumps({"ok": True, **manifest}, ensure_ascii=False, indent=2))
+ return 0
+
+
+
+def run(**kwargs: object):
+ return _run(_namespace_from_kwargs(**kwargs))
+
+def main() -> int:
+ parser = _build_parser()
+ args = parser.parse_args()
+ return _run(args)
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/sprite_gen/compose/compose_layers.py b/sprite_gen/compose/compose_layers.py
new file mode 100644
index 0000000..8d3511d
--- /dev/null
+++ b/sprite_gen/compose/compose_layers.py
@@ -0,0 +1,651 @@
+# 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
+
+# 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:
+ 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/export_aseprite.py b/sprite_gen/compose/export_aseprite.py
new file mode 100644
index 0000000..7358caf
--- /dev/null
+++ b/sprite_gen/compose/export_aseprite.py
@@ -0,0 +1,244 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Export a composed run as Aseprite-compatible atlas metadata.
+
+The exporter re-describes the existing atlas. It never re-encodes the image,
+and it reads only the composed ``manifest.json`` contract, so curated frame
+selection, order, transforms, edits, clones, and generated breathe cells are
+already baked before this stage runs.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import shutil
+import tempfile
+from importlib.metadata import PackageNotFoundError, version as package_version
+from pathlib import Path
+from typing import Any
+
+from sprite_gen.spec.runio import acquire_run_dir_lock, atomic_write_set, atomic_write_text, read_guard
+
+DEFAULT_OUTPUT = Path("exports/aseprite.json")
+DEFAULT_SPLIT_DIR = Path("exports/aseprite")
+
+
+def _package_version() -> str:
+ try:
+ return package_version("sprite-gen")
+ except PackageNotFoundError: # pragma: no cover - bare checkout
+ return "unknown"
+
+
+def _validated_rows(manifest: dict[str, Any]) -> dict[str, Any]:
+ layout_rows = manifest["frame_layout"]["rows"]
+ animation_rows = manifest["animation"]["rows"]
+ if set(layout_rows) != set(animation_rows):
+ raise ValueError(
+ "manifest rows disagree: "
+ f"frame_layout has {sorted(layout_rows)}, animation has {sorted(animation_rows)}"
+ )
+ return layout_rows
+
+
+def _state_durations(state: str, animation: dict[str, Any], count: int) -> list[int]:
+ durations = animation.get("durations_ms")
+ if not durations:
+ fps = float(animation.get("fps", 6)) or 6.0
+ durations = [max(1, round(1000.0 / fps))] * count
+ if len(durations) != count:
+ raise ValueError(
+ f"{state}: {count} layout rects but {len(durations)} durations_ms entries"
+ )
+ return [int(duration) for duration in durations]
+
+
+def _frame_entry(rect: dict[str, Any], duration: int, filename: str) -> dict[str, Any]:
+ size = {"w": rect["w"], "h": rect["h"]}
+ return {
+ "filename": filename,
+ "frame": {key: rect[key] for key in ("x", "y", "w", "h")},
+ "rotated": False,
+ "trimmed": False,
+ "spriteSourceSize": {"x": 0, "y": 0, **size},
+ "sourceSize": size,
+ "duration": duration,
+ }
+
+
+def _meta(manifest: dict[str, Any], tags: list[dict[str, Any]]) -> dict[str, Any]:
+ layout = manifest["frame_layout"]
+ return {
+ "app": "sprite-gen",
+ "version": _package_version(),
+ "image": manifest["game_input"],
+ "format": "RGBA8888",
+ "size": {"w": layout["sheetWidth"], "h": layout["sheetHeight"]},
+ "scale": "1",
+ "frameTags": tags,
+ }
+
+
+def _hashed(frames: list[dict[str, Any]]) -> dict[str, dict[str, Any]]:
+ return {
+ frame["filename"]: {key: value for key, value in frame.items() if key != "filename"}
+ for frame in frames
+ }
+
+
+def aseprite_json(manifest: dict[str, Any], *, fmt: str = "json-array") -> dict[str, Any]:
+ """Map one runtime manifest to Aseprite ``json-array`` or ``json-hash``."""
+ if fmt not in {"json-array", "json-hash"}:
+ raise ValueError(f"unknown format: {fmt!r} (expected json-array or json-hash)")
+ layout_rows = _validated_rows(manifest)
+ animation_rows = manifest["animation"]["rows"]
+ frames: list[dict[str, Any]] = []
+ tags: list[dict[str, Any]] = []
+ for state, rects in layout_rows.items():
+ durations = _state_durations(state, animation_rows[state], len(rects))
+ start = len(frames)
+ for rect, duration in zip(rects, durations):
+ frames.append(_frame_entry(rect, duration, str(len(frames))))
+ tags.append({"name": state, "from": start, "to": len(frames) - 1, "direction": "forward"})
+ return {"frames": _hashed(frames) if fmt == "json-hash" else frames, "meta": _meta(manifest, tags)}
+
+
+def split_state_jsons(
+ manifest: dict[str, Any], *, fmt: str = "json-hash"
+) -> dict[str, dict[str, Any]]:
+ """Return one locally indexed Aseprite document per animation state."""
+ if fmt not in {"json-array", "json-hash"}:
+ raise ValueError(f"unknown format: {fmt!r} (expected json-array or json-hash)")
+ layout_rows = _validated_rows(manifest)
+ animation_rows = manifest["animation"]["rows"]
+ documents: dict[str, dict[str, Any]] = {}
+ for state, rects in layout_rows.items():
+ durations = _state_durations(state, animation_rows[state], len(rects))
+ frames = [
+ _frame_entry(rect, duration, str(index))
+ for index, (rect, duration) in enumerate(zip(rects, durations))
+ ]
+ tags = [{"name": state, "from": 0, "to": len(frames) - 1, "direction": "forward"}]
+ documents[state] = {
+ "frames": _hashed(frames) if fmt == "json-hash" else frames,
+ "meta": _meta(manifest, tags),
+ }
+ return documents
+
+
+def _run_relative(run_dir: Path, value: str | Path, *, label: str) -> Path:
+ relative = Path(value)
+ if relative.is_absolute():
+ raise ValueError(f"{label} must be relative to the run dir: {value}")
+ target = (run_dir / relative).resolve()
+ try:
+ target.relative_to(run_dir)
+ except ValueError as exc:
+ raise ValueError(f"{label} escapes the run dir: {value}") from exc
+ return target
+
+
+def _export_target(run_dir: Path, value: str | Path, *, split_states: bool) -> Path:
+ """Resolve an export target without allowing canonical run files to be replaced."""
+ target = _run_relative(run_dir, value, label="output")
+ exports_root = (run_dir / "exports").resolve()
+ try:
+ relative = target.relative_to(exports_root)
+ except ValueError as exc:
+ raise ValueError(f"output must stay under the run's exports/ directory: {value}") from exc
+ if not relative.parts:
+ raise ValueError("output cannot replace the exports/ directory itself")
+ if not split_states and target.suffix.lower() != ".json":
+ raise ValueError(f"single-file output must be a .json file under exports/: {value}")
+ return target
+
+
+def _publish_split(output_dir: Path, documents: dict[str, dict[str, Any]]) -> None:
+ """Replace the split export directory as one rollback-capable generation."""
+ output_dir.parent.mkdir(parents=True, exist_ok=True)
+ staging = Path(tempfile.mkdtemp(prefix=f".{output_dir.name}.staging-", dir=output_dir.parent))
+ backup = output_dir.with_name(f".{output_dir.name}.backup")
+ try:
+ payloads = {
+ staging / f"{state}.json": json.dumps(document, ensure_ascii=False, indent=2) + "\n"
+ for state, document in documents.items()
+ }
+ atomic_write_set(payloads)
+ if backup.exists():
+ shutil.rmtree(backup)
+ if output_dir.exists():
+ output_dir.rename(backup)
+ try:
+ staging.rename(output_dir)
+ except BaseException:
+ if backup.exists():
+ backup.rename(output_dir)
+ raise
+ shutil.rmtree(backup, ignore_errors=True)
+ finally:
+ shutil.rmtree(staging, ignore_errors=True)
+
+
+def add_arguments(parser: argparse.ArgumentParser) -> None:
+ parser.add_argument("--run-dir", required=True, type=Path)
+ parser.add_argument("--manifest", default="manifest.json")
+ parser.add_argument("--output", help="run-relative file or split directory")
+ parser.add_argument("--format", dest="fmt", choices=("json-array", "json-hash"), default="json-array")
+ parser.add_argument("--split-states", action="store_true")
+
+
+def run(
+ run_dir: Path,
+ manifest: str = "manifest.json",
+ output: str | None = None,
+ fmt: str = "json-array",
+ split_states: bool = False,
+) -> int:
+ run_dir = run_dir.expanduser().resolve()
+ try:
+ acquire_run_dir_lock(run_dir, "export-aseprite")
+ manifest_path = _run_relative(run_dir, manifest, label="manifest")
+ output_path = _export_target(
+ run_dir,
+ output or (DEFAULT_SPLIT_DIR if split_states else DEFAULT_OUTPUT),
+ split_states=split_states,
+ )
+ with read_guard(run_dir):
+ data = json.loads(manifest_path.read_text(encoding="utf-8"))
+ if split_states:
+ documents = split_state_jsons(data, fmt=fmt)
+ _publish_split(output_path, documents)
+ report = {
+ "ok": True,
+ "output": str(output_path),
+ "image": data["game_input"],
+ "format": fmt,
+ "states": list(documents),
+ }
+ else:
+ exported = aseprite_json(data, fmt=fmt)
+ output_path.parent.mkdir(parents=True, exist_ok=True)
+ atomic_write_text(output_path, json.dumps(exported, ensure_ascii=False, indent=2) + "\n")
+ report = {
+ "ok": True,
+ "output": str(output_path),
+ "image": exported["meta"]["image"],
+ "format": fmt,
+ "frames": len(exported["frames"]),
+ "frameTags": [tag["name"] for tag in exported["meta"]["frameTags"]],
+ }
+ except (OSError, KeyError, TypeError, ValueError, json.JSONDecodeError) as exc:
+ print(json.dumps({"ok": False, "error": str(exc)}, ensure_ascii=False, indent=2))
+ return 1
+ print(json.dumps(report, ensure_ascii=False, indent=2))
+ return 0
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ add_arguments(parser)
+ return run(**vars(parser.parse_args(argv)))
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/sprite_gen/compose/export_pngs.py b/sprite_gen/compose/export_pngs.py
new file mode 100644
index 0000000..245884b
--- /dev/null
+++ b/sprite_gen/compose/export_pngs.py
@@ -0,0 +1,147 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Export curated frames back to named PNGs (the inverse of an imported set).
+
+For an imported still set (e.g. a furniture pack), the natural deliverable is
+not a single atlas but the same separate PNGs with the curation transform baked
+in, keeping each item's original filename so the consuming app needs no change.
+
+Output goes INSIDE the run dir by default (`<run-dir>/curated/`). That folder is
+provably writable — the curator already writes `curation.json` there — so this
+works the same on macOS, Linux, and Windows without assuming write access to any
+other location. The skill never creates folders elsewhere in your project tree;
+you copy `curated/` wherever the app needs it. `--out-dir` may target another
+path explicitly; if that path cannot be created/written it fails loudly (no
+silent fallback to a different location).
+
+ python3 export_curated_pngs.py --run-dir <run-dir> [--state <name>] [--out-dir <path>]
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import shutil
+from pathlib import Path
+
+from PIL import Image
+
+from sprite_gen.curate.curation import edit_index, apply_pixel_edits, apply_transform, frame_variant, load_curation, pixel_snap_scale, source_frame_index, state_pixel_ops, state_plan
+from sprite_gen.spec.layout import row_frame_rel, state_frame_total
+from sprite_gen.frames.extract import require_frames_manifest
+from sprite_gen.spec.runio import acquire_run_dir_lock, atomic_save_image, load_request
+
+
+def _build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--run-dir", required=True, type=Path)
+ parser.add_argument("--state", help="state to export; defaults to all states")
+ parser.add_argument("--out-dir", type=Path, help="output dir (default: <run-dir>/curated)")
+ parser.add_argument("--selected-only", action="store_true", help="export only selected frames")
+ return parser
+
+
+def _namespace_from_kwargs(**kwargs: object) -> argparse.Namespace:
+ parser = _build_parser()
+ values: dict[str, object] = {}
+ remaining = dict(kwargs)
+ for action in parser._actions:
+ if action.dest == "help":
+ continue
+ default = [] if action.nargs == "*" else action.default
+ if default is argparse.SUPPRESS:
+ default = None
+ value = remaining.pop(action.dest, default)
+ if getattr(action, "required", False) and value is None:
+ raise TypeError(f"missing required argument: {action.dest}")
+ values[action.dest] = value
+ if remaining:
+ names = ", ".join(sorted(remaining))
+ raise TypeError(f"unexpected keyword argument(s): {names}")
+ return argparse.Namespace(**values)
+def _run(args: argparse.Namespace):
+
+ run_dir = args.run_dir.expanduser().resolve()
+ acquire_run_dir_lock(run_dir, "export_curated_pngs")
+ request = load_request(run_dir)
+ cell = request["cell"]
+ cell_size = (int(cell.get("width", cell.get("size", 0))), int(cell.get("height", cell.get("size", 0))))
+ curation = load_curation(run_dir)
+
+ frames_manifest = require_frames_manifest(run_dir) # fail loud if absent/corrupt
+ labels_by_state = {row["state"]: row.get("labels", []) for row in frames_manifest.get("rows", [])}
+ rows_by_state = {row["state"]: row for row in frames_manifest.get("rows", [])}
+
+ out_dir = (args.out_dir.expanduser().resolve() if args.out_dir else run_dir / "curated")
+ try:
+ out_dir.mkdir(parents=True, exist_ok=True)
+ except OSError as exc:
+ raise SystemExit(f"cannot create output dir {out_dir}: {exc}")
+ if not os.access(out_dir, os.W_OK):
+ raise SystemExit(f"output dir not writable: {out_dir}")
+
+ states = [args.state] if args.state else list(request["states"])
+ written = []
+ for state in states:
+ if state not in request["states"]:
+ raise SystemExit(f"unknown state: {state}")
+ default_count = state_frame_total(request, state)
+ ordered, transforms = state_plan(curation, state, default_count)
+ indices = ordered if args.selected_only else list(range(default_count))
+ labels = labels_by_state.get(state, [])
+ multi_state = len(states) > 1
+ variant = frame_variant(curation, state)
+ for index in indices:
+ # 복제 인스턴스는 원본 프레임 파일을 읽는다 (변형/픽셀편집은 인스턴스 인덱스)
+ src_index = source_frame_index(curation, state, index, default_count)
+ src_path = run_dir / row_frame_rel(rows_by_state[state], src_index, variant)
+ if not src_path.is_file():
+ raise SystemExit(
+ f"selected frame {src_path} is missing — the generation is incomplete or the "
+ f"'{variant}' variant was not baked (re-extract before exporting); "
+ f"skipping it would silently drop a PNG."
+ )
+ with Image.open(src_path) as opened:
+ edit_idx = edit_index(curation, state, index)
+ baked = apply_transform(apply_pixel_edits(opened.convert("RGBA"), state_pixel_ops(curation, state).get(edit_idx)), transforms.get(edit_idx), cell_size,
+ snap_scale=pixel_snap_scale(request) if variant == "pixel" else None)
+ name = labels[index] if index < len(labels) and labels[index] else f"frame-{index}"
+ filename = f"{state}-{name}.png" if multi_state else f"{name}.png"
+ dest = out_dir / filename
+ atomic_save_image(baked, dest)
+ written.append(str(dest))
+
+ # carry the original meta.json along so the curated set is self-contained
+ source_meta = None
+ unpack_src = run_dir / "unpack-source.json"
+ if unpack_src.is_file():
+ info = json.loads(unpack_src.read_text(encoding="utf-8"))
+ if info.get("source_dir"):
+ candidate = Path(info["source_dir"]) / "meta.json"
+ if candidate.is_file():
+ shutil.copy2(candidate, out_dir / "meta.json")
+ source_meta = str(out_dir / "meta.json")
+
+ print(json.dumps({
+ "ok": True,
+ "out_dir": str(out_dir),
+ "count": len(written),
+ "files": written,
+ "meta_copied": source_meta,
+ "note": "copy this folder into your app; the skill did not write anywhere else",
+ }, ensure_ascii=False, indent=2))
+ return 0
+
+
+
+def run(**kwargs: object):
+ return _run(_namespace_from_kwargs(**kwargs))
+
+def main() -> int:
+ parser = _build_parser()
+ args = parser.parse_args()
+ return _run(args)
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/sprite_gen/compose/layers.py b/sprite_gen/compose/layers.py
new file mode 100644
index 0000000..cafe825
--- /dev/null
+++ b/sprite_gen/compose/layers.py
@@ -0,0 +1,493 @@
+# 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/curate/__init__.py b/sprite_gen/curate/__init__.py
new file mode 100644
index 0000000..9881313
--- /dev/null
+++ b/sprite_gen/curate/__init__.py
@@ -0,0 +1 @@
+# SPDX-License-Identifier: Apache-2.0
diff --git a/sprite_gen/curate/anchor.py b/sprite_gen/curate/anchor.py
new file mode 100644
index 0000000..118b9d5
--- /dev/null
+++ b/sprite_gen/curate/anchor.py
@@ -0,0 +1,515 @@
+# SPDX-License-Identifier: Apache-2.0
+"""방향 앵커 = 사람이 승인한 **단 한 장** — 해석·후처리 베이크·materialize 의 SSoT.
+
+앵커는 그 방향의 identity 다 (directional-anchor-workflow.md). 그래서 앵커 재료는
+raw 생성물이 아니라 **사람이 화면에서 승인한 모습**이어야 한다 — 픽셀 편집·변형·
+삭제·재정렬이 반영된 프레임. 이 모듈이 그 한 장을 결정하고 굽는다:
+
+ 지정(curation.json `anchors.<direction>`) > 그 방향 앵커 행의 시퀀스 첫 인스턴스
+
+두 번째가 기본값이다 (명시 기본값 — 폴백이 아니다). index 0 이 아니라 **시퀀스 첫
+인스턴스**인 이유: 사용자가 앞 프레임을 삭제/재정렬했으면 index 0 은 기각분이다
+(회귀 2026-07-19 maintainer — side_idle 이 0·1·2 삭제 후 3부터라 index 0 베이크가
+삭제된 미편집 프레임을 앵커로 만들었다).
+
+지정은 **어느 행의 어느 인스턴스든** 될 수 있다 (maintainer 2026-07-25 "내가 앵커를 정할
+수 있게, 어떤 프레임을 앵커로 할지 큐레이션 뷰에서"): 같은 방향이면 walk 의 3번
+프레임도, 시퀀스에 없는 후보 풀 프레임도 앵커가 될 수 있다. 사라진 인스턴스를
+가리키는 지정은 fail-loud 다 — 조용히 기본값으로 되돌리면 "지정했는데 왜 안 먹지"를
+사용자가 영원히 못 본다 (No Silent Fallback).
+
+`references/anchors/<direction>-anchor-x<scale>.png` 는 **파생 캐시**다: 생성 직전마다
+큐레이션 진실에서 다시 굽고 그 자리를 덮어쓴다. 정적 스냅샷을 재사용하면 사용자가
+뷰에서 앵커를 더 편집한 순간 소리 없이 낡고, 이후 생성 행 전부가 옛 정체성/치수를
+물려받는다 (회귀 2026-07-19 maintainer "다운앵커가 왜 내가 편집해둔 아틀라스가 아니야").
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+from pathlib import Path
+from typing import Any
+
+from sprite_gen.curate.curation import (anchor_choices, apply_pixel_edits, apply_transform, edit_index,
+ frame_variant, load_curation, pixel_snap_scale, source_frame_index,
+ state_instances, state_pixel_ops, state_plan)
+from sprite_gen.spec.layout import row_frame_rel, state_frame_total
+
+ANCHOR_SCALE = 8
+CONTENT_ALPHA_FLOOR = 40 # 콘텐츠 crop 기준 (프린지 알파를 콘텐츠로 세지 않는다)
+
+
+class AnchorUnavailable(SystemExit):
+ """앵커를 지금 낼 수 없다. `kind` 가 **"아직"(pending)** 과 **"깨졌다"(broken)** 를 가른다.
+
+ 두 상태는 사용자에게 전혀 다른 뜻이다: `pending` 은 생성이 거기까지 안 온 정상 구간
+ (앵커 행을 아직 안 뽑았다)이고, broken 은 사람이 고쳐야 하는 것(지정이 사라진 프레임을
+ 가리킨다·다른 방향 프레임을 지정했다)이다. 이 구분이 없으면 뷰가 멀쩡한 작업 중간 런에
+ 빨간 오류를 띄운다.
+
+ `SystemExit` 하위라 기존 fail-loud 계약(CLI 종료 코드, 서버의 `except SystemExit`)이
+ 그대로 산다 — 새 예외 계층을 만들어 호출부를 뜯지 않는다.
+
+ 분류를 `.code` 에 얹지 않는 이유 (validator 검증 2026-07-25 2차 기각): `SystemExit.code` 는
+ **인터프리터가 종료 시 stderr 에 찍는 채널**이다. 거기에 슬러그를 넣으면 정성껏 쓴
+ 안내문 대신 `no-frames` 한 단어만 사용자에게 간다 (실측: `anchor --for-state`
+ 추출 전 호출의 stderr 가 정확히 `no-frames`). 분류는 `kind` 가 들고, `.code` 는
+ 메시지가 흐르도록 손대지 않는다."""
+
+ PENDING_KINDS = frozenset({"no-frames", "row-not-extracted"})
+
+ def __init__(self, kind: str, message: str) -> None:
+ super().__init__(message) # .code = message — 인터프리터의 stderr 채널을 비워두지 않는다
+ self.kind = kind
+
+ @property
+ def pending(self) -> bool:
+ return self.kind in self.PENDING_KINDS
+
+
+# --- 방향/앵커 상태 어휘 ------------------------------------------------------
+# 방향 접두사 판정은 `directions.set` 만 본다 (layout 계약과 독립) — 택소노미
+# 이전 flat 방향 런도 같은 앵커 계약을 받아야 한다. 파일 경로는 그대로 layout
+# 리졸버(raw_rel/row_frame_rel)가 소유한다.
+
+def anchor_suffix(request: dict[str, Any]) -> str:
+ return str((request.get("directions") or {}).get("anchor_suffix", "idle"))
+
+
+def directions(request: dict[str, Any]) -> list[str]:
+ return [str(d) for d in ((request.get("directions") or {}).get("set") or [])]
+
+
+def anchor_state(request: dict[str, Any], direction: str) -> str:
+ """그 방향의 앵커 행 이름 (`<direction>_<anchor_suffix>`)."""
+ return f"{direction}_{anchor_suffix(request)}"
+
+
+def state_direction(request: dict[str, Any], state: str) -> str | None:
+ """상태가 속한 생성 방향 (없으면 None — 비방향 런/미러 방향)."""
+ for direction in directions(request):
+ if state == direction or state.startswith(direction + "_"):
+ return direction
+ return None
+
+
+def anchor_ref_rel(direction: str, scale: int = ANCHOR_SCALE) -> str:
+ """생성에 첨부되는 앵커 ref 의 런-상대 경로 (파생 캐시)."""
+ return f"references/anchors/{direction}-anchor-x{scale}.png"
+
+
+def _legacy_ref_rel(direction: str, scale: int) -> str:
+ """앵커가 `<dir>_idle` 시퀀스 헤드로만 정해졌던 시절의 이름. 지금은 앵커 프레임이
+ 다른 행에서 올 수 있어 `-idle-` 이 거짓이 된다 — materialize 가 지운다."""
+ return f"references/anchors/{direction}-idle-x{scale}.png"
+
+
+# --- 해석 -------------------------------------------------------------------
+
+def resolve_anchor(request: dict[str, Any], curation: dict[str, Any] | None,
+ direction: str) -> dict[str, Any]:
+ """이 방향의 앵커 인스턴스 = {"direction", "state", "index", "source"}.
+
+ source: "picked"(사용자 지정) | "default"(앵커 행 시퀀스 첫 인스턴스).
+ 해석 불가는 SystemExit — 앵커 없이 방향 행을 생성하지 않는다."""
+ if direction not in directions(request):
+ raise AnchorUnavailable(
+ "unknown-direction",
+ f"anchor: '{direction}' is not a generated direction "
+ f"({', '.join(directions(request)) or 'run has no directions block'})")
+ pick = anchor_choices(curation).get(direction)
+ if pick is not None:
+ state, index = pick["state"], pick["index"]
+ if state not in request.get("states", {}):
+ raise AnchorUnavailable(
+ "pick-unknown-state",
+ f"anchor: picked anchor state '{state}' is not in this run (direction "
+ f"{direction}) — re-pick the anchor frame in the curation view")
+ owner = state_direction(request, state)
+ if owner != direction:
+ raise AnchorUnavailable(
+ "pick-wrong-direction",
+ f"anchor: picked frame {state}#{index} belongs to direction '{owner}', not "
+ f"'{direction}' — an anchor owns its own facing")
+ if pick.get("stale"):
+ # 핀이 지금 프레임을 가리킨다고 **증명되지 않는다**. 그대로 쓰면 사용자가 본 적
+ # 없는 프레임이 방향 identity 가 된다 (이 플랜이 존재하는 사고와 같은 형태).
+ # 조용히 기본값으로 돌아가지도 않는다. 두 사유를 구분해 말한다 — "재생성됐다" 를
+ # 증명 없는 핀에 붙이면 사실과 다른 오류가 된다 (validator 5차 기각 2).
+ if pick.get("stale_reason") == "unverifiable":
+ raise AnchorUnavailable(
+ "pick-unverifiable",
+ f"anchor: pinned anchor frame {state}#{index} carries no generation stamp, so "
+ f"it cannot be proven to point at the current frames (a hand-written or "
+ f"pre-stamp pin) — re-pick the anchor frame in the curation view")
+ raise AnchorUnavailable(
+ "pick-stale-generation",
+ f"anchor: pinned anchor frame {state}#{index} is from an older generation of "
+ f"'{state}' (the row was regenerated, so that index is a different image now) "
+ f"— re-pick the anchor frame in the curation view")
+ live = state_instances(curation, state, state_frame_total(request, state))
+ if index not in live:
+ raise AnchorUnavailable(
+ "pick-missing",
+ f"anchor: picked anchor frame {state}#{index} no longer exists (archived, or "
+ f"the row was regenerated) — re-pick the anchor frame in the curation view")
+ return {"direction": direction, "state": state, "index": index, "source": "picked"}
+ state = anchor_state(request, direction)
+ if state not in request.get("states", {}):
+ raise AnchorUnavailable(
+ "no-anchor-row",
+ f"anchor: direction '{direction}' has no anchor row '{state}' and no picked anchor "
+ f"frame — declare/generate the anchor row, or pick a frame of this direction")
+ ordered, _ = state_plan(curation, state, state_frame_total(request, state))
+ if not ordered:
+ raise AnchorUnavailable(
+ "empty-sequence",
+ f"anchor: '{state}' has an empty curated sequence — nothing to use as the direction "
+ f"anchor (restore a frame, or pick one explicitly)")
+ return {"direction": direction, "state": state, "index": ordered[0], "source": "default"}
+
+
+def anchor_status(run_dir: Path, request: dict[str, Any], curation: dict[str, Any] | None,
+ direction: str) -> dict[str, Any]:
+ """뷰용 비-예외 상태: 해석 + 재료 파일 실재까지 확인하고 실패는 `error`(+`code`,
+ `pending`)로 돌려준다.
+
+ 표시는 죽지 않아야 하지만 **이유는 보여야** 한다 (조용한 빈칸 금지). 다만 `pending`
+ (아직 그 행을 안 뽑았다)은 오류가 아니라 정상 구간이므로 뷰가 경고색으로 칠하지
+ 않는다 — 그 구분이 `code` 다. 생성 경로는 언제나 `resolve_anchor`/`anchor_image` 의
+ fail-loud 를 쓴다."""
+ try:
+ resolved = resolve_anchor(request, curation, direction)
+ path = frame_source_path(run_dir, request, curation, resolved["state"], resolved["index"])
+ if not path.is_file():
+ raise AnchorUnavailable(
+ "frame-file-missing",
+ f"anchor: frame file missing for {resolved['state']}#{resolved['index']}: {path}")
+ return {**resolved, "error": None, "code": None, "pending": False}
+ except AnchorUnavailable as exc:
+ return {"direction": direction, "state": None, "index": None, "source": None,
+ "error": str(exc), "code": exc.kind, "pending": exc.pending}
+ except (SystemExit, Exception) as exc:
+ # 예상 밖 실패(손상된 매니페스트 등)도 뷰를 죽이지 않지만 pending 으로 위장하지 않는다
+ return {"direction": direction, "state": None, "index": None, "source": None,
+ "error": str(exc), "code": "unexpected", "pending": False}
+
+
+# --- 후처리 베이크 ------------------------------------------------------------
+
+def frame_source_path(run_dir: Path, request: dict[str, Any], curation: dict[str, Any] | None,
+ state: str, index: int) -> Path:
+ """이 인스턴스가 읽는 실제 프레임 파일 (복제 해소 + 표시/굽기 variant 반영).
+
+ 위치 SSoT 는 frames-manifest 의 `files` 다 (패턴 조립 금지 — layout.row_frame_rel).
+
+ 게이트는 `load_consistent_frames_manifest(allow_pending_states=True)` 다 —
+ `require_frames_manifest`(완성된 생성물 소비자 게이트: compose/export/preview)가
+ **아니다**. 앵커 소비자는 정의상 **생성 도중**에 돈다: stage-1 로 앵커 행만 뽑은
+ 시점에 stage-2 행들의 프레임은 아직 없고, 바로 그때 앵커 ref 가 필요하다. strict
+ 게이트를 물리면 request 의 모든 행에 매니페스트 행을 요구해서 "행 생성 직전에
+ 매번 돌려라" 라는 계약이 **항상** 실패한다 (validator 검증 2026-07-25 실측 —
+ stage-1 런에서 `--for-state`/`--direction`/`--all`/`--pick` 전부 corrupt-manifest
+ 로 죽었다). 뷰가 같은 이유로 이미 관용 게이트를 쓴다."""
+ from sprite_gen.frames.extract import load_consistent_frames_manifest
+
+ manifest = load_consistent_frames_manifest(run_dir, allow_pending_states=True)
+ if not manifest:
+ raise AnchorUnavailable(
+ "no-frames",
+ f"anchor: nothing extracted yet in {run_dir} — generate and extract the anchor row "
+ f"'{state}' first, then ask for its anchor ref")
+ row = next((r for r in manifest.get("rows", []) if r.get("state") == state), None)
+ if row is None:
+ raise AnchorUnavailable(
+ "row-not-extracted",
+ f"anchor: row '{state}' is not extracted yet — generate and extract it first "
+ f"(this is the normal state before that row exists, not a broken run)")
+ src_index = source_frame_index(curation, state, index, state_frame_total(request, state))
+ return run_dir / row_frame_rel(row, src_index, frame_variant(curation, state))
+
+
+def bake_frame(run_dir: Path, request: dict[str, Any], curation: dict[str, Any] | None,
+ state: str, index: int) -> "Any":
+ """인스턴스 하나를 **뷰에 보이는 그대로** 셀 캔버스에 굽는다 (RGBA).
+
+ export/compose 와 같은 프리미티브·같은 순서 (클론 해소 → 픽셀 편집 → 변형 →
+ pp 격자 재양자화) — 앵커만 다른 수학으로 구우면 승인한 모습과 어긋난다."""
+ from PIL import Image
+
+ cell = request["cell"]
+ cell_size = (int(cell.get("width", cell.get("size", 0))),
+ int(cell.get("height", cell.get("size", 0))))
+ default_count = state_frame_total(request, state)
+ _ordered, transforms = state_plan(curation, state, default_count)
+ variant = frame_variant(curation, state)
+ src_path = frame_source_path(run_dir, request, curation, state, index)
+ if not src_path.is_file():
+ raise AnchorUnavailable(
+ "frame-file-missing", f"anchor: frame file missing for {state}#{index}: {src_path}")
+ edit_idx = edit_index(curation, state, index)
+ with Image.open(src_path) as opened:
+ return apply_transform(
+ apply_pixel_edits(opened.convert("RGBA"),
+ state_pixel_ops(curation, state).get(edit_idx)),
+ transforms.get(edit_idx), cell_size,
+ snap_scale=pixel_snap_scale(request) if variant == "pixel" else None)
+
+
+def anchor_image(run_dir: Path, request: dict[str, Any], curation: dict[str, Any] | None,
+ direction: str, scale: int = ANCHOR_SCALE) -> tuple["Any", dict[str, Any]]:
+ """생성에 붙일 앵커 ref 이미지 + 해석 결과.
+
+ 콘텐츠 bbox 로 crop 한 뒤 ×scale 니어리스트 확대 — 픽셀 데이터는 그대로이고,
+ 작은 셀 스프라이트를 image-gen 이 읽을 수 있게 키우기만 한다."""
+ from PIL import Image
+
+ resolved = resolve_anchor(request, curation, direction)
+ img = bake_frame(run_dir, request, curation, resolved["state"], resolved["index"])
+ box = img.split()[3].point(lambda a: 255 if a >= CONTENT_ALPHA_FLOOR else 0).getbbox()
+ if box is None:
+ raise AnchorUnavailable(
+ "empty-content",
+ f"anchor: baked anchor frame {resolved['state']}#{resolved['index']} is empty "
+ f"(no visible pixels)")
+ content = img.crop(box)
+ upscaled = content.resize((content.width * scale, content.height * scale),
+ Image.Resampling.NEAREST)
+ return upscaled, {**resolved, "content_size": [content.width, content.height]}
+
+
+def materialize(run_dir: Path, direction: str, scale: int = ANCHOR_SCALE,
+ request: dict[str, Any] | None = None,
+ curation: dict[str, Any] | None = None, quiet: bool = False) -> Path:
+ """앵커 ref 를 큐레이션 진실에서 방금 구워 파일 자리를 덮어쓴다 (self-heal 캐시)."""
+ run_dir = Path(run_dir)
+ if request is None:
+ request = load_request(run_dir)
+ if curation is None:
+ curation = load_curation(run_dir)
+ image, resolved = anchor_image(run_dir, request, curation, direction, scale)
+ out = run_dir / anchor_ref_rel(direction, scale)
+ out.parent.mkdir(parents=True, exist_ok=True)
+ image.save(out)
+ legacy = run_dir / _legacy_ref_rel(direction, scale)
+ if legacy.is_file() and legacy != out:
+ legacy.unlink()
+ if not quiet:
+ print(f"[anchor] removed legacy snapshot {legacy.relative_to(run_dir)} "
+ f"(anchor frame is no longer pinned to the idle row)")
+ if not quiet:
+ print(f"[anchor] {direction}: baked {resolved['state']}#{resolved['index']} "
+ f"({resolved['source']}) -> {out.relative_to(run_dir)} "
+ f"({resolved['content_size'][0]}x{resolved['content_size'][1]} content)")
+ return out
+
+
+# --- 행 생성용 identity ref ---------------------------------------------------
+
+def load_request(run_dir: Path) -> dict[str, Any]:
+ """request 로드는 게이트 하나만 쓴다 (`runio.load_request`) — 여기 자체 구현을 두면
+ 스키마 이관이 이 경로만 비껴간다."""
+ from sprite_gen.spec.runio import load_request as _load
+
+ return _load(run_dir)
+
+
+def base_source(run_dir: Path) -> Path:
+ for candidate in sorted(Path(run_dir).glob("base-source.*")):
+ if candidate.suffix.lower() in (".png", ".jpg", ".jpeg", ".webp"):
+ return candidate
+ raise SystemExit(f"no base-source image in run dir: {run_dir}")
+
+
+def identity_ref(run_dir: Path, state: str, request: dict[str, Any] | None = None,
+ curation: dict[str, Any] | None = None, scale: int = ANCHOR_SCALE,
+ quiet: bool = False) -> Path:
+ """이 행을 생성할 때 identity 로 붙이는 파일 (refs[0]).
+
+ - 방향 런의 **액션 행** = 그 방향 앵커 (호출마다 큐레이션 진실에서 재베이크).
+ - 방향 앵커 행 자체 / 비방향 런 = `base-source.*` (앵커 이전 체인).
+ """
+ run_dir = Path(run_dir)
+ if request is None:
+ request = load_request(run_dir)
+ direction = state_direction(request, state)
+ if direction is not None and state != anchor_state(request, direction):
+ return materialize(run_dir, direction, scale, request=request,
+ curation=curation, quiet=quiet)
+ return base_source(run_dir)
+
+
+# --- 지정 쓰기 (CLI) ----------------------------------------------------------
+
+def _write_anchor_pick(run_dir: Path, request: dict[str, Any], state: str | None,
+ index: int | None, direction: str | None = None) -> dict[str, Any]:
+ """`curation.json` 의 `anchors.<direction>` 갱신 (state=None → 지정 해제).
+
+ Isolation: 사이드카는 뷰 autosave 와 공유 자원이라 배타락(publish_guard) 안에서
+ **fresh 재독 → 갱신 → 원자 쓰기** 한다 (lost update 금지).
+
+ Consistency: 재독은 raw `json.loads` 가 아니라 **세대 게이트**(`load_curation_report`)를
+ 통과해야 한다. 그냥 읽어 되쓰면 `stamp_curation` 이 payload 의 모든 행에 현재 세대
+ 지문을 다시 찍어서, 행 재생성으로 게이트가 이미 드롭한 낡은 선택·기각·픽셀편집이
+ **현재 세대 도장을 받아 부활**하고 새 프레임에 적용된다 — 그 부활한 selected 가 방향
+ 앵커까지 고른다 (validator 검증 2026-07-25 3차 기각 실측: 리롤 후 다른 방향 `--pick` 한 번에
+ `down_idle` 의 죽은 선택이 되살아나 `down` 앵커가 됐다). 게이트 도크스트링이 못박은
+ 불변식이 이거다 — "증명 없는 선택을 새 프레임에 적용하지 않는다"."""
+ from sprite_gen.curate.curation import empty_curation, load_curation_report, write_curation_atomic
+ from sprite_gen.spec.runio import publish_guard
+
+ if state is not None:
+ owner = state_direction(request, state)
+ if owner is None:
+ raise AnchorUnavailable(
+ "pick-wrong-direction",
+ f"anchor: '{state}' does not belong to a generated direction — only direction "
+ f"rows can own a direction anchor")
+ direction = owner
+ if direction is None:
+ raise SystemExit("anchor: --clear needs a direction (--direction <dir>)")
+ with publish_guard(run_dir):
+ doc = load_curation_report(run_dir)[0] or empty_curation()
+ anchors = {k: dict(v) for k, v in anchor_choices(doc).items()}
+ if state is None:
+ anchors.pop(direction, None)
+ else:
+ # `repin` = 명시 재지정 의도. CLI 로 찍는 건 언제나 사람이 방금 한 행동이므로
+ # 낡은 핀을 그 자리에서 푼다 (writer 가 소비·제거한다). 뷰는 stale 핀을 다시
+ # 누를 때만 이 플래그를 싣는다 (autosave 가 세탁하지 못하게).
+ anchors[direction] = {"state": state, "index": int(index), "repin": True}
+ # 커밋 전 검증 (Atomicity): 지정을 얹은 문서로 먼저 해석해 본다. 없는 인스턴스·
+ # 타 방향 프레임을 디스크에 남긴 뒤 죽으면, 사용자는 "지정은 됐는데 매번 에러"
+ # 상태에 갇힌다 (validator 검증 2026-07-25 파생 증상 1 — write 후 크래시로 잔류).
+ if state is not None:
+ resolve_anchor(request, {**doc, "anchors": anchors}, direction)
+ # 그 행이 아직 추출 전이면 지정 자체를 거부한다. 사람이 본 적 없는 프레임을
+ # 앵커로 찍을 수는 없고, 세대 지문도 계산되지 않아 저장하면 다음 로드에서
+ # "재생성됐다" 로 오분류돼 그 방향 생성이 막힌다 (validator 5차 기각 2 실측).
+ try:
+ path = frame_source_path(run_dir, request, doc, state, int(index))
+ except AnchorUnavailable as exc:
+ if not exc.pending:
+ raise
+ path = None
+ if path is None or not path.is_file():
+ raise AnchorUnavailable(
+ "row-not-extracted",
+ f"anchor: cannot pin {state}#{index} — that row is not extracted yet "
+ f"(nothing to look at, and the pin could not be verified later). Generate "
+ f"and extract '{state}' first, then pin the frame you approved")
+ doc["anchors"] = anchors
+ write_curation_atomic(run_dir, doc)
+ return {"direction": direction, "state": state, "index": index}
+
+
+def _parse_pick(value: str) -> tuple[str, int]:
+ state, sep, raw_index = str(value).rpartition("#")
+ if not sep or not raw_index.strip().lstrip("-").isdigit():
+ raise SystemExit(f"anchor: --pick expects <state>#<index> (e.g. down_idle#2), got: {value!r}")
+ return state, int(raw_index)
+
+
+def add_arguments(parser: argparse.ArgumentParser) -> None:
+ parser.add_argument("--run-dir", required=True, type=Path)
+ parser.add_argument("--direction", help="materialize this direction's anchor ref")
+ parser.add_argument("--all", dest="all_directions", action="store_true",
+ help="materialize every generated direction's anchor ref")
+ parser.add_argument("--for-state",
+ help="print the identity ref to attach when generating this state "
+ "(direction action row -> its anchor, anchor row/simple run -> base-source)")
+ parser.add_argument("--pick", metavar="STATE#INDEX",
+ help="pin this instance as its direction's anchor frame (curation.json anchors)")
+ parser.add_argument("--clear", action="store_true",
+ help="drop the pinned anchor frame (back to the anchor row's sequence head)")
+ parser.add_argument("--scale", type=int, default=ANCHOR_SCALE,
+ help=f"nearest-neighbour upscale of the ref image (default {ANCHOR_SCALE})")
+
+
+def run(run_dir: Path, direction: str | None = None, all_directions: bool = False,
+ for_state: str | None = None, pick: str | None = None, clear: bool = False,
+ scale: int = ANCHOR_SCALE) -> int:
+ run_dir = Path(run_dir).expanduser().resolve()
+ request = load_request(run_dir)
+ extra_targets: list[str] = []
+ if pick and clear:
+ raise SystemExit("anchor: --pick and --clear are mutually exclusive")
+ if pick:
+ state, index = _parse_pick(pick)
+ written = _write_anchor_pick(run_dir, request, state, index)
+ print(f"[anchor] {written['direction']} anchor frame pinned: {state}#{index}")
+ if direction and direction != written["direction"]:
+ # 지정 방향은 state 소유자에서 파생된다 (교차 방향 지정은 resolve_anchor 가 막는다).
+ # 사용자가 적은 --direction 과 어긋나면 조용히 넘기지 않는다 — 말하고 둘 다 굽는다.
+ print(f"[anchor] note: --direction {direction} does not own '{state}' — pinned "
+ f"{written['direction']} instead; baking both refs")
+ extra_targets = [written["direction"], direction]
+ else:
+ extra_targets = [written["direction"]]
+ direction = written["direction"]
+ elif clear:
+ written = _write_anchor_pick(run_dir, request, None, None, direction=direction)
+ print(f"[anchor] {written['direction']} anchor frame unpinned "
+ f"(back to the {anchor_state(request, written['direction'])} sequence head)")
+ direction = direction or written["direction"]
+ if for_state:
+ if for_state not in request.get("states", {}):
+ raise SystemExit(f"anchor: unknown state: {for_state}")
+ # 지정/해제가 굽기로 약속한 방향(교차 방향 경고 포함)을 먼저 처리한다 — 그냥
+ # early return 하면 "양쪽 굽는다" 는 안내가 거짓이 된다.
+ for target in extra_targets:
+ if target == state_direction(request, for_state):
+ continue # identity_ref 가 아래에서 어차피 굽는다
+ try:
+ materialize(run_dir, target, scale, request=request)
+ except AnchorUnavailable as exc:
+ if not exc.pending:
+ raise
+ print(f"[anchor] ref not baked yet: {exc}")
+ print(identity_ref(run_dir, for_state, request=request, quiet=True)
+ .relative_to(run_dir).as_posix())
+ return 0
+ targets = (directions(request) if all_directions
+ else (extra_targets or ([direction] if direction else [])))
+ if not targets:
+ raise SystemExit("anchor: pass --direction <dir>, --all, or --for-state <state>")
+ # 여러 방향을 도는 벌크(`--all`)는 **끝까지 돌고 나서** 한 번에 보고한다: 중간에 raise
+ # 하면 앞의 방향만 구운 채 죽어서 재실행 지점이 모호해진다 (validator 3차 note 1). 단건은
+ # 즉시 fail-loud 그대로다.
+ failures: list[AnchorUnavailable] = []
+ for target in targets:
+ try:
+ materialize(run_dir, target, scale, request=request)
+ except AnchorUnavailable as exc:
+ # 지정/해제는 사용자 의도라 이미 저장됐다. 그 행이 아직 추출 전이라 ref 를 못
+ # 굽는 건 실패가 아니라 정상 순서 — 이유를 밝히고 계속한다. 그 외에는 fail-loud.
+ # ref 를 **요구**하는 진입점(`--for-state`)은 위에서 예외 없이 통과해야 한다.
+ if (pick or clear) and exc.pending:
+ print(f"[anchor] ref not baked yet: {exc} — re-run this command right before "
+ f"generating a row of '{target}'")
+ continue
+ if len(targets) == 1:
+ raise
+ print(f"[anchor] {target}: {exc}")
+ failures.append(exc)
+ if failures:
+ # broken 이 하나라도 있으면 그 kind 로 분류한다 — 전부 pending 일 때만 pending.
+ worst = next((f for f in failures if not f.pending), failures[0])
+ raise AnchorUnavailable(
+ worst.kind,
+ f"anchor: {len(failures)} of {len(targets)} direction(s) could not be baked "
+ f"(the others were written; re-run for the rest): "
+ + " | ".join(str(exc) for exc in failures))
+ return 0
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
+ add_arguments(parser)
+ args = parser.parse_args(argv)
+ return run(**vars(args))
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/sprite_gen/curate/curation.py b/sprite_gen/curate/curation.py
new file mode 100644
index 0000000..8bd94d0
--- /dev/null
+++ b/sprite_gen/curate/curation.py
@@ -0,0 +1,1135 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Shared curation sidecar logic for sprite-gen.
+
+`curation.json` is an optional, non-destructive sidecar in a run directory. It
+records which extracted frames a human selected (and in what order), which
+frames were logically deleted, plus a per-frame affine transform. The original
+`frames/<state>/frame-N.png` files are never rewritten — the atlas/GIF compose
+steps read this sidecar and apply the transform at compose time, so a curation
+decision is always reversible by editing `curation.json`.
+
+This module is the single source of truth for the curation schema and for how a
+transform is applied, so the webview server and the compose scripts can never
+drift apart.
+
+Schema (`curation.json`):
+
+ {
+ "version": 1,
+ "kind": "sprite-gen-curation",
+ "run_revision": "9f3c1a0b7e2d4c58", # stamped at write = the frame generation this
+ # curation was made for. When it matches the
+ # current run, the whole sidecar applies
+ # (fast path). When it does not, each state
+ # is judged by its own `revision` stamp
+ # below — never silently applied wholesale.
+ "pixel_unfake": true, # optional run-wide DEFAULT; false -> compose
+ # reads the frame-N.plain.png variant (pre-
+ # pixel unfake). absent/true -> the
+ # canonical frame-N.png. Only
+ # meaningful when extraction saved
+ # both variants (fit.pixel_unfake).
+ "anchors": { # optional DIRECTION ANCHOR FRAME PICKS
+ "down": {"state": "down_idle", # (maintainer 2026-07-25): which curated instance
+ "index": 2, # is this direction's identity truth for
+ "revision": ["a1b2c3d4e5f6"] # generating its other rows. Any instance of any
+ } # row of that direction is allowed (a pool
+ }, # candidate too). Absent direction -> the anchor
+ # row's sequence head (explicit default).
+ # `revision` = the PINNED ROW's state_revision at
+ # pin time; when the row is later regenerated the
+ # gate marks the pin stale (never re-stamped, never
+ # silently followed to a new frame) and generation
+ # fails loud until it is re-picked.
+ # Resolution/bake SSoT = sprite_gen/curate/anchor.py.
+ "recolor": { # optional ADOPTED COLOURWAY: which baked
+ "picked": "crimson" # recolor variant (sprite_gen/effects/recolor.py,
+ }, # `<run>/variants/`) the human picked in the
+ # curation view. Keyed by variant NAME — a
+ # colourway survives re-baking, so unlike
+ # `anchors` this carries no generation stamp.
+ # A name no longer in the bake report is
+ # reported as unknown by the view, never
+ # silently cleared. Reader = recolor_pick().
+ "states": {
+ "<state>": {
+ "revision": ["a1b2c3d4e5f6"], # per-state generation stamp: ordered SOURCE-
+ # material segment digests (state_revision).
+ # Valid while it is a prefix of the current
+ # segments — an engine-upgrade heal of the
+ # same raw keeps it, a raw re-roll drops it.
+ "pixel_unfake": false, # optional per-state override of the run-wide
+ # default above (the curator's per-row
+ # toggle). absent -> the run-wide value.
+ "selected": [0, 1, 2, 3], # 0-based frame indices, in play order
+ # (may include clone instance indices)
+ "deleted": [4], # optional 0-based frame indices
+ # excluded from UI rows and bake.
+ "clones": {"12": 5}, # optional duplicate instances: new index ->
+ # source frame index. LINKED by default
+ # (maintainer 2026-07-18): a linked clone
+ # shares the SOURCE frame's transform and
+ # pixel edits (one edit truth — clones are
+ # play slots of the same frame). Clone
+ # indices live outside 0..frame_count-1.
+ "unlinked": [12], # optional clone indices explicitly detached
+ # ("링크 끊기"): they own their transforms/
+ # pixels independently (pre-2026-07-18
+ # clones with own edits are treated as
+ # unlinked by the webview on load).
+ "order": [0, 1, 2, 3, 4, 5], # optional, webview-owned; full display
+ # order (sequence then candidate pool).
+ # Restores the row arrangement on reload.
+ # Consumers key off `selected`; ignored here.
+ "breathe": { # optional idle-breathing POST-PROCESS LAYER
+ "depth": 0.06, # (maintainer 2026-07-18: breathing is a
+ "breaths": 1, # modulation ORTHOGONAL to frame selection —
+ "lag": 0.10, # a blink frame can breathe too).
+ "rigid_row": null, # depth = total stretch as a fraction of the
+ "anatomy": { # body height. breaths = breath count PER
+ "rigid_row": 58, # LOOP; the loop length never changes.
+ "neck_row": 49, # lag = travelling-wave phase delay, which is
+ "neck_source": "bottleneck", # what makes the head follow a beat late.
+ "face": [45, 57], # rigid_row = manual override of the rigid
+ "basis_row": 49, # boundary (null = auto-detected).
+ "axis_x": 35, #
+ "torso_half": 21, # `anatomy` is the detection result frozen at
+ "max_half": 28, # curation time so the bake and the webview
+ "width": 72, "height": 81, # read the same numbers instead of both
+ "rigid_source": "face", # re-implementing detection. `fingerprint`
+ "warnings": [], # pins the source it was derived from; on a
+ "fingerprint": "72x81:..." # mismatch the bake re-detects and refreshes
+ } # it (self-heal). A manual rigid_row survives
+ }, # regardless — that is intent, not a cache.
+ #
+ # `splits`/`amplitude`/`subpixel` are the
+ # retired split-line schema and are REJECTED
+ # loudly, never reinterpreted (2026-07-25).
+ # Compose/GIF bake deterministically; frames
+ # on disk never change, no re-extraction.
+ "transforms": { # keyed by 0-based frame index (string)
+ "0": {"rotate": 0.0, "scale": 1.0, "dx": 0, "dy": 0}
+ },
+ "pixels": { # optional per-frame pixel edits (sidecar,
+ "0": {"12,34": "#1f2430", # originals never rewritten): cell-coord
+ "13,34": null} # "x,y" -> paint hex | null = erase.
+ } # Applied before the transform at bake.
+ }
+ }
+ }
+
+Defaults when absent (explicit, not a silent fallback):
+- no `curation.json` -> every state uses all extracted frames in order, identity transform.
+- mismatched `run_revision` -> per-state salvage: each state entry whose `revision` stamp is a
+ prefix of the current state_revision segments is KEPT; entries
+ without a valid stamp are dropped. The drop is reported on stderr
+ and to the webview (load_curation_report) — stale edits are never
+ silently applied. The load itself writes nothing: `curation.json`
+ stays on disk untouched, and the copy to
+ `curation.stale-<hash>.json` (idempotent content-hash name) is
+ made by the writer that actually overwrites it
+ (`write_curation_atomic`) — never silently destroyed either.
+- `anchors` missing/direction absent -> that direction's anchor is the anchor row's curated
+ sequence head (`sprite_gen.curate.anchor.resolve_anchor`).
+- pinned row regenerated -> the pin is KEPT and marked `stale` by the load gate (reported in
+ `report["anchors_stale"]`), so resolution fails loud
+ (`pick-stale-generation`) instead of silently pointing the pin at
+ a brand-new frame the human never saw, and instead of silently
+ reverting to the sequence head. Re-pick to clear it.
+- state missing from sidecar -> same all-frames default for that state.
+- `selected` missing/empty -> all non-deleted frames in extraction order.
+- `deleted` missing -> no frames are deleted.
+- `order` missing -> webview rebuilds arrangement from `selected`; bake is unaffected (state_plan reads `selected`, never `order`).
+- frame missing from transforms -> identity transform.
+
+`rotate` is in degrees, counter-clockwise positive (PIL convention).
+`scale` is a multiplier about the frame center.
+`dx`/`dy` are pixel offsets inside the cell, +x right, +y down.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import math
+import sys
+from pathlib import Path
+from typing import Any
+
+from PIL import Image
+
+from sprite_gen.spec.layout import raw_rel
+from sprite_gen.spec.runio import load_request
+
+CURATION_FILENAME = "curation.json"
+SCHEMA_VERSION = 1
+IDENTITY = {"rotate": 0.0, "scale": 1.0, "dx": 0, "dy": 0, "shx": 0.0, "shy": 0.0, "flipX": 0}
+
+# Generation-material chip roles for imported `_refs/<role>-<name>.png` files
+# (run-contract.md §4). Single source shared by the importer (fail-loud on an
+# unknown role) and the webview server (render), so neither silently invents a role.
+IMPORTED_REF_ROLES = ("anchor", "basis", "guide")
+
+# 은퇴한 사이드카 키 -> 현행 키. `fit` 쪽과 같은 어휘 교체다 (runio.LEGACY_FIT_KEYS 참조):
+# "pixel perfect" 는 광의 통용어의 오용이고, 이 파이프라인이 하는 일의 정확한 명칭은
+# "unfake"(격자 스냅/재양자화로 가짜 픽셀아트를 되돌린다) 다 — maintainer 2026-07-25.
+LEGACY_CURATION_KEYS = {"pixel_perfect": "pixel_unfake"}
+
+
+def _migrate_curation_keys(doc: dict[str, Any], where: str) -> bool:
+ """은퇴 키를 현행 키로 옮긴다 (최상위 + 행별, in-place). 옮겼으면 True.
+
+ 두 키가 동시에 있으면 hard fail — 어느 쪽이 진실인지 코드가 고를 수 없다."""
+ moved = False
+ scopes = [("", doc)] + [(f"states.{name}.", entry)
+ for name, entry in (doc.get("states") or {}).items()
+ if isinstance(entry, dict)]
+ for prefix, scope in scopes:
+ for legacy, current in LEGACY_CURATION_KEYS.items():
+ if legacy not in scope:
+ continue
+ if current in scope:
+ raise SystemExit(
+ f"{where}: both `{prefix}{legacy}` (retired) and `{prefix}{current}` are "
+ f"present — two truths for one setting. Delete the `{prefix}{legacy}` line.")
+ scope[current] = scope.pop(legacy)
+ moved = True
+ return moved
+
+
+def imported_ref_role(filename: str) -> str | None:
+ """Role for an imported `_refs` filename `<role>-<name>.png`, or None if the
+ prefix is not a known role. Callers must handle None explicitly (the importer
+ fails loud, the server skips) — never silently relabel an unknown role."""
+ stem = Path(filename).stem
+ prefix = stem.split("-", 1)[0] if "-" in stem else ""
+ return prefix if prefix in IMPORTED_REF_ROLES else None
+
+
+def curation_path(run_dir: Path) -> Path:
+ return run_dir / CURATION_FILENAME
+
+
+# 폐기된 분할선 스키마 키. 조용히 무시하거나 재해석하지 않고 요란하게 거부한다 —
+# 제거된 결정이 필드 하나로 되살아나는 경로를 만들지 않기 위해서다 (docs/pixel-unfake.md
+# 의 `conform` 사고, 2026-07-17). splits 없이는 구 정규화가 None 을 냈으므로 구 설정은
+# 전부 이 게이트에 걸린다 — 조용히 다른 동작으로 바뀌는 사이드카는 없다.
+# 호흡 파라미터 허용 범위 — 큐레이터 컨트롤(`breathe.js` BREATHE_*_MAX)과 같은 값이어야
+# 한다. 둘이 갈리면 UI 가 만들 수 있는 값을 굽기가 거부한다.
+BREATHE_DEPTH_MAX = 0.20
+BREATHE_BREATHS_MAX = 8
+BREATHE_LAG_MAX = 0.45
+
+RETIRED_BREATHE_KEYS = {
+ "splits": "분할선은 봉투 경계로 대체됐다 — 경계는 자동 검출되고 `rigid_row` 로만 덮어쓴다",
+ "amplitude": "정수 px 진폭은 몸통 높이 비율 `depth` 로 대체됐다 (기본 0.06)",
+ "subpixel": "서브픽셀 중간색은 2상태 토글을 보정하려던 것이라 연속 위상에서 의미가 없다",
+ "hold": "구 분할선 스키마의 유지 프레임 수 — 위상이 연속이라 유지 개념이 없다",
+}
+
+
+def _exact_int(name: str, value: Any, state: str) -> int:
+ """정수만 받는다 — 2.7 이나 "3.5" 를 조용히 깎지 않는다.
+
+ 파이썬 `int()` 는 2.7 을 2 로 깎고 "3.5" 에는 예외를 던지는데, 미러의 `Math.round`
+ 는 3 과 4 를 낸다. 어느 쪽으로 맞추든 조용히 깎는 순간 프리뷰와 굽기가 갈리므로
+ **양쪽 다 거부**하는 쪽으로 정했다 (범위 밖 loud reject 와 같은 판단)."""
+ try:
+ number = float(value)
+ except (TypeError, ValueError):
+ raise SystemExit(f"curation: states.{state}.breathe.{name} 을 숫자로 못 읽는다: {value!r}")
+ if number != int(number):
+ raise SystemExit(
+ f"curation: states.{state}.breathe.{name} = {value!r} 가 정수가 아니다. "
+ f"조용히 깎지 않는다 — 프리뷰는 반올림하고 굽기는 버려서 서로 다른 애니메이션이 된다.")
+ return int(number)
+
+
+def state_breathe(curation: dict[str, Any] | None, state: str) -> dict[str, Any] | None:
+ """상태의 호흡 후처리 레이어 설정 (없으면 None) — 정규화·클램프 포함.
+
+ 호흡은 프레임 선택(깜빡임 등)과 직교하는 변조 레이어다 (maintainer 확정 2026-07-18).
+ 변형 수학은 봉투 기반 스쿼시&스트레치다 (2026-07-25 교체, `sprite_gen.effects.breathe`).
+ 반환: {"depth": float, "depth_x": float|None, "breaths": int, "lag": float,
+ "rigid_row": int|None, "anatomy": dict|None}
+ depth_x: 가로 독립 진폭 — None = depth 따름(레거시), 0 = 가로 항등.
+ compose/GIF 가 재생 시퀀스 위에 결정론으로 굽는다 — 디스크 프레임 불변."""
+ if not curation:
+ return None
+ entry = curation.get("states", {}).get(state)
+ raw = entry.get("breathe") if isinstance(entry, dict) else None
+ if not isinstance(raw, dict):
+ return None
+ retired = sorted(k for k in RETIRED_BREATHE_KEYS if k in raw)
+ if retired:
+ detail = "\n".join(f" - {k}: {RETIRED_BREATHE_KEYS[k]}" for k in retired)
+ raise SystemExit(
+ f"curation: states.{state}.breathe 에 폐기된 분할선 스키마 키가 있다: {', '.join(retired)}\n"
+ f"{detail}\n"
+ f" 마이그레이션: `sprite-gen migrate-breathe <run-dir> --apply` 또는 해당 키를 지우고 "
+ f"`depth`(기본 0.06)·`breaths`·`lag`(기본 0.10) 로 다시 적어라. 조용히 변환하지 않는다.")
+ # 형변환 계약(미러와 동일해야 한다): depth/lag 는 실수(숫자 문자열 허용),
+ # breaths/rigid_row 는 **정수여야 한다**. 2.7 을 조용히 2 로 깎으면 프리뷰(반올림 3)와
+ # 갈리고, "요청 그대로 적용된다" 는 문서도 거짓이 된다 (validator 실측 2026-07-25).
+ try:
+ depth = float(raw.get("depth", 0.06))
+ # 가로 독립 진폭 (2026-07-30 가로/세로 분리): None = depth 따름(레거시 동일),
+ # 0 = 가로 사상 항등. depth 와 달리 0 이 유효하다 — "가로만 끄기" 가 정당한 상태다.
+ raw_dx = raw.get("depth_x")
+ depth_x = None if raw_dx is None else float(raw_dx)
+ lag = float(raw.get("lag", 0.10))
+ breaths = _exact_int("breaths", raw.get("breaths", 1), state)
+ except (TypeError, ValueError) as exc:
+ # 폐기 키는 요란하게 거부하면서 형식 오류만 조용히 호흡을 꺼버리면 계약이 어긋난다
+ # — 둘 다 "이 사이드카는 그대로 못 쓴다" 이고, 조용한 쪽은 사용자가 못 알아챈다.
+ raise SystemExit(
+ f"curation: states.{state}.breathe 의 depth/breaths/lag 를 숫자로 못 읽는다: {exc}\n"
+ f" 받은 값: depth={raw.get('depth')!r} breaths={raw.get('breaths')!r} lag={raw.get('lag')!r}")
+ # 범위 밖은 **조용히 깎지 않는다.** 클램프는 파이썬에만 있어서 미러·배지·문서가 굽기와
+ # 다른 값을 말하게 됐다 (validator 실측 2026-07-25: breaths 12 를 8 로 깎는데 프리뷰·
+ # 필름스트립·WebM 은 12회 숨쉬고 배지는 "적용 12회" 라고 띄웠다). 폐기 키는 요란하게
+ # 거부하면서 값 범위만 조용한 것도 계약이 어긋난다.
+ ranged = [("depth", depth, 0.005, BREATHE_DEPTH_MAX),
+ ("breaths", breaths, 1, BREATHE_BREATHS_MAX),
+ ("lag", lag, 0.0, BREATHE_LAG_MAX)]
+ if depth_x is not None:
+ ranged.append(("depth_x", depth_x, 0.0, BREATHE_DEPTH_MAX))
+ for name, value, lo, hi in ranged:
+ if not lo <= value <= hi:
+ raise SystemExit(
+ f"curation: states.{state}.breathe.{name} = {value!r} 가 범위 [{lo}, {hi}] 밖이다. "
+ f"조용히 깎지 않는다 — 사이드카를 고쳐라 (큐레이터 컨트롤은 이 범위 안에서만 값을 낸다).")
+ rigid_row = raw.get("rigid_row")
+ if rigid_row is not None:
+ rigid_row = _exact_int("rigid_row", rigid_row, state)
+ # 영역 조정 오버라이드 (2026-07-30, 큐레이터 영역 UI): rigid_row 와 같은 지위의
+ # 사람 의도 입력 — anatomy 는 파생 캐시일 뿐이다. 범위 검증은 프레임을 아는
+ # anatomy.analyze 가 한다 (여기서는 정수성만).
+ axis_x = raw.get("axis_x")
+ if axis_x is not None:
+ axis_x = _exact_int("axis_x", axis_x, state)
+ torso_half = raw.get("torso_half")
+ if torso_half is not None:
+ torso_half = _exact_int("torso_half", torso_half, state)
+ frozen = raw.get("anatomy")
+ return {"depth": depth, "depth_x": depth_x, "breaths": breaths, "lag": lag,
+ "rigid_row": rigid_row, "axis_x": axis_x, "torso_half": torso_half,
+ "anatomy": frozen if isinstance(frozen, dict) else None}
+
+
+def edit_index(curation: dict[str, Any] | None, state: str, index: int) -> int:
+ """인스턴스의 편집(변형/픽셀) truth 인덱스 — 링크된 복제는 원본을 가리킨다.
+
+ 복제는 기본 링크 (maintainer 확정 2026-07-18): 같은 프레임의 재생 슬롯이므로 편집
+ SSoT 는 원본 하나다. `unlinked` 에 명시된 복제만 자기 편집을 소유한다.
+ 베이크(compose/GIF/export)와 웹뷰가 같은 규칙을 쓴다 (드리프트 금지)."""
+ if not curation:
+ return index
+ entry = curation.get("states", {}).get(state)
+ if not isinstance(entry, dict):
+ return index
+ clones = entry.get("clones")
+ if not isinstance(clones, dict):
+ return index
+ src = clones.get(str(index), clones.get(index))
+ if src is None:
+ return index
+ unlinked = entry.get("unlinked")
+ if isinstance(unlinked, list) and index in {int(u) for u in unlinked if str(u).lstrip("-").isdigit()}:
+ return index
+ # 레거시 자가판정 (웹뷰와 동일 규칙): 링크 개념(2026-07-18) 이전 사이드카가 복제
+ # 인덱스에 직접 넣어둔 변형/픽셀 편집은 독립 의도다 — 조용한 편집 소실 금지.
+ own_transform = (entry.get("transforms") or {}).get(str(index))
+ own_pixels = (entry.get("pixels") or {}).get(str(index))
+ if own_transform or (own_pixels and len(own_pixels)):
+ return index
+ try:
+ return int(src)
+ except (TypeError, ValueError):
+ return index
+
+
+def frame_variant(curation: dict[str, Any] | None, state: str | None = None) -> str:
+ """Which extracted frame variant consumers read: 'pixel' or 'plain'.
+
+ Resolution order (single source for every consumer):
+ 1. the state's own `states.<state>.pixel_unfake` (the curator's per-row toggle),
+ 2. the run-wide `pixel_unfake` default (the curator's toggle-all),
+ 3. absent sidecar / absent fields -> the canonical pixel unfakeed frames.
+
+ Called without `state` it resolves the run-wide default only (legacy callers,
+ single-state tools that pass their state explicitly elsewhere)."""
+ if not curation:
+ return "pixel"
+ if state is not None:
+ entry = curation.get("states", {}).get(state)
+ if isinstance(entry, dict) and isinstance(entry.get("pixel_unfake"), bool):
+ return "pixel" if entry["pixel_unfake"] else "plain"
+ if curation.get("pixel_unfake") is False:
+ return "plain"
+ return "pixel"
+
+
+def frame_filename(index: int, variant: str = "pixel") -> str:
+ """Frame file name for a variant. 'pixel' = canonical frame-N.png; 'plain'
+ = the pre-unfake twin saved by extraction when fit.pixel_unfake."""
+ if variant == "plain":
+ return f"frame-{index}.plain.png"
+ return f"frame-{index}.png"
+
+
+def pixel_snap_scale(request: dict[str, Any]) -> int | None:
+ """Logical-grid scale (cell px per logical px) for a `fit.pixel_unfake` run, or None
+ for a legacy run. Mirrors extract's pp_scale so a curation transform baked onto the
+ canonical pixel frames re-snaps to the SAME grid the extraction snapped to. Single
+ source for compose/GIF/PNG-export/cycle, the extraction itself, and the webview
+ preview — every consumer calls this instead of re-deriving the formula (hand copies
+ drifted: the webview omitted the usable-height clamp branch entirely)."""
+ fit = request.get("fit") or {}
+ if not fit.get("pixel_unfake"):
+ return None
+ cell = request.get("cell", {})
+ cell_height = int(cell.get("height", cell.get("size", 0)))
+ margin_y = int(cell.get("safe_margin_y", cell.get("safe_margin", 0)))
+ usable_height = max(1, cell_height - margin_y * 2)
+ logical_height = int(fit.get("logical_height", cell_height))
+ scale = max(1, cell_height // max(1, logical_height))
+ if logical_height * scale > cell_height:
+ scale = max(1, usable_height // max(1, logical_height))
+ return scale
+
+
+def effective_logical_height(request: dict[str, Any]) -> int | None:
+ """엔진이 **실제로** 쓰는 논리 높이 = 셀 높이 / 파생 배율. 선언값이 아니다.
+
+ 격자 배율은 정수라, 셀 높이의 약수가 아닌 `fit.logical_height` 는 선언대로 적용될
+ 수 없다 — 셀 64 에 48 을 선언하면 배율은 `64//48 = 1` 이 되어 논리 높이가 64 로
+ 되돌아간다 (선언은 무효, 회귀 hero synthetic fixtures: conform 눌림이 제거된 뒤로
+ 48 은 아무 픽셀도 바꾸지 않으면서 웹뷰 라벨만 "48px" 로 거짓 표기했다, 2026-07-25).
+ 소비자는 선언값 대신 이 값을 보고, 추출은 선언이 무효화되면 경고로 관측시킨다."""
+ scale = pixel_snap_scale(request)
+ if scale is None:
+ return None
+ cell = request.get("cell", {})
+ cell_height = int(cell.get("height", cell.get("size", 0)))
+ return max(1, cell_height // scale)
+
+
+def run_revision(run_dir: Path) -> str:
+ """Frame-content fingerprint of the run's current generation: the request + frames
+ manifest bytes plus each canonical frame file's name/size/mtime. It changes whenever
+ the frames are (re)written (`--force` re-import, re-extract), so a curation sidecar
+ stamped for a prior generation is detected as stale. Single source of run identity for
+ the server, compose, export, and the webview."""
+ h = hashlib.sha256()
+ for name in ("sprite-request.json", "frames/frames-manifest.json"):
+ try:
+ h.update((run_dir / name).read_bytes())
+ except OSError:
+ h.update(b"\0")
+ frames_root = run_dir / "frames"
+ if frames_root.is_dir():
+ # 재귀 걷기 — 택소노미(frames/<dir>/<pose>/)와 flat 레거시 둘 다 커버.
+ # orig/ 표시 쌍둥이는 세대 정체성에 불포함 (레거시 스탬프와 동일 규칙).
+ for frame in sorted(frames_root.rglob("frame-*.png")):
+ if frame.name.endswith(".plain.png") or frame.parent.name == "orig":
+ continue
+ try:
+ st = frame.stat()
+ rel = frame.relative_to(frames_root).as_posix()
+ h.update(f"{rel}:{st.st_size}:{st.st_mtime_ns}".encode())
+ except OSError:
+ pass
+ return h.hexdigest()[:16]
+
+
+# raw/프레임 파일 내용 다이제스트 캐시 — (path, size, mtime_ns) 가 같으면 재해시하지
+# 않는다. state_revision 이 서버 요청마다 불리므로 MB 급 raw 재해시를 피한다.
+_CONTENT_DIGEST_CACHE: dict[tuple[str, int, int], str] = {}
+
+
+def _file_content_digest(path: Path) -> str | None:
+ """파일 내용 sha256 12자리 (mtime/size 키 메모이즈). 없으면 None."""
+ try:
+ st = path.stat()
+ except OSError:
+ return None
+ key = (str(path), st.st_size, st.st_mtime_ns)
+ cached = _CONTENT_DIGEST_CACHE.get(key)
+ if cached is None:
+ try:
+ cached = hashlib.sha256(path.read_bytes()).hexdigest()[:12]
+ except OSError:
+ return None
+ _CONTENT_DIGEST_CACHE[key] = cached
+ return cached
+
+
+def state_revision(run_dir: Path, state: str, request: dict[str, Any] | None = None,
+ row: dict[str, Any] | None = None) -> list[str] | None:
+ """행(state) 단위 세대 지문 — 순서 있는 원료(source-material) 세그먼트 다이제스트 리스트.
+
+ 세그먼트 = 그 행의 프레임 인덱스 공간을 만드는 원료 단위: primary raw, 그리고 선언
+ 순서의 take raw (manifest row `takes` 가 SSoT). raw 가 아예 없는 임포트 행은 프레임
+ 파일 내용 자체가 원료다. 다이제스트 입력은 원료의 **내용**(sha256)·세그먼트 프레임
+ 수·셀/픽셀 언페이크 기하이고, frames/ 캐시의 mtime 이나 엔진 리비전은 넣지 않는다 —
+ 엔진 업그레이드 heal 이 같은 raw 를 재유도해도 지문이 유지돼 큐레이션이 살아남고,
+ raw 리롤·테이크 교체·셀 변경은 지문을 바꾼다.
+
+ 유효성 규칙 (load_curation_report): 저장 리스트가 현재 리스트의 접두(prefix)면 유효.
+ 테이크가 끝에 추가돼도 기존 프레임 인덱스 공간이 밀리지 않으므로 선택이 유지된다.
+ manifest row 가 없으면 None (검증 불가 — 그 행 큐레이션은 살릴 수 없다)."""
+ try:
+ if request is None:
+ request = load_request(run_dir)
+ except (OSError, json.JSONDecodeError):
+ return None
+ if state not in (request.get("states") or {}):
+ return None
+ if row is None:
+ try:
+ manifest = json.loads(
+ (run_dir / "frames" / "frames-manifest.json").read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError):
+ return None
+ row = next((r for r in manifest.get("rows", []) if r.get("state") == state), None)
+ if not isinstance(row, dict):
+ return None
+ cell = request.get("cell", {})
+ fit = request.get("fit") or {}
+ # 기하 세그먼트는 **파생된 격자 배율**을 넣는다 — 선언값(`fit.logical_height`)이 아니다.
+ # 선언값을 넣으면 추출 출력이 한 픽셀도 안 바뀌는 선언 편집이 전 행 큐레이션을 무효화
+ # 한다 (회귀 hero synthetic_fixture_b 2026-07-25: 셀 64 에서 무효값 48 을 지웠을 뿐인데 배율은
+ # 1 그대로, 프레임은 바이트 동일이었는데도 14행이 통째로 드롭됐다). 지문은 "엔진이
+ # 실제로 만들 격자"만 보면 되고, 그게 `pixel_snap_scale` 이다.
+ # 주의: 이 basis 문자열이 바뀌면서 배율 표기 방식이 한 번 바뀐다 (v1.57.1). run_revision
+ # fast-path 가 맞는 사이드카는 영향 없고, 이미 세대가 어긋난 사이드카만 첫 로드에서
+ # 평소대로 드롭 + stale 백업된다 (조용히 재해석하지 않는다 — 원칙 6).
+ basis = (f"{cell.get('width', cell.get('size'))}x{cell.get('height', cell.get('size'))}"
+ f":pp={1 if fit.get('pixel_unfake') else 0}:scale={pixel_snap_scale(request)}")
+ segments = row.get("takes")
+ if not segments:
+ segments = [{
+ "label": None, "start": 0,
+ "frames": row.get("frames", len(row.get("files") or [])),
+ "raw": raw_rel(request, state),
+ }]
+ digests: list[str] = []
+ for seg in segments:
+ raw_path = run_dir / str(seg.get("raw", ""))
+ content = _file_content_digest(raw_path) if seg.get("raw") else None
+ if content is None:
+ # 임포트 행 (raw 없음): 세그먼트가 낳은 프레임 파일 내용이 곧 원료.
+ start = int(seg.get("start", 0))
+ count = int(seg.get("frames", 0))
+ parts = []
+ for rel in (row.get("files") or [])[start:start + count]:
+ parts.append(_file_content_digest(run_dir / rel) or "missing")
+ content = hashlib.sha256("|".join(parts).encode()).hexdigest()[:12]
+ h = hashlib.sha256(
+ f"{seg.get('label') or ''}:{seg.get('raw') or ''}:{content}"
+ f":{int(seg.get('frames', 0))}:{basis}".encode())
+ digests.append(h.hexdigest()[:12])
+ return digests
+
+
+def backup_stale_curation(run_dir: Path, raw_text: str) -> str:
+ """덮여 사라질 큐레이션 원문을 `curation.stale-<hash>.json` 으로 보존 — **writer 전용**.
+
+ 파일명이 내용 해시라 멱등 — 같은 원문은 한 번만 남고, 정상 편집 흐름에서는 절대
+ 생기지 않는다. 사람이 나중에 열어 selected/transforms 를 수동 복원할 수 있는
+ 관측 가능한 안전망이다 (백업 없는 원자 덮어쓰기 금지).
+
+ **조회 경로는 이걸 부르지 않는다.** 예전엔 `load_curation_report` 가 세대 불일치로 행을
+ 드롭할 때 여기서 백업을 썼다 — 읽기만 해도 런 디렉터리에 새 파일이 생겼다는 뜻이고,
+ 그건 이 플랜이 request 로더에서 잡은 것과 같은 계열의 "조회가 런에 쓴다" 였다. 드롭은
+ 메모리 판정일 뿐 그 시점에 사라지는 것은 없다 (`curation.json` 은 디스크에 그대로다).
+ 실제로 원문이 사라지는 순간은 `write_curation_atomic` 의 덮어쓰기 하나뿐이고, 백업은
+ 그 writer 한 곳에서만 일어난다."""
+ digest = hashlib.sha256(raw_text.encode("utf-8")).hexdigest()[:8]
+ name = f"curation.stale-{digest}.json"
+ path = run_dir / name
+ if not path.exists():
+ path.write_text(raw_text, encoding="utf-8")
+ return name
+
+
+def _validated_anchor_pins(run_dir: Path, data: dict[str, Any], request: dict[str, Any] | None,
+ report: dict[str, Any]) -> dict[str, Any]:
+ """앵커 지정을 검증해 `stale` 표식을 붙여 돌려준다 (드롭하지 않는다).
+
+ 드롭하면 지정이 조용히 사라져 기본값(시퀀스 헤드)으로 복귀하고, 그냥 이월하면 지정이 새
+ 세대의 전혀 다른 프레임에 조용히 옮겨 붙는다 — 둘 다 금지다. 표식을 달아두면
+ `sprite_gen.curate.anchor.resolve_anchor` 가 fail-loud 하고 뷰가 이유를 보여준다 (validator 4차 기각:
+ 핀한 행을 리롤하면 사용자가 본 적 없는 프레임이 '당신이 핀한 앵커'로 표시됐다)."""
+ anchors_out: dict[str, Any] = {}
+ for direction, pick in anchor_choices(data).items():
+ stored = pick.get("revision")
+ current = state_revision(run_dir, pick["state"], request=request) if request else None
+ fresh = (isinstance(stored, list) and stored and current
+ and stored == current[:len(stored)])
+ entry = {"state": pick["state"], "index": pick["index"]}
+ if stored is not None:
+ entry["revision"] = stored
+ if not fresh:
+ entry["stale"] = True
+ # 왜 낡았나를 구분한다: 재생성됐다(지문 불일치) vs 애초에 증명이 없다(지문 없음).
+ # 후자에 "재생성됐다" 라고 말하면 사실과 다른 오류가 된다 (validator 5차 기각 2).
+ entry["stale_reason"] = "regenerated" if stored is not None else "unverifiable"
+ report["anchors_stale"].append(direction)
+ anchors_out[direction] = entry
+ return anchors_out
+
+
+def _report_stale_anchors(run_dir: Path, report: dict[str, Any]) -> None:
+ if not report["anchors_stale"]:
+ return
+ print(f"[curation] anchor pin(s) can no longer be proven against the current frames: "
+ f"{', '.join(report['anchors_stale'])} — generation fails loud until they are re-picked "
+ f"(they are NOT silently reverted to the sequence head, and NOT silently re-stamped): "
+ f"{run_dir}", file=sys.stderr)
+
+
+def load_curation_report(run_dir: Path) -> tuple[dict[str, Any] | None, dict[str, Any]]:
+ """사이드카 로드 + 세대 검증 보고 — **읽기만 한다** (run dir 바이트 불변). Returns (doc|None, report).
+
+ report = {"dropped": [state...], "anchors_stale": [direction...]}. 규칙:
+ - run_revision 이 현재와 일치 → 문서 전체 유효 (fast path, dropped 없음).
+ - 불일치 → 행 단위 구제: `revision` 스탬프가 현재 state_revision 의 접두인 행만
+ 유지, 나머지는 드롭. 드롭이 하나라도 있으면 stderr 로 보고한다. 전 행이 드롭되면
+ doc 은 None (전량 기본값).
+ 스탬프 없는 행(레거시/수동 편집)은 불일치 세대에서 검증 불가 → 드롭 (No Silent
+ Fallback — 증명 없는 선택을 새 프레임에 적용하지 않는다).
+
+ 드롭은 **이 로드가 무엇을 적용하지 않을지**에 대한 판정이지 파일 삭제가 아니다:
+ `curation.json` 은 그대로 남아 있고, 실제로 덮이는 순간 `write_curation_atomic` 이
+ `curation.stale-<hash>.json` 백업을 남긴다. 그래서 조회는 백업을 쓰지 않는다 — 조회가
+ 런 디렉터리에 파일을 만들면 그것도 "조회가 런에 쓴다" 다
+ (plan sprite-gen/state-revision-read-mutation)."""
+ path = curation_path(run_dir)
+ report: dict[str, Any] = {"dropped": [], "anchors_stale": []}
+ if not path.is_file():
+ return None, report
+ raw_text = path.read_text(encoding="utf-8")
+ data = json.loads(raw_text)
+ if data.get("kind") != "sprite-gen-curation":
+ raise SystemExit(f"{path} is not a sprite-gen-curation file")
+ # 은퇴 키 이관 (메모리) — 다음 저장이 현행 키로 파일을 갱신한다. 두 키 동시 = hard fail.
+ _migrate_curation_keys(data, str(path))
+ try:
+ request = load_request(run_dir)
+ except (OSError, json.JSONDecodeError):
+ request = None
+ # 앵커 지정 검증은 **fast path 와 무관하게 항상** 돈다. run_revision 은 "이 문서를 쓴
+ # 시점 = 지금 프레임 세대" 를 뜻할 뿐, 그 문서 안 지정의 스탬프가 그 세대라는 증명이
+ # 아니다: 낡은 핀을 안은 채 다른 편집을 저장하면 문서 지문만 새것이 되고, fast path 는
+ # 그 문서를 통째로 유효하다고 통과시켜 낡은 핀이 살아난다 (validator 5차 실측 — provenance
+ # 이월만으로는 못 막았다. 게이트가 건너뛰면 이월된 증거를 아무도 안 본다).
+ anchors_out = _validated_anchor_pins(run_dir, data, request, report)
+ if data.get("run_revision") == run_revision(run_dir) and not report["anchors_stale"]:
+ return ({**data, **({"anchors": anchors_out} if anchors_out else {})}, report)
+ if data.get("run_revision") == run_revision(run_dir):
+ # 프레임 세대는 현재지만 지정 하나가 낡았다 — states 는 전부 유효하다.
+ _report_stale_anchors(run_dir, report)
+ return ({**data, "anchors": anchors_out}, report)
+ kept: dict[str, Any] = {}
+ for name, entry in (data.get("states") or {}).items():
+ entry_rev = entry.get("revision") if isinstance(entry, dict) else None
+ current = state_revision(run_dir, name, request=request) if request else None
+ if (isinstance(entry_rev, list) and entry_rev and current
+ and entry_rev == current[:len(entry_rev)]):
+ kept[name] = entry
+ else:
+ report["dropped"].append(name)
+ if not report["dropped"] and not report["anchors_stale"]:
+ # 런 세대 지문은 바뀌었지만 (예: request 메타 편집) 전 행이 개별 검증을 통과.
+ return {**data, "states": kept, **({"anchors": anchors_out} if anchors_out else {})}, report
+ if report["dropped"]:
+ print(f"[curation] frames regenerated under {CURATION_FILENAME}: dropped "
+ f"{', '.join(report['dropped'])} (kept {len(kept)}); the file itself is unchanged "
+ f"until the next save, which backs it up to curation.stale-<hash>.json: {run_dir}",
+ file=sys.stderr)
+ _report_stale_anchors(run_dir, report)
+ if not kept and not anchors_out:
+ return None, report
+ # 전 행이 드롭돼도 지정은 남긴다 — 남아 있어야 오류를 낼 수 있다.
+ return {**data, "states": kept, **({"anchors": anchors_out} if anchors_out else {})}, report
+
+
+def load_curation(run_dir: Path) -> dict[str, Any] | None:
+ """The single gate every consumer (server, compose, export, GIF) passes through.
+ Thin wrapper over load_curation_report — see it for the per-state salvage +
+ backup semantics."""
+ return load_curation_report(run_dir)[0]
+
+
+def stamp_curation(run_dir: Path, payload: dict[str, Any]) -> dict[str, Any]:
+ """쓰기 직전 세대 도장. run_revision(런 전체 fast-path 지문) + 행별 `revision`
+ (state_revision 세그먼트 지문) 을 payload 사본에 찍어 반환한다. `runRevision`
+ (transport echo) 은 제거. 행 스탬프가 계산 불가(행 미생성)면 스탬프를 지운다 —
+ 거짓 증명을 남기지 않는다."""
+ payload = {k: v for k, v in payload.items() if k != "runRevision"}
+ payload["run_revision"] = run_revision(run_dir)
+ try:
+ request = load_request(run_dir)
+ except (OSError, json.JSONDecodeError):
+ request = None
+ anchors = payload.get("anchors")
+ if isinstance(anchors, dict):
+ for direction, pick in list(anchors.items()):
+ if not isinstance(pick, dict) or not isinstance(pick.get("state"), str):
+ continue
+ for derived in ("stale", "stale_reason", "repin"):
+ pick.pop(derived, None) # 파생/의도 표식은 저장하지 않는다 (게이트가 재판정)
+ # **없을 때만** 찍는다: 이월되는 기존 지정에 현재 지문을 다시 찍으면 낡은 지정이
+ # 새 세대에서 유효해져 버린다 (states 부활과 같은 병). 새 지정(revision 없음)만
+ # 지금 세대로 도장받는다. 계산 불가(그 행 미추출)면 스탬프를 남기지 않는다 —
+ # states 와 같은 규칙(거짓 증명 금지)이고, 게이트가 그걸 unverifiable 로 읽는다.
+ if pick.get("revision") is None:
+ rev = state_revision(run_dir, pick["state"], request=request) if request else None
+ if rev:
+ pick["revision"] = rev
+ else:
+ pick.pop("revision", None)
+ states = payload.get("states")
+ if isinstance(states, dict):
+ for name, entry in states.items():
+ if not isinstance(entry, dict):
+ continue
+ rev = state_revision(run_dir, name, request=request) if request else None
+ if rev:
+ entry["revision"] = rev
+ else:
+ entry.pop("revision", None)
+ return payload
+
+
+def normalize_transform(raw: Any) -> dict[str, float]:
+ """Coerce a stored transform into a full {rotate, scale, dx, dy, shx, shy, flipX} dict."""
+ if not isinstance(raw, dict):
+ return dict(IDENTITY)
+ return {
+ "rotate": float(raw.get("rotate", 0.0)),
+ "scale": float(raw.get("scale", 1.0)),
+ "dx": float(raw.get("dx", 0)),
+ "dy": float(raw.get("dy", 0)),
+ "shx": float(raw.get("shx", 0.0)),
+ "shy": float(raw.get("shy", 0.0)),
+ # (maintainer 2026-05-28) flipX: 0 | 1 — horizontal mirror. Image-gen 결과가 좌우
+ # 반대로 나올 때 frame 별로 거울 반전. matrix 마지막에 diag(-1, 1) 곱.
+ "flipX": 1 if raw.get("flipX") else 0,
+ }
+
+
+def is_identity(transform: dict[str, float]) -> bool:
+ return (
+ abs(transform["rotate"]) < 1e-6
+ and abs(transform["scale"] - 1.0) < 1e-6
+ and abs(transform["dx"]) < 1e-6
+ and abs(transform["dy"]) < 1e-6
+ and abs(transform.get("shx", 0.0)) < 1e-6
+ and abs(transform.get("shy", 0.0)) < 1e-6
+ and not transform.get("flipX", 0)
+ )
+
+
+def normalize_frame_indices(raw: Any, default_count: int,
+ extra_valid: set[int] | None = None) -> list[int]:
+ """Return unique 0-based frame indices that are valid for this state.
+ `extra_valid` admits clone instance indices (outside the physical range)."""
+ if not isinstance(raw, list):
+ return []
+ indices: list[int] = []
+ seen: set[int] = set()
+ extra = extra_valid or set()
+ for value in raw:
+ try:
+ index = int(value)
+ except (TypeError, ValueError):
+ continue
+ if (0 <= index < default_count or index in extra) and index not in seen:
+ indices.append(index)
+ seen.add(index)
+ return indices
+
+
+def state_clones(curation: dict[str, Any] | None, state: str, default_count: int) -> dict[int, int]:
+ """행의 복제 인스턴스 맵 {복제 인덱스: 원본 프레임 인덱스}.
+
+ 복제 인덱스는 물리 프레임 범위(0..default_count-1) 밖의 정수, 원본은 범위 안이어야
+ 한다. 복제는 자기만의 order 슬롯/변형/픽셀편집을 갖는 정식 인스턴스이고, 굽기 때
+ 원본 프레임 파일을 읽는다 (frames/ 는 파생 캐시라 복제 파일을 만들지 않는다 —
+ 복제 의도는 사이드카가 소유). 손상 항목은 스킵."""
+ entry = ((curation or {}).get("states") or {}).get(state)
+ raw = entry.get("clones") if isinstance(entry, dict) else None
+ clones: dict[int, int] = {}
+ if isinstance(raw, dict):
+ for key, value in raw.items():
+ try:
+ clone_idx, src = int(key), int(value)
+ except (TypeError, ValueError):
+ continue
+ if clone_idx >= default_count and 0 <= src < default_count:
+ clones[clone_idx] = src
+ return clones
+
+
+def source_frame_index(curation: dict[str, Any] | None, state: str,
+ index: int, default_count: int) -> int:
+ """인스턴스 인덱스 → 실제 프레임 파일 인덱스 (복제면 원본, 아니면 자기 자신).
+ 소비자는 파일을 열 때만 이 리졸버를 쓰고, transforms/pixels 는 인스턴스
+ 인덱스로 그대로 조회한다 — 복제마다 다른 변형이 가능해야 하므로."""
+ return state_clones(curation, state, default_count).get(index, index)
+
+
+def state_instances(curation: dict[str, Any] | None, state: str, default_count: int) -> list[int]:
+ """행의 **살아있는 인스턴스** 전체 (물리 프레임 + 복제, 보관분 제외).
+
+ 시퀀스(state_plan)와 다르다: 후보 풀에 있는(선택 안 된) 프레임도 포함한다.
+ "선택되진 않았지만 존재하는 인스턴스" 를 물어야 하는 소비자 — 앵커 프레임 지정
+ 검증(sprite_gen.curate.anchor) — 의 SSoT."""
+ clones = state_clones(curation, state, default_count)
+ entry = ((curation or {}).get("states") or {}).get(state)
+ deleted: set[int] = set()
+ if isinstance(entry, dict):
+ deleted = set(normalize_frame_indices(entry.get("deleted"), default_count, set(clones)))
+ return [index for index in [*range(default_count), *sorted(clones)] if index not in deleted]
+
+
+def anchor_choices(curation: dict[str, Any] | None) -> dict[str, dict[str, Any]]:
+ """방향 앵커 프레임 지정 — {direction: {"state": str, "index": int}}.
+
+ 사용자가 큐레이션 뷰에서 "이 프레임을 앵커로" 라고 지정한 것 (maintainer 2026-07-25).
+ 지정이 없는 방향은 여기 없다 = 앵커 행의 시퀀스 첫 인스턴스가 앵커라는 뜻.
+ 손상 항목은 스킵 (손으로 편집된 사이드카가 크래시를 내지 않는다) — 지정이 가리키는
+ 인스턴스의 **실재 검증은 해석 시점**(sprite_gen.curate.anchor.resolve_anchor)에 fail-loud."""
+ raw = (curation or {}).get("anchors")
+ picks: dict[str, dict[str, Any]] = {}
+ if isinstance(raw, dict):
+ for direction, value in raw.items():
+ if not isinstance(value, dict):
+ continue
+ state = value.get("state")
+ try:
+ index = int(value.get("index"))
+ except (TypeError, ValueError):
+ continue
+ if isinstance(state, str) and state:
+ pick = {"state": state, "index": index}
+ # 세대 지문 (쓰기 시 stamp_curation 이 찍는다) + 로드 게이트가 붙인 stale 표식.
+ # stale 은 파생값이라 파일에 쓰지 않는다 — 게이트가 매번 다시 판정한다.
+ if value.get("revision") is not None:
+ pick["revision"] = value["revision"]
+ if value.get("stale"):
+ pick["stale"] = True
+ pick["stale_reason"] = str(value.get("stale_reason") or "regenerated")
+ if value.get("repin"):
+ pick["repin"] = True # 명시 재지정 의도 (쓰기 경로에서 소비·제거)
+ picks[str(direction)] = pick
+ return picks
+
+
+def recolor_pick(curation: dict[str, Any] | None) -> str | None:
+ """The adopted recolor variant name, or None when none is picked.
+
+ Keyed by VARIANT NAME, not by a frame generation: a colourway ("crimson") is a
+ decision about colour, and re-baking the same spec against re-curated frames
+ produces the same colourway. So this pick is deliberately NOT stamped with a
+ run/state revision the way anchor pins are — there is nothing about new frames
+ that could make "crimson" the wrong answer to "which colourway".
+
+ What CAN go wrong is the name disappearing from the spec. That is not resolved
+ here: the pick is returned as stored, and the reader (the curation view via
+ `serve_curation`) reports it as unknown against the current bake report instead
+ of silently clearing it (No Silent Fallback)."""
+ raw = (curation or {}).get("recolor")
+ if not isinstance(raw, dict):
+ return None
+ picked = raw.get("picked")
+ return picked if isinstance(picked, str) and picked else None
+
+
+def _carry_anchor_provenance(run_dir: Path, payload: dict[str, Any]) -> dict[str, Any]:
+ """앵커 지정의 세대 지문(`revision`)은 **엔진 소유**다 — 쓰는 쪽이 들고 오지 않는다.
+
+ 이미 파일에 있는 같은 지정(direction+state+index 동일)은 저장된 지문을 그대로 이월한다.
+ **stale 이어도 이월한다** — 그게 fail-safe 다. 지문을 왕복시키지 않는 writer(뷰 autosave 는
+ `{state, index}` 만 싣는다)가 있으면, 지문 없는 지정이 stamp 단계에서 현재 세대 도장을
+ 받아 **낡은 핀이 유효해지고 오류 배너가 사라진다** — 즉 무관한 편집 한 번이 4차에서 세운
+ fail-loud 계약을 세탁한다 (validator 5차 기각 실측: 리롤 후 side_walk 프레임 하나 삭제·저장에
+ down 핀이 새 세대 프레임으로 조용히 옮겨 붙었다).
+
+ 낡은 핀을 푸는 유일한 길은 **명시적 재지정**이다: payload 의 그 지정에 `repin: true` 가
+ 실려 있어야 새 지문을 받는다 (뷰의 핀 버튼이 stale 상태에서 그걸 싣는다). 잊은 writer 는
+ 지정을 낡은 상태로 남기므로 오류가 유지된다 — 조용히 유효해지는 쪽으로 실패하지 않는다.
+ """
+ anchors = payload.get("anchors")
+ if not isinstance(anchors, dict) or not anchors:
+ return payload
+ try:
+ old = json.loads((run_dir / CURATION_FILENAME).read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError):
+ return payload
+ stored = anchor_choices(old)
+ payload = {**payload, "anchors": {k: dict(v) if isinstance(v, dict) else v
+ for k, v in anchors.items()}}
+ for direction, pick in payload["anchors"].items():
+ if not isinstance(pick, dict):
+ continue
+ prior = stored.get(direction)
+ if pick.pop("repin", None):
+ pick.pop("revision", None) # 명시 재지정 = 지금 세대로 새로 도장받는다
+ continue
+ if (prior and prior["state"] == pick.get("state")
+ and prior["index"] == pick.get("index") and prior.get("revision") is not None):
+ pick["revision"] = prior["revision"]
+ return payload
+
+
+def write_curation_atomic(run_dir: Path, payload: dict[str, Any]) -> str | None:
+ """Atomically replace curation.json (temp file in the same dir + os.replace). Stamps the
+ sidecar with the current run generation (`run_revision`) AND per-state `revision`
+ segment fingerprints (stamp_curation), so a later regeneration invalidates only the
+ rows it actually touched. Before replacing, any state entry in the existing file that
+ this write would lose (missing from the payload, or stamped for an incompatible
+ generation) triggers a `curation.stale-<hash>.json` backup of the old file — an
+ autosave can never permanently destroy selections without an observable copy.
+ `runRevision` is a transport-only echo field and is not stored.
+
+ Returns the backup filename when one was written, else None — this is the **single
+ place** a stale backup is created, so it is also the single place that can report one.
+ The load gate deliberately does not back up: a generation-mismatched read drops rows
+ from *this load*, but nothing is lost until an overwrite, and a read that creates a
+ file in the run dir is itself a read-that-writes
+ (plan sprite-gen/state-revision-read-mutation).
+
+ Sidecar write semantics live with the sidecar schema (this module) so every writer —
+ the webview POST and the `sprite-gen anchor --pick` CLI — stamps and backs up
+ identically. Callers own the run-dir lock (publish_guard)."""
+ import os
+ import tempfile
+
+ backup: str | None = None
+
+ if payload.get("kind") != "sprite-gen-curation":
+ raise ValueError("payload is not a sprite-gen-curation document")
+ _migrate_curation_keys(payload, str(run_dir / CURATION_FILENAME))
+ payload = _carry_anchor_provenance(run_dir, payload)
+ payload = stamp_curation(run_dir, payload)
+ if isinstance(payload.get("anchors"), dict) and not payload["anchors"]:
+ payload.pop("anchors") # 빈 지정은 기록하지 않는다 (없음 = 기본값, 같은 뜻)
+ target = run_dir / CURATION_FILENAME
+ if target.is_file():
+ old_text = target.read_text(encoding="utf-8")
+ try:
+ old = json.loads(old_text)
+ except json.JSONDecodeError:
+ old = None
+ if isinstance(old, dict):
+ # 앵커 지정의 **소실**도 states 와 같은 무게로 다룬다 (백업 대칭): 뷰가 열린 채
+ # CLI `--pick` 으로 심은 지정은 뷰의 다음 autosave 가 통째로 덮을 수 있고
+ # (뷰가 authoritative 인 건 다른 필드와 같은 semantics 지만), 관측 가능한 사본이
+ # 없으면 사용자가 사라진 지정을 되찾을 방법이 없다. **사라짐(direction 이 새
+ # 문서에 아예 없음)만** 백업한다 — 지정을 다른 프레임으로 옮기는 건 소실이
+ # 아니므로 정상 편집마다 백업 파일이 쌓이지 않는다.
+ new_anchors = anchor_choices(payload)
+ if any(d not in new_anchors for d in anchor_choices(old)):
+ backup = backup_stale_curation(run_dir, old_text)
+ new_states = payload.get("states") or {}
+ same_generation = old.get("run_revision") == payload.get("run_revision")
+ for name, old_entry in (old.get("states") or {}).items():
+ new_entry = new_states.get(name)
+ if not isinstance(old_entry, dict):
+ continue
+ if not isinstance(new_entry, dict):
+ lost = True
+ else:
+ old_rev, new_rev = old_entry.get("revision"), new_entry.get("revision")
+ if isinstance(old_rev, list) and isinstance(new_rev, list):
+ lost = old_rev != new_rev[:len(old_rev)]
+ else:
+ # 레거시 스탬프 없는 항목: 같은 런 세대의 정상 편집이면 호환
+ lost = not same_generation
+ if lost:
+ backup = backup_stale_curation(run_dir, old_text)
+ break
+ text = json.dumps(payload, ensure_ascii=False, indent=2) + "\n"
+ fd, tmp_name = tempfile.mkstemp(dir=str(run_dir), prefix=".curation-", suffix=".tmp")
+ try:
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
+ handle.write(text)
+ os.replace(tmp_name, target)
+ except BaseException:
+ if os.path.exists(tmp_name):
+ os.unlink(tmp_name)
+ raise
+ if backup:
+ # 원문이 실제로 덮인 순간에만 나는 줄이다 — 백업이 조용히 쌓이지 않게 관측 가능히.
+ print(f"[curation] this save overwrote selections {CURATION_FILENAME} still held; "
+ f"the previous file is preserved as {backup}: {run_dir}", file=sys.stderr)
+ return backup
+
+
+def transform_matrix(t: dict[str, float]) -> tuple[float, float, float, float]:
+ """Forward 2x2 linear matrix (M00, M01, M10, M11) = Rotate · Shear · Scale · FlipX.
+
+ Screen y-down. Positive `rotate` is counter-clockwise. This exact matrix is
+ mirrored in the webview (CSS `matrix()` + canvas), so what the user aligns to
+ the ground grid is what bakes — no preview/bake drift. flipX (when set)
+ multiplies the right-most diag(-1, 1) so column-0 의 부호가 반전된다.
+ """
+ rr = math.radians(t["rotate"])
+ c, sn = math.cos(rr), math.sin(rr)
+ s, shx, shy = t["scale"], t.get("shx", 0.0), t.get("shy", 0.0)
+ m00 = s * (c + sn * shy)
+ m01 = s * (c * shx + sn)
+ m10 = s * (-sn + c * shy)
+ m11 = s * (c - sn * shx)
+ if t.get("flipX"):
+ m00, m10 = -m00, -m10
+ return m00, m01, m10, m11
+
+
+def state_pixel_ops(curation: dict[str, Any] | None, state: str) -> dict[int, dict[str, Any]]:
+ """프레임별 픽셀 편집 ops — {frame_index: {"x,y": "#rrggbb"|None}}. 손상 항목은 스킵."""
+ entry = ((curation or {}).get("states") or {}).get(state)
+ raw = entry.get("pixels") if isinstance(entry, dict) else None
+ ops: dict[int, dict[str, Any]] = {}
+ if isinstance(raw, dict):
+ for key, value in raw.items():
+ try:
+ index = int(key)
+ except (TypeError, ValueError):
+ continue
+ if isinstance(value, dict) and value:
+ ops[index] = value
+ return ops
+
+
+def apply_pixel_edits(frame: Image.Image, ops: dict[str, Any] | None) -> Image.Image:
+ """사이드카 픽셀 편집을 프레임 사본에 합성 (원본 불변). 좌표는 셀 픽셀 공간,
+ 변형(apply_transform) 이전에 적용한다 — 웹뷰 오버레이와 같은 순서."""
+ if not ops:
+ return frame
+ edited = frame.convert("RGBA").copy()
+ px = edited.load()
+ for key, value in ops.items():
+ try:
+ x_str, y_str = str(key).split(",", 1)
+ x, y = int(x_str), int(y_str)
+ except (TypeError, ValueError):
+ continue
+ if not (0 <= x < edited.width and 0 <= y < edited.height):
+ continue
+ if value is None:
+ px[x, y] = (0, 0, 0, 0)
+ elif isinstance(value, str) and value.startswith("#") and len(value) in (7, 9):
+ r, g, b = int(value[1:3], 16), int(value[3:5], 16), int(value[5:7], 16)
+ a = int(value[7:9], 16) if len(value) == 9 else 255
+ px[x, y] = (r, g, b, a)
+ return edited
+
+
+def state_plan(
+ curation: dict[str, Any] | None,
+ state: str,
+ default_count: int,
+) -> tuple[list[int], dict[int, dict[str, float]]]:
+ """Resolve the ordered frame indices and per-frame transforms for a state.
+
+ Returns (ordered_zero_based_indices, {frame_index: transform}).
+ """
+ default_order = list(range(default_count))
+ if not curation:
+ return default_order, {}
+ entry = curation.get("states", {}).get(state)
+ if not isinstance(entry, dict):
+ return default_order, {}
+
+ # 복제 인스턴스 인덱스도 selected/deleted 의 유효 인덱스다 (파일은 원본을 읽음
+ # — source_frame_index). 기본값(선택 없음)은 물리 프레임만: 복제는 명시 선택으로만 굽는다.
+ clone_ids = set(state_clones(curation, state, default_count))
+ deleted = set(normalize_frame_indices(entry.get("deleted"), default_count, clone_ids))
+ default_visible = [index for index in default_order if index not in deleted]
+ selected = entry.get("selected")
+ if isinstance(selected, list) and selected:
+ # tolerate a hand-edited / corrupt sidecar: skip non-integer,
+ # out-of-range, duplicate, or deleted entries instead of crashing.
+ ordered = [
+ index
+ for index in normalize_frame_indices(selected, default_count, clone_ids)
+ if index not in deleted
+ ]
+ if not ordered:
+ ordered = default_visible
+ else:
+ ordered = default_visible
+
+ transforms_raw = entry.get("transforms", {})
+ transforms: dict[int, dict[str, float]] = {}
+ if isinstance(transforms_raw, dict):
+ for key, value in transforms_raw.items():
+ try:
+ index = int(key)
+ except (TypeError, ValueError):
+ continue
+ transform = normalize_transform(value)
+ if not is_identity(transform):
+ transforms[index] = transform
+ return ordered, transforms
+
+
+def apply_transform(
+ frame: Image.Image,
+ transform: dict[str, float] | None,
+ cell_size: tuple[int, int],
+ snap_scale: int | None = None,
+) -> Image.Image:
+ """Apply scale/shear/rotate (about center) + translate, into a fresh cell.
+
+ Rendered with one inverse-affine `Image.transform` into the cell, so cell
+ size is preserved and the atlas layout never changes. Non-destructive: the
+ source frame is not modified. The forward matrix matches `transform_matrix`,
+ which the webview uses for its preview, so alignment to the ground grid is
+ faithful to the bake.
+
+ `snap_scale` (a `fit.pixel_unfake` run baking the canonical pixel variant,
+ from `pixel_snap_scale`): the transform is sampled NEAREST and the result is
+ re-quantized to the fixed logical grid (cell-anchored, `snap_scale` px per
+ logical px), so a curated move/scale/rotate cannot smear the pixel grid —
+ the sprite lands back on the same grid the extraction snapped to. The webview
+ mirrors this quantization live while editing (curator src/display.js drawFrameInto).
+ """
+ transform = normalize_transform(transform) if transform else dict(IDENTITY)
+ if is_identity(transform) and frame.size == cell_size:
+ return frame.convert("RGBA")
+
+ src = frame.convert("RGBA")
+ cw, ch = cell_size
+ m00, m01, m10, m11 = transform_matrix(transform)
+ det = m00 * m11 - m01 * m10
+ if abs(det) < 1e-6:
+ det = 1e-6 if det >= 0 else -1e-6
+ # inverse 2x2 (output -> input)
+ ia, ib = m11 / det, -m01 / det
+ id_, ie = -m10 / det, m00 / det
+ cin_x, cin_y = src.width / 2, src.height / 2
+ cout_x, cout_y = cw / 2 + transform["dx"], ch / 2 + transform["dy"]
+ c = -(ia * cout_x + ib * cout_y) + cin_x
+ f = -(id_ * cout_x + ie * cout_y) + cin_y
+ if not snap_scale:
+ return src.transform((cw, ch), Image.AFFINE, (ia, ib, c, id_, ie, f), resample=Image.BICUBIC)
+ out = src.transform((cw, ch), Image.AFFINE, (ia, ib, c, id_, ie, f), resample=Image.NEAREST)
+ if snap_scale > 1:
+ logical_w, logical_h = max(1, cw // snap_scale), max(1, ch // snap_scale)
+ out = out.resize((logical_w, logical_h), Image.Resampling.NEAREST)
+ out = out.resize((logical_w * snap_scale, logical_h * snap_scale), Image.Resampling.NEAREST)
+ if out.size != (cw, ch): # cell not divisible by scale: pad back to exact cell
+ padded = Image.new("RGBA", (cw, ch), (0, 0, 0, 0))
+ padded.alpha_composite(out, (0, 0))
+ out = padded
+ return out
+
+
+def empty_curation() -> dict[str, Any]:
+ return {"version": SCHEMA_VERSION, "kind": "sprite-gen-curation", "states": {}}
diff --git a/sprite_gen/effects/__init__.py b/sprite_gen/effects/__init__.py
new file mode 100644
index 0000000..9881313
--- /dev/null
+++ b/sprite_gen/effects/__init__.py
@@ -0,0 +1 @@
+# SPDX-License-Identifier: Apache-2.0
diff --git a/sprite_gen/effects/anatomy.py b/sprite_gen/effects/anatomy.py
new file mode 100644
index 0000000..88f352a
--- /dev/null
+++ b/sprite_gen/effects/anatomy.py
@@ -0,0 +1,324 @@
+# SPDX-License-Identifier: Apache-2.0
+"""실루엣 해부 — 호흡 변형이 어디까지 미쳐야 하는지를 기하로 결정한다 (AI 개입 0).
+
+호흡을 "가슴선 하나"로 정의하려던 접근은 임의 몬스터에 일반화되지 않는다. 가슴은
+해부학 개념이라 버섯(몸통에 얼굴)·박쥐(옆으로 뻗은 날개)·슬라임(목 자체가 없음)에서
+서로 다른 것을 뜻한다. 대신 이 모듈은 **변형시키면 안 되는 영역**을 찾는다:
+
+ · 목 — 폭 프로파일의 병목 (medial axis "neck" 개념). 있으면 그 위는 머리다.
+ · 얼굴 — 좌우 대칭 눈쌍. 목이 없거나 목이 얼굴을 관통할 때 이쪽이 경계를 정한다.
+ · 부속 — 몸통 반폭을 크게 넘는 가로 질량(날개·긴 팔). 늘리지 말고 밀어야 한다.
+
+셋 다 실패해도 조용히 넘어가지 않는다 — 무엇으로 판정했는지(`neck_source`)와 무엇을
+못 찾았는지(`face is None`)가 결과에 그대로 남는다.
+
+근거 문헌: 실루엣 인체계측의 행별 girth 프로파일(Expert Systems with Applications
+2017), Medial Axis Isoperimetric Profiles (arXiv:2007.01428).
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+
+from PIL import Image
+
+from sprite_gen.frames.extract import solid_alpha_bbox
+from sprite_gen.frames.segment import mask_components, smooth_profile
+
+ALPHA_SOLID = 128
+
+# 부속 인정 임계 — 최대반폭이 몸통반폭의 이 배를 넘어야 "옆으로 뻗은 것"으로 본다.
+APPENDAGE_RATIO = 1.30
+# 병목 인정 임계 — prominence 가 최대폭의 이 비율을 넘어야 진짜 목이다.
+BOTTLENECK_PROMINENCE = 0.06
+# 눈 후보 제약 — 눈은 작고 컴팩트하다. 이게 골렘 팔·아웃라인 덩어리를 걸러낸다.
+EYE_MAX_EXTENT = 0.20 # bbox 변 길이 / 이미지 변 길이
+EYE_ASPECT = (0.4, 2.5)
+EYE_MIN_AREA = 0.002 # 불투명 면적 대비
+EYE_MAX_AREA = 0.06
+EYE_TOP_LIMIT = 0.65 # 이 아래에서 시작하는 덩어리는 눈이 아니다
+DARK_QUANTILE = 0.30 # 명도 하위 이만큼을 어두운 픽셀로 본다
+
+
+@dataclass(frozen=True)
+class Anatomy:
+ """한 상태(state)의 실루엣 해부 결과 — 사이드카에 얼릴 수 있는 순수 값."""
+
+ width: int
+ height: int
+ axis_x: int # 몸통 세로축 (알파 무게중심 x), 콘텐츠 bbox 기준
+ neck_row: int # 정수리 기준 행
+ neck_source: str # "bottleneck" | "shoulder-gradient"
+ rigid_row: int # 이 위는 변형하지 않는다 (목과 얼굴 중 아래쪽)
+ rigid_source: str # "neck" | "face" | "manual"
+ basis_row: int # 진폭 정규화 기준 — 병목이 진짜일 때만 목
+ torso_half: int
+ max_half: int
+ torso_source: str = "auto" # "auto" | "manual" — 보호 램프 앵커가 갈린다 (breathe.protect)
+ face: tuple[int, int] | None = None
+ warnings: tuple[str, ...] = field(default=())
+
+ @property
+ def has_appendage(self) -> bool:
+ return self.max_half >= APPENDAGE_RATIO * self.torso_half
+
+ @property
+ def rigid_u(self) -> float:
+ """발바닥 기준(0=발, 1=정수리) 강체 경계 — 프레임 높이가 달라도 쓸 수 있다."""
+ return 1.0 - self.rigid_row / max(1, self.height - 1)
+
+ @property
+ def basis_rows(self) -> int:
+ return max(1, self.height - self.basis_row)
+
+ def as_dict(self) -> dict:
+ return {"width": self.width, "height": self.height, "axis_x": self.axis_x,
+ "neck_row": self.neck_row, "neck_source": self.neck_source,
+ "rigid_row": self.rigid_row, "rigid_source": self.rigid_source,
+ "basis_row": self.basis_row, "torso_half": self.torso_half,
+ "max_half": self.max_half, "torso_source": self.torso_source,
+ "face": list(self.face) if self.face else None,
+ "warnings": list(self.warnings)}
+
+
+# ── 실루엣 ──────────────────────────────────────────────────────────
+
+def axis_x(image: Image.Image, box: tuple[int, int, int, int]) -> int:
+ """몸통 세로축 = 불투명 픽셀 x 무게중심 (box 상대 좌표)."""
+ px = image.load()
+ x0, y0, x1, y1 = box
+ total = acc = 0
+ for y in range(y0, y1):
+ for x in range(x0, x1):
+ if px[x, y][3] >= ALPHA_SOLID:
+ acc += x - x0
+ total += 1
+ return acc // max(1, total)
+
+
+# analyze() 의 `axis_x` **파라미터**(사람 오버라이드)가 함수 이름을 가리므로 별칭으로 부른다.
+_axis_centroid = axis_x
+
+
+def width_profile(image: Image.Image, box: tuple[int, int, int, int], cx: int) -> list[int]:
+ """행별 '몸통 중심 런' 폭.
+
+ 행 전체 불투명 픽셀을 세면 박쥐 날개처럼 옆으로 뻗은 부속이 폭을 지배한다.
+ 몸통 축을 지나는 **연속 런**만 재면 떨어져 있는 부속이 배제된다 — 실루엣의
+ 국소 두께를 세로축으로 샘플링한 것과 같다."""
+ px = image.load()
+ x0, y0, x1, y1 = box
+ width = x1 - x0
+ out: list[int] = []
+ for y in range(y0, y1):
+ seed = None
+ if px[x0 + cx, y][3] >= ALPHA_SOLID:
+ seed = cx
+ else:
+ best = None
+ for i in range(width):
+ if px[x0 + i, y][3] >= ALPHA_SOLID and (best is None or abs(i - cx) < abs(best - cx)):
+ best = i
+ seed = best
+ if seed is None:
+ out.append(0)
+ continue
+ lo = seed
+ while lo > 0 and px[x0 + lo - 1, y][3] >= ALPHA_SOLID:
+ lo -= 1
+ hi = seed
+ while hi < width - 1 and px[x0 + hi + 1, y][3] >= ALPHA_SOLID:
+ hi += 1
+ out.append(hi - lo + 1)
+ return out
+
+
+def bottleneck_prominences(profile: list[float]) -> list[tuple[int, float]]:
+ """국소 최소와 그 prominence — 양옆으로 다시 올라가는 높이 중 작은 쪽.
+
+ prominence 를 쓰는 이유: 도트 계단이 만드는 얕은 최소는 병목이 아니다. 형상을
+ 실제로 분절하는 병목만 남긴다 (medial axis 의 neck 개념을 1D 프로파일에 적용)."""
+ n = len(profile)
+ if n < 3:
+ return []
+ out = []
+ for i in range(1, n - 1):
+ if profile[i] > profile[i - 1] or profile[i] > profile[i + 1]:
+ continue
+ left = max(profile[:i])
+ right = max(profile[i + 1:])
+ out.append((i, min(left, right) - profile[i]))
+ return out
+
+
+def _best_bottleneck(profile: list[float], u0: float, u1: float) -> int | None:
+ n = len(profile)
+ lo, hi = int(n * u0), int(n * u1)
+ peak = max(profile) if profile else 0.0
+ cand = [(i, p) for i, p in bottleneck_prominences(profile) if lo <= i < hi]
+ if not cand:
+ return None
+ i, p = max(cand, key=lambda t: t[1])
+ return i if p >= BOTTLENECK_PROMINENCE * peak else None
+
+
+def _steepest_widening(profile: list[float], u0: float, u1: float) -> int:
+ """아래로 갈수록 실루엣이 가장 급히 넓어지는 행 = 어깨선.
+
+ 골렘처럼 머리 위가 계속 좁아 병목이 아예 없는 실루엣의 대체값. 이 값은 목이
+ 아니라 '목이 없다'는 사실의 표식이므로, 진폭 정규화 기준으로는 쓰지 않는다."""
+ n = len(profile)
+ lo, hi = max(1, int(n * u0)), max(2, int(n * u1))
+ return max(range(lo, hi), key=lambda i: profile[i] - profile[i - 1])
+
+
+def detect_neck(profile: list[int]) -> tuple[int, str]:
+ n = len(profile)
+ smooth = smooth_profile([float(v) for v in profile], 2 * max(1, n // 40) + 1)
+ row = _best_bottleneck(smooth, 0.05, 0.70)
+ if row is not None:
+ return row, "bottleneck"
+ return _steepest_widening(smooth, 0.05, 0.60), "shoulder-gradient"
+
+
+def detect_face(image: Image.Image, box: tuple[int, int, int, int], cx: int) -> tuple[int, int] | None:
+ """좌우 대칭 눈쌍으로 얼굴 세로 구간 (top_row, bottom_row) 을 찾는다.
+
+ 눈은 가장 어두운 **작고 컴팩트한** 덩어리이면서 몸통 축에 대해 거울 대칭인 쌍이다.
+ 두 조건을 동시에 요구하는 게 핵심이다 — 어둡기만 보면 아웃라인이, 대칭만 보면
+ 좌우 팔이 걸린다(실측: 컴팩트 제약 없이 골렘의 양팔이 눈으로 잡혔다).
+ 못 찾으면 None — 그때는 목이 경계를 정한다."""
+ px = image.load()
+ x0, y0, x1, y1 = box
+ w, h = x1 - x0, y1 - y0
+ lums: list[tuple[float, int]] = []
+ for j in range(h):
+ for i in range(w):
+ p = px[x0 + i, y0 + j]
+ if p[3] >= ALPHA_SOLID:
+ lums.append((0.299 * p[0] + 0.587 * p[1] + 0.114 * p[2], j * w + i))
+ if not lums:
+ return None
+ values = sorted(v for v, _ in lums)
+ threshold = values[0] + DARK_QUANTILE * (values[-1] - values[0])
+ area = len(lums)
+ mask = [False] * (w * h)
+ for v, idx in lums:
+ if v <= threshold:
+ mask[idx] = True
+
+ blobs = []
+ for bx0, by0, bx1, by1 in mask_components(mask, w, h,
+ min_area=max(4, int(EYE_MIN_AREA * area)),
+ max_area=int(EYE_MAX_AREA * area)):
+ bw, bh = bx1 - bx0, by1 - by0
+ if bh > EYE_MAX_EXTENT * h or bw > EYE_MAX_EXTENT * w:
+ continue
+ if not EYE_ASPECT[0] <= bw / bh <= EYE_ASPECT[1]:
+ continue
+ if by0 > EYE_TOP_LIMIT * h:
+ continue
+ blobs.append((bx0, by0, bx1, by1, bw * bh))
+
+ best = None
+ for i, a in enumerate(blobs):
+ for b in blobs[i + 1:]:
+ amid, bmid = (a[0] + a[2]) / 2, (b[0] + b[2]) / 2
+ da, db = amid - cx, bmid - cx
+ # 눈은 축을 **사이에 두고** 있다. 이 조건이 없으면 한쪽 눈 + 축 위의 입이
+ # 짝으로 잡혀 얼굴 구간이 입 아래까지 늘어난다 (실측: 버섯).
+ if da * db >= 0 or min(abs(da), abs(db)) < 0.05 * w:
+ continue
+ if abs((amid + bmid) / 2 - cx) > 0.08 * w: # 쌍의 중심이 축에 있나
+ continue
+ if abs(amid - bmid) < 0.10 * w: # 충분히 떨어져 있나
+ continue
+ if max(a[4], b[4]) > 2.5 * min(a[4], b[4]): # 크기가 비슷한가
+ continue
+ if min(a[3], b[3]) < max(a[1], b[1]): # 세로 구간이 겹치나
+ continue
+ # 큰 쌍 우선, 같으면 축에 더 대칭인 쌍 (결정론 — 순서 의존 제거)
+ score = (a[4] + b[4], -abs(da + db))
+ if best is None or score > best[0]:
+ best = (score, min(a[1], b[1]), max(a[3], b[3]) - 1)
+ if best is None:
+ return None
+ top, bot = best[1], best[2]
+ # 눈 아래 입까지 여유를 준다 — 눈만 지키고 입이 흔들리면 표정이 깨진다.
+ return top, min(h - 1, bot + max(1, round((bot - top) * 0.7)))
+
+
+def torso_metrics(image: Image.Image, box: tuple[int, int, int, int], cx: int,
+ profile: list[int], row_lo: int, row_hi: int) -> tuple[int, int]:
+ """(몸통 반폭 중앙값, 실루엣 최대 반폭) — 둘의 비가 부속의 존재량이다."""
+ px = image.load()
+ x0, y0, x1, y1 = box
+ band = [profile[r] for r in range(max(0, row_lo), min(len(profile), row_hi)) if profile[r]]
+ torso = (sorted(band)[len(band) // 2] // 2) if band else (x1 - x0) // 4
+ max_half = 0
+ for j in range(max(0, row_lo), min(y1 - y0, row_hi)):
+ for i in range(x1 - x0):
+ if px[x0 + i, y0 + j][3] >= ALPHA_SOLID:
+ max_half = max(max_half, abs(i - cx))
+ return max(1, torso), max(1, max_half)
+
+
+def analyze(image: Image.Image, rigid_row: int | None = None,
+ axis_x: int | None = None, torso_half: int | None = None) -> Anatomy:
+ """한 프레임의 실루엣 해부 — 검출 SSoT.
+
+ `rigid_row`/`axis_x`/`torso_half` 를 주면 사람이 정한 값으로 덮어쓴다(자동 검출은
+ 그대로 수행해 관측값으로 남긴다). 값 하나에 출처만 auto/manual 로 갈릴 뿐 진실은
+ 하나다. `axis_x` 는 몸통 세로축(콘텐츠 bbox 상대 열)이라 얼굴 검출·폭 프로파일·
+ 부속 판정까지 그 축 기준으로 다시 돈다. `torso_half` 는 몸통 반폭 — 부속 보호
+ 밴드가 어디서 시작하는지를 정한다 (큐레이터 영역 조정 UI, 2026-07-30)."""
+ box = solid_alpha_bbox(image)
+ if not box:
+ raise SystemExit("anatomy: 프레임에 불투명 콘텐츠가 없다")
+ x0, y0, x1, y1 = box
+ w, h = x1 - x0, y1 - y0
+ cx = _axis_centroid(image, box)
+ if axis_x is not None:
+ if not 0 <= axis_x < w:
+ raise SystemExit(f"anatomy: axis_x {axis_x} 가 콘텐츠 폭 {w} 밖이다")
+ if axis_x != cx:
+ cx = int(axis_x)
+ profile = width_profile(image, box, cx)
+ neck_row, neck_source = detect_neck(profile)
+ face = detect_face(image, box, cx)
+
+ warnings: list[str] = []
+ auto_cx = _axis_centroid(image, box)
+ if axis_x is not None and axis_x != auto_cx:
+ warnings.append(f"axis-x-override: auto {auto_cx} -> manual {axis_x}")
+ auto_rigid = max(neck_row, (face[1] + 1) if face else 0)
+ auto_rigid = min(auto_rigid, int(h * 0.80)) # 몸통이 통째로 사라지지는 않게
+ rigid_source = "face" if (face and face[1] + 1 > neck_row) else "neck"
+ if rigid_row is not None:
+ if not 0 < rigid_row < h:
+ raise SystemExit(f"anatomy: rigid_row {rigid_row} 가 콘텐츠 높이 {h} 밖이다")
+ if rigid_row != auto_rigid:
+ warnings.append(f"rigid-row-override: auto {auto_rigid} -> manual {rigid_row}")
+ auto_rigid, rigid_source = rigid_row, "manual"
+
+ # 진폭 정규화 기준: 병목이 진짜일 때만 목을 쓴다. 슬라임처럼 폭 프로파일이 단조
+ # 증가라 병목이 없으면 (H - neck) 이 실제 변형 구간의 몇 배가 되어 정규화가 폭주한다.
+ basis_row = neck_row if neck_source == "bottleneck" else auto_rigid
+ if neck_source != "bottleneck":
+ warnings.append("neck-absent: 폭 프로파일에 병목이 없어 어깨-기울기로 대체했다 "
+ f"(정규화 기준은 강체 경계 {auto_rigid} 사용)")
+ if face is None:
+ warnings.append("face-absent: 대칭 눈쌍을 못 찾아 목만으로 경계를 정했다")
+
+ torso, max_half = torso_metrics(image, box, cx, profile, auto_rigid, h)
+ torso_source = "auto"
+ if torso_half is not None:
+ if not 1 <= torso_half <= w:
+ raise SystemExit(f"anatomy: torso_half {torso_half} 가 범위 [1, {w}] 밖이다")
+ if torso_half != torso:
+ warnings.append(f"torso-half-override: auto {torso} -> manual {torso_half}")
+ torso, torso_source = int(torso_half), "manual"
+ return Anatomy(width=w, height=h, axis_x=cx, neck_row=neck_row, neck_source=neck_source,
+ rigid_row=auto_rigid, rigid_source=rigid_source, basis_row=basis_row,
+ torso_half=torso, max_half=max_half, torso_source=torso_source, face=face,
+ warnings=tuple(warnings))
diff --git a/sprite_gen/effects/breathe.py b/sprite_gen/effects/breathe.py
new file mode 100644
index 0000000..502891d
--- /dev/null
+++ b/sprite_gen/effects/breathe.py
@@ -0,0 +1,613 @@
+# SPDX-License-Identifier: Apache-2.0
+"""결정론 호흡(idle breathing) — 봉투 기반 스쿼시&스트레치 (변형 강도 장).
+
+호흡은 프레임 선택(깜빡임)과 직교하는 변조 레이어다 (maintainer 확정 2026-07-18).
+설정은 curation.json 사이드카 `states.<state>.breathe` (curation.state_breathe 가
+정규화 SSoT), 굽기는 compose/GIF 가 재생 시퀀스 위에 이 모듈의 수학으로 한다.
+AI 개입 0 — 같은 입력이면 항상 같은 출력.
+
+## 왜 분할선이 아니라 봉투인가 (2026-07-25 교체)
+
+구 방식은 수평 분할선 위의 행을 정수 px 내리는 것이었다. 실제 출력은 **2상태 토글**
+이라(측정: idle GIF 6프레임이 `f0==f2==f4`, `f1==f3==f5`) 호흡이 아니라 1px 진동으로
+읽혔다. 머리를 잘라 붙이는 변형으로 바꿔봐도 잘린 단면이 목에 가로선으로 드러났다.
+
+붙이는 연산이 있는 한 이음매는 없앨 수 없다. 그래서 **자르지 않는다.** 스프라이트
+전체에 연속 변형장 하나를 걸고 그 강도를 목(또는 얼굴 아래)에서 0 으로 떨군다:
+
+ env(y) = 발끝램프(y) x 강체테이퍼(y) # 0 = 원본 그대로, 1 = 최대 변형
+ g(y,t) = depth * norm * wave(t - lag*u(y)) * env(y)
+ sx(y) = 1 + g # 가로
+ sy(y) = 1 / (1 + g) # 세로 (면적 보존)
+
+## 불변식 (테스트가 지키는 것)
+
+1. **강체 구간은 항등이다 — 근사가 아니다.** env=0 인 행은 g=0 -> 가로 사상이 원본
+ 좌표 그대로, sy=1 -> 누적 높이가 정확히 1씩 증가 -> 행 복제/삭제 0.
+ 그래서 그 구간은 프레임 간 **비트 동일**하다. 눈·입이 몇 도트뿐인 픽셀아트에서
+ 3% 세로 신장도 표정을 뭉개므로 이게 핵심 계약이다.
+2. **가로 사상은 단조다.** X(x) = ∫ dens(s) ds 이고 dens > 0 이므로 접힘이 구조적으로
+ 불가능하다. 몸통만 1+g, 부속(날개)은 1 -> 날개는 밖으로 밀리기만 하고 안 늘어난다.
+3. **몸통 축 열이 가로 사상의 고정점이다.** 출력 위치를 축의 적분값 기준으로 잡으므로
+ 축은 언제나 제자리이고, 그래서 (a) 변형이 0 이면 사상이 진짜 항등이 되고
+ (b) 배율이 변해도 스프라이트가 통째로 좌우로 튀지 않는다. bbox 중앙을 기준으로
+ 잡으면 축이 중앙과 다른 캐릭터가 변형 0 에서도 밀린다 (회귀 2026-07-25 validator 검증).
+4. **격자를 벗어나는 연산이 없다.** 세로는 행 정수 복제/삭제, 가로는 정수 열 사상.
+ 보간·블렌딩·비정수 스케일이 한 번도 일어나지 않으므로 출력이 항상 정수 도트다.
+ 언페이크(pitch 검출)를 프레임마다 다시 할 필요가 없는 이유이자, 다시 하면 안 되는
+ 이유이기도 하다 (synthetic_fixture_a up_run frame-2, 2026-07-22 하모닉 오검출 붕괴).
+5. **루프 길이 불변.** 출력 프레임 수 = 입력 프레임 수. 호흡이 그 안에서 breaths 회
+ 딱 떨어진다.
+
+(구 테이크 방식 — exhale 프레임을 raw 테이크로 굽고 전체 재추출 — 은 v1.56.31 에서
+폐기: 깜빡임×호흡 조합 불가 + 적용마다 수 분 + 팔레트 드리프트. 봉투 방식은 그 셋 중
+무엇도 해소하지 않으므로 되돌릴 근거가 없다.)
+"""
+
+from __future__ import annotations
+
+import math
+
+from PIL import Image
+
+from sprite_gen.effects.anatomy import Anatomy, analyze
+from sprite_gen.curate.curation import normalize_transform
+from sprite_gen.frames.extract import solid_alpha_bbox
+
+# 강체 경계에서 변형 강도가 0 이 되기까지의 테이퍼 반폭 (콘텐츠 높이 비율).
+# 이 테이퍼가 이음매를 없앤다 — 경계에서 강도가 계단이 아니라 경사로 떨어진다.
+TAPER = 0.055
+# 발끝 고정 램프 — 변형 구간 아래쪽 이 비율만큼은 강도가 0 에서 올라온다 (발이 안 뜬다).
+FOOT = 0.28
+# 행당 변형 상한. 넘으면 조용히 깎지 않고 멈춘다 (No Silent Fallback).
+MAX_ROW_STRAIN = 0.25
+# 기본 진폭 — 몸통 높이 대비 총 신장량.
+DEFAULT_DEPTH = 0.06
+# 진행파 위상지연 (호흡 주기 비율) — 몸통 윗부분이 늦게 밀어올려 머리가 한 박자 늦게 온다.
+DEFAULT_LAG = 0.10
+# 한 호흡이 부드럽게 읽히려면 필요한 최소 프레임 수 (프레임을 찍어낼 때의 권고치).
+SMOOTH_CYCLE_FRAMES = 6
+
+
+# ── 파형 ────────────────────────────────────────────────────────────
+
+def wave(t: float) -> float:
+ """한 호흡의 기본 파형. 2차 하모닉을 살짝 섞어 정점이 뾰족해진다(들숨의 어택)."""
+ return 0.86 * math.sin(2 * math.pi * t) + 0.14 * math.sin(4 * math.pi * t)
+
+
+def smoothstep(a: float, b: float, x: float) -> float:
+ if b <= a:
+ return 1.0 if x >= b else 0.0
+ u = min(1.0, max(0.0, (x - a) / (b - a)))
+ return u * u * (3 - 2 * u)
+
+
+# ── 변형 강도 봉투 ──────────────────────────────────────────────────
+
+def envelope(anat: Anatomy, taper: float = TAPER, foot: float = FOOT):
+ """(env(u), 진폭 정규화 계수) — u = 0(발바닥) .. 1(정수리).
+
+ 정규화: 테이퍼·발끝램프가 변형 구간을 갉아먹으므로 그대로 두면 강체 경계가 낮은
+ 캐릭터일수록 호흡이 작아진다. sum(env) 로 나눠 **총 신장량이 항상
+ depth × 기준높이**가 되게 한다 — 진폭 숫자가 캐릭터와 무관하게 같은 뜻을 갖는다."""
+ height = anat.height
+ ru = anat.rigid_u
+ band = max(1.5, taper * height) / max(1, height)
+ foot_top = foot * ru
+
+ def env(u: float) -> float:
+ return smoothstep(0.0, foot_top, u) * (1.0 - smoothstep(ru - band, ru + band, u))
+
+ total = sum(env(j / max(1, height - 1)) for j in range(height))
+ norm = anat.basis_rows / total if total > 1e-6 else 0.0
+ return env, norm
+
+
+def protect(anat: Anatomy):
+ """부속 보호 가중 p(x) — 1 이면 그 열은 가로로 안 늘어난다 (콘텐츠 bbox 상대 x).
+
+ 자동 검출 밴드는 부속(날개·긴 팔)이 실재할 때만 켜지고 램프 끝을 max_half 에
+ 앵커한다. **수동 밴드(큐레이터 영역 UI)는 무조건 켜지고 램프를 밴드 자체에
+ 앵커한다** — 블롭(max_half ≈ torso_half)에서 자동 램프는 몸 끝까지 완만해 밴드를
+ 아무리 좁혀도 보호가 1 에 도달하지 못했다 (실측 2026-07-30 synthetic silhouette 문어:
+ 밴드 12→4 에 출력 차이가 바이트 22개, maintainer "버그로 보여"). 사람이 밴드를 그렸으면
+ 그 밖은 밀리기만 해야 한다."""
+ cx = anat.axis_x
+ if anat.torso_source == "manual":
+ t0 = float(anat.torso_half)
+ t1 = t0 + 2.0
+ return lambda x: smoothstep(t0, t1, abs(x - cx))
+ if not anat.has_appendage:
+ return lambda x: 0.0
+ t0 = anat.torso_half * 1.15
+ t1 = max(t0 + 1.0, anat.max_half * 0.95)
+ return lambda x: smoothstep(t0, t1, abs(x - cx))
+
+
+def row_strain(anat: Anatomy, depth: float) -> float:
+ """행당 최대 변형 — MAX_ROW_STRAIN 초과 여부 판정용 (관측 가능하게 노출)."""
+ env, norm = envelope(anat)
+ peak = max(env(j / max(1, anat.height - 1)) for j in range(anat.height))
+ return depth * norm * peak
+
+
+# ── 외곽선 1px 다듬기 ───────────────────────────────────────────────
+
+def _dark(p) -> bool:
+ """다듬기의 '외곽선 어두움' 판정 — 외곽선과 어두운 음영을 갈라야 한다.
+
+ 실측(문어 idle 왼쪽 볼, 2026-07-30): 외곽선 lum 0~13, 어두운 음영 73~92, 내부 112+.
+ 구 문턱 96 은 음영까지 외곽선으로 세어 (외곽,외곽,음영) 3연속이 '전부 어두움' 이
+ 되니 다듬기 패턴이 발화하지 않아 볼의 바깥 검은 열이 잔존했다. 60 이 두 군집
+ 사이를 가른다."""
+ return bool(p[3]) and (0.299 * p[0] + 0.587 * p[1] + 0.114 * p[2]) < 60.0
+
+
+def _thin_outline_1px(out: Image.Image) -> None:
+ """안쪽점 기준 다듬기를 고정점까지 반복 — 한 패스의 제거가 새 돌출점을 만들 수 있다.
+
+ 실측(문어 idle 위상 0): 2점 패턴의 바깥점 (2,13) 을 지우면 남은 (3,13) 이 이웃 행보다
+ 1px 튀어나온 새 돌출점이 되는데, 단일 패스 스냅샷은 그걸 못 본다. 각 패스가 불투명
+ 픽셀을 단조 감소시키므로 종료가 보장된다 (JS 미러 동일)."""
+ while _thin_outline_pass(out):
+ pass
+
+
+def _thin_outline_pass(out: Image.Image) -> int:
+ """워프된 프레임의 실루엣 외곽선 2px 를 **안쪽점 기준** 1px 로 정규화하는 1패스.
+
+ 세로 스쿼시&스트레치는 정수 행 복제/삭제라, 가파른 대각선 외곽선이 국소적으로 2px
+ 두께가 되며 위상마다 위치를 바꿔 "간헐 2줄 검은점" 으로 읽힌다 (실측 2026-07-30:
+ 문어 idle 왼쪽 볼, maintainer 발견). 각 열/행의 실루엣 끝에서 '어두움-어두움-내부색'
+ 3연속을 만나면 **바깥 픽셀을 제거(알파 0)** 해 이웃 행들과 정렬된 **안쪽** 선만
+ 남긴다 — 초기 구현은 안쪽을 내부색으로 되돌려 바깥점을 선으로 남겼는데, 돌출한
+ 바깥점이 이웃 행 선과 어긋나 여전히 2줄로 읽혔다 (maintainer 실기기 판정 2026-07-30:
+ "안쪽 검은점 기준이 더 정확하다").
+
+ 안전 필터 — 제거가 새 결함을 만들면 안 된다:
+ · 제거된 자리의 수직(가로 패턴)/수평(세로 패턴) 이웃이 불투명 내부색이면 제거로
+ 실루엣 끝에 내부색이 노출된다 → 제외.
+ · 이웃 양쪽이 제거되지 않는 어두운 픽셀이면 어두운 선 **중간에 구멍**이 난다 → 제외.
+ · 이웃이 같은 패스에서 같이 제거되는 후보면 안전(돌출 열/행이 통째로 사라짐).
+ 제외가 다른 후보의 안전성을 바꾸므로 고정점까지 반복한다(결정론 — 정렬 순회).
+
+ 호출자는 **변형이 실제로 일어난 프레임에만** 부른다(_warp 의 deformed 게이트). 변형 0
+ 프레임은 이 함수를 타지 않아 "변형 0 = 원본 동일" 계약이 유지된다. 원본 스냅샷에서만
+ 읽고 한 번에 적용하므로 순회 순서와 무관하게 결과가 같다(JS 미러 바이트 동일 성질)."""
+ src = out.load()
+ w, h = out.size
+ op = lambda x, y: 0 <= x < w and 0 <= y < h and bool(src[x, y][3])
+ dark = lambda x, y: op(x, y) and _dark(src[x, y])
+ # 후보 수집: (바깥픽셀 좌표) -> 패턴 축 ('h' = 행 끝 패턴, 'v' = 열 끝 패턴)
+ cand: dict[tuple[int, int], str] = {}
+ for x in range(w):
+ ys = [y for y in range(h) if op(x, y)]
+ if not ys:
+ continue
+ t0, b0 = ys[0], ys[-1]
+ if t0 + 2 <= b0 and dark(x, t0) and dark(x, t0 + 1) and op(x, t0 + 2) and not dark(x, t0 + 2):
+ cand[(x, t0)] = "v"
+ if b0 - 2 >= t0 and dark(x, b0) and dark(x, b0 - 1) and op(x, b0 - 2) and not dark(x, b0 - 2):
+ cand[(x, b0)] = "v"
+ # 행 끝 좌표 맵 (돌출점 판정용)
+ row_lo: dict[int, int] = {}
+ row_hi: dict[int, int] = {}
+ for y in range(h):
+ xs = [x for x in range(w) if op(x, y)]
+ if not xs:
+ continue
+ row_lo[y], row_hi[y] = xs[0], xs[-1]
+ l0, r0 = xs[0], xs[-1]
+ if l0 + 2 <= r0 and dark(l0, y) and dark(l0 + 1, y) and op(l0 + 2, y) and not dark(l0 + 2, y):
+ cand.setdefault((l0, y), "h")
+ if r0 - 2 >= l0 and dark(r0, y) and dark(r0 - 1, y) and op(r0 - 2, y) and not dark(r0 - 2, y):
+ cand.setdefault((r0, y), "h")
+ # 1px 단독 돌출점 — 그 행의 어두운 끝점이 위아래 행 끝보다 정확히 1px 바깥으로 튀어나온
+ # 경우(가로 매핑 반올림이 행마다 갈린 아티팩트). 2점 패턴이 아니라 위 후보에 안 잡힌다.
+ # 점을 지우고 **안쪽 자리에 그 색을 그대로 그린다** — 이웃 행들과 정렬된 안쪽 선이 된다.
+ # 안전: 돌출 정의상 (x, y±1) 은 투명이라(이웃 행 끝이 더 안쪽) 제거로 노출·구멍이 없다.
+ # 가로(좌우) 한정 — 세로(정수리) 1px 계단은 작가 의도(머리카락 스파이크류)와 구분이
+ # 안 돼 건드리지 않는다.
+ moves: dict[tuple[int, int], tuple[int, int, int, int]] = {} # 안쪽좌표 -> 칠할 색
+ for y in sorted(row_lo):
+ up_lo, dn_lo = row_lo.get(y - 1), row_lo.get(y + 1)
+ m = row_lo[y]
+ if (up_lo is not None and dn_lo is not None and min(up_lo, dn_lo) - m == 1
+ and dark(m, y) and op(m + 1, y)):
+ cand.setdefault((m, y), "h")
+ if not dark(m + 1, y):
+ moves[(m + 1, y)] = src[m, y]
+ up_hi, dn_hi = row_hi.get(y - 1), row_hi.get(y + 1)
+ r = row_hi[y]
+ if (up_hi is not None and dn_hi is not None and r - max(up_hi, dn_hi) == 1
+ and dark(r, y) and op(r - 1, y)):
+ cand.setdefault((r, y), "h")
+ if not dark(r - 1, y):
+ moves[(r - 1, y)] = src[r, y]
+ # 안전 필터 고정점: 제거 대상에서 빠진 픽셀은 이웃 후보의 kept-dark 가 되므로 반복.
+ drop = set(cand)
+ changed = True
+ while changed:
+ changed = False
+ for p in sorted(drop):
+ x, y = p
+ neigh = ((x, y - 1), (x, y + 1)) if cand[p] == "h" else ((x - 1, y), (x + 1, y))
+ kept_dark = 0
+ ok = True
+ for nx, ny in neigh:
+ if not op(nx, ny) or (nx, ny) in drop:
+ continue
+ if dark(nx, ny):
+ kept_dark += 1
+ else:
+ ok = False # 내부색이 실루엣 끝으로 노출된다
+ break
+ if not ok or kept_dark >= 2: # 어두운 선 중간 구멍
+ drop.discard(p)
+ changed = True
+ break
+ for x, y in drop:
+ out.putpixel((x, y), (0, 0, 0, 0))
+ applied = len(drop)
+ for (x, y), color in moves.items():
+ if (x, y) not in drop:
+ out.putpixel((x, y), color)
+ applied += 1
+ return applied
+
+
+# ── 워프 ────────────────────────────────────────────────────────────
+
+def _warp(frame: Image.Image, anat: Anatomy, depth: float, lag: float, t: float,
+ depth_x: float | None = None) -> Image.Image:
+ """한 위상 t 의 프레임 — 캔버스 크기 불변, 발바닥 고정.
+
+ 세로는 행 국소 배율을 누적해 각 원본 행이 출력에서 몇 행을 차지하는지 정하고,
+ 가로는 행 안에서 위치마다 다른 밀도를 적분해 단조 사상을 만든다. 둘 다 정수
+ 연산이라 출력이 정수 도트다.
+
+ `depth_x` 는 가로 성분의 독립 진폭이다 (maintainer 요청 2026-07-30 — 가로/세로 분리).
+ None 이면 depth 를 따른다(레거시와 바이트 동일), 0 이면 가로 사상이 전 위상
+ 항등이다. 파형·봉투·지연은 두 축이 공유한다 — 축마다 다른 건 스칼라뿐이다."""
+ box = solid_alpha_bbox(frame)
+ if not box:
+ return frame.copy()
+ body = frame.convert("RGBA").crop(box)
+ src = body.load()
+ width, height = body.size
+ canvas_w, canvas_h = frame.size
+ anchor_x = box[0] + anat.axis_x
+ baseline = box[3]
+
+ env, norm = envelope(anat)
+ p_of = protect(anat)
+ ru = anat.rigid_u
+ dx_amp = depth if depth_x is None else depth_x
+
+ def gain(u: float, d: float) -> float:
+ e = env(u)
+ if e <= 0.0:
+ return 0.0
+ return d * norm * wave(t - lag * min(1.0, u / max(1e-6, ru))) * e
+
+ # 세로 누적 — j=0 이 정수리
+ heights: list[float] = []
+ acc = 0.0
+ for j in range(height):
+ g = gain(1.0 - j / max(1, height - 1), depth)
+ acc += 1.0 if g == 0.0 else 1.0 / (1.0 + g)
+ heights.append(acc)
+ total = max(1, math.floor(acc + 0.5))
+
+ out = Image.new("RGBA", frame.size, (0, 0, 0, 0))
+ dst = out.load()
+ y_cursor = baseline - total
+ prev = 0
+ clipped = 0
+ deformed = False # 이 위상에서 변형이 실제로 일어났나 (다듬기 게이트)
+ for j in range(height):
+ u = 1.0 - j / max(1, height - 1)
+ cur = math.floor(heights[j] + 0.5)
+ reps = max(0, cur - prev)
+ prev = cur
+ if reps == 0:
+ continue
+ g = gain(u, dx_amp) # 가로 성분 — 독립 진폭 (depth_x)
+ if reps != 1:
+ deformed = True # 행 복제/삭제 = 세로 변형이 실재
+ if g == 0.0:
+ # 변형 없음 = 원본 위치 그대로. 축 고정점 사상의 g->0 극한과 정확히 같다.
+ row_map = [(box[0] + i, i) for i in range(width)]
+ else:
+ deformed = True # 가로 사상 변형이 실재
+ dens = [max(0.05, 1.0 + g * (1.0 - p_of(i))) for i in range(width)]
+ edge = [0.0]
+ for d in dens:
+ edge.append(edge[-1] + d)
+ origin = edge[anat.axis_x] # 축을 고정점으로 — 여기가 anchor_x 에 박힌다
+ # half-up 반올림: 파이썬 기본 round() 는 은행가 반올림(round(0.5)==0)이라
+ # JS Math.round(half-up) 미러와 .5 경계에서 갈린다. 규칙을 명시해 고정한다.
+ lo = math.floor(edge[0] - origin + 0.5)
+ hi = math.floor(edge[width] - origin + 0.5)
+ row_map = []
+ i = 0
+ for ox in range(lo, hi):
+ while i < width - 1 and (edge[i + 1] - origin) <= ox:
+ i += 1
+ row_map.append((anchor_x + ox, i))
+ # 외곽선 보존: 가로 축소 위상에서 forward 밀도매핑이 실루엣 양끝 열을 통째로
+ # 떨궈 1px 외곽선이 사라진다(발끝 플리커, 실측 2026-07-30: 문어 idle y25~y28
+ # 이 날숨 위상마다 소실). 이 행의 최말단 불투명 소스 열(= 외곽선)을 출력의
+ # 양끝 불투명 픽셀에 그대로 실어 항상 1px 외곽선이 남게 한다 — 원본 외곽선
+ # 픽셀을 복사하므로 색·밝기가 정확히 보존되고(재도색 아님) 위상 간 잔여
+ # 깜빡임이 없다. g==0 항등 분기(위)는 손대지 않아 "변형 0 = 원본 동일" 계약이
+ # 그대로 산다. 축소가 아니면(양끝이 이미 외곽선을 실으면) no-op 이다.
+ op = [k for k in range(width) if src[k, j][3]]
+ if op and row_map:
+ op_lo, op_hi = op[0], op[-1]
+ for k in range(len(row_map) - 1, -1, -1):
+ if src[row_map[k][1], j][3]:
+ row_map[k] = (row_map[k][0], op_hi)
+ break
+ for k in range(len(row_map)):
+ if src[row_map[k][1], j][3]:
+ row_map[k] = (row_map[k][0], op_lo)
+ break
+ for r in range(reps):
+ yy = y_cursor + r
+ for ox, si in row_map:
+ pixel = src[si, j]
+ if not pixel[3]:
+ continue
+ if 0 <= yy < canvas_h and 0 <= ox < canvas_w:
+ dst[ox, yy] = pixel
+ else:
+ clipped += 1
+ y_cursor += reps
+ if clipped:
+ # 조용히 자르지 않는다 — 정수리나 옆구리가 셀 밖으로 나가면 스프라이트가
+ # 망가지고, 그건 여백이나 진폭을 사람이 정해야 하는 문제다 (No Silent Fallback).
+ raise SystemExit(
+ f"breathe: 늘어난 프레임이 셀 밖으로 나가 불투명 픽셀 {clipped}개가 잘린다 "
+ f"(셀 {canvas_w}x{canvas_h}, 콘텐츠 {box[0]},{box[1]}-{box[2]},{box[3]}). "
+ f"셀 여백을 늘리거나 depth 를 낮춰라.")
+ if deformed:
+ _thin_outline_1px(out)
+ return out
+
+
+# ── 해부 결과 얼리기 / 자가 복구 ────────────────────────────────────
+
+def _fnv1a(data: bytes) -> int:
+ """FNV-1a 32비트 — **JS 미러가 똑같이 계산할 수 있어야 해서** 이 해시를 쓴다.
+
+ SHA-256 은 브라우저에서 동기로 못 구한다(SubtleCrypto 는 async 라 렌더 루프에서 못 쓴다).
+ 미러가 지문을 못 구하면 프리뷰는 자기가 그리는 프레임이 얼린 해부와 맞는지 확인할
+ 방법이 없고, 그러면 굽기만 자가 복구하고 프리뷰는 낡은 숫자로 계속 그린다
+ (validator 실측 2026-07-25: 픽셀 편집 후 최대 617바이트, 불투명 픽셀 수까지 불일치).
+ 충돌 위험은 "프레임이 바뀌었나" 판정에는 무시할 수준이다."""
+ h = 2166136261
+ for b in data:
+ h = ((h ^ b) * 16777619) & 0xFFFFFFFF
+ return h
+
+
+def _num(value) -> str:
+ """키에 들어갈 수의 정규형 — 파이썬과 JS 가 **같은 문자열**을 내야 한다.
+
+ `f"{v:.6f}"` 와 `v.toFixed(6)` 는 6번째 자리가 정확히 반올림 경계일 때 갈린다(파이썬은
+ 십진 표현 기준 round-half-even, JS 는 이진값 기준). `repr` 계열도 지수 표기가 다르다
+ (`1e-07` vs `1e-7`). 그래서 **부동소수 곱·합·floor 만** 쓴다 — 양쪽 다 IEEE754 double 이라
+ 같은 입력에 같은 결과가 나오는 연산이다."""
+ if value is None:
+ return "~"
+ if isinstance(value, bool):
+ return "1" if value else "0"
+ if isinstance(value, (int, float)):
+ return str(math.floor(float(value) * 1000000.0 + 0.5))
+ return str(value)
+
+
+def _canon(value) -> str:
+ """키에 들어갈 값의 정규 직렬화 — dict 는 키 정렬, 수는 `_num`."""
+ if isinstance(value, dict):
+ return "{" + ",".join(f"{k}={_canon(value[k])}" for k in sorted(value, key=str)) + "}"
+ if isinstance(value, (list, tuple)):
+ return "[" + ",".join(_canon(v) for v in value) + "]"
+ return _num(value)
+
+
+def reference_key(*, state: str, variant: str, request_stamp: str, source_index: int,
+ source_stamp: str, pixel_ops, transform) -> str:
+ """기준 프레임의 **정체성** — 그 프레임을 만드는 입력들로만 만든다. 픽셀은 안 읽는다.
+
+ 예전엔 이게 *변형 결과 RGBA* 의 해시였다. 그런데 굽기는 `apply_transform` 에서
+ **BICUBIC** 으로 리샘플하고(`snap_scale` 없는 런 = 기본 런 전부) 웹뷰 캔버스는
+ `imageSmoothingEnabled=false`, 즉 **NEAREST** 다. 같은 원본에 같은 변형을 걸어도 두 쪽이
+ 만드는 그림이 다르니 지문은 **영구 불일치**였다 — 회전·확대가 걸린 줄은 프리뷰가 영원히
+ 원본으로 떨어지고 영상 내보내기가 영구 차단됐으며, 안내대로 "해부를 갱신" 해도 라우트가
+ 또 BICUBIC 프레임으로 같은 숫자를 만들어 **절대 안 풀렸다** (validator 실측 2026-07-26:
+ rotate 3°에서 555px 상이, 정수 이동만 걸린 줄은 우연히 일치).
+
+ 입력을 해시하면 리샘플러가 식에서 아예 빠진다. 여기 들어가는 값은 전부 사이드카(사람의
+ 의도)와 서버가 준 파일 스탬프라, 웹뷰가 **동기로 정확히** 아는 것들이다. 덤으로 웹뷰가
+ 신선도 판정에 캔버스를 읽을 이유가 없어져서 "어느 캔버스를 쟀나" 계열 결함(9·10라운드)이
+ 구조적으로 사라진다.
+
+ 실패 방향도 안전하다: 런을 복사해 mtime 이 바뀌면 키가 달라져 **시끄럽게 거부**하고 한 번
+ 다시 잰다 — 조용히 낡은 숫자로 굽는 반대 방향이 아니다.
+
+ ## 왜 이 재료들인가 (그리고 셀·snap 이 왜 없는가)
+
+ 재료는 전부 웹뷰가 **동기로 정확히** 아는 것이어야 한다. 사이드카 값(변종·픽셀편집·변형)은
+ 웹뷰가 소유한 canon 이고, 파일 스탬프 둘은 서버가 상태 응답에 실어 보낸다.
+
+ 셀 크기와 `snap_scale` 은 뺐다 — 둘 다 `sprite-request.json` 과 변종의 순수 함수인데,
+ 변종은 이미 키에 있고 request 는 `request_stamp` 로 통째로 덮인다. 파생값을 또 넣으면
+ 양쪽이 그 파생을 각자 재구현해야 하고(웹뷰의 측정 k 는 `pixel_snap_scale` 과 다른
+ 검출기다) 거기서 드리프트가 난다. 원인을 덮는 편이 결과를 흉내내는 것보다 안전하다."""
+ # 정규화를 **키 안에서** 한다. 호출부에 맡기면 한쪽은 사이드카 원문(`{"rotate": 3}`)을,
+ # 다른 쪽은 항등 머지본(7키 전부)을 넘겨 같은 프레임이 다른 키를 갖는다 — 변형이 없는
+ # 프레임(대부분)이 정확히 그 모양이었다.
+ return "|".join((
+ "breathe-ref-v1", str(state), str(variant), str(request_stamp),
+ str(int(source_index)), str(source_stamp),
+ _canon(pixel_ops or {}), _canon(normalize_transform(transform)),
+ ))
+
+
+def anatomy_fingerprint(key: str) -> str:
+ """기준 프레임 키의 지문 — 변종·소스 인덱스는 읽을 수 있게 남기고 나머지는 해시한다.
+
+ 키를 그대로 쓰면 거부 메시지는 친절해지지만 사이드카가 픽셀 편집량만큼 부푼다(칠한
+ 점 하나가 키 한 조각이다). 앞머리 두 조각만 남겨 "어느 변종의 몇 번 프레임" 은
+ 보이게 하고, 입력 전체는 해시로 접는다."""
+ parts = key.split("|")
+ variant, index = (parts[2], parts[4]) if len(parts) > 5 else ("?", "?")
+ return f"{variant}:{index}:{_fnv1a(key.encode('utf-8')):08x}"
+
+
+def resolve_anatomy(reference: Image.Image, cfg: dict) -> Anatomy:
+ """**줄 전체가 공유하는 한 벌**을 기준 프레임에서 확정한다.
+
+ 해부는 **캐릭터의 속성이지 프레임의 속성이 아니다.** 깜빡임 프레임이라고 목이 옮겨
+ 가지 않는다. 프레임마다 다시 재면 검출 지터로 `rigid_row` 가 흔들리고(실측 2↔3),
+ 그러면 "강체 구간" 이 프레임 간 **같은 구간이 아니게 된다** — 이 모듈의 핵심 계약이
+ 프레임별 재검출 때문에 깨지는 것이다. 게다가 사이드카에는 해부가 한 벌뿐이라
+ 프리뷰(미러)는 그 한 벌로 그리고 굽기는 프레임마다 다른 값으로 구워 갈렸다
+ (validator 실측 2026-07-25: 골든 픽스처 idle 4프레임에서 최대 220바이트, 불투명 픽셀
+ **수**까지 불일치 — 위치가 아니라 그림이 달랐다).
+
+ 그래서 지문은 **기준 프레임 하나**를 지킨다: 스프라이트가 바뀌면 여기서 잡혀 한 번
+ 다시 재고 그 사실을 보고한다. 나머지 프레임이 서로 다른 것은 정상이며 재검출 사유가
+ 아니다.
+
+ `rigid_row` 는 **사람의 의도(입력)** 이고 `anatomy` 는 거기서 파생된 **캐시**다.
+ 그래서 얼린 값이 override 와 어긋나면 캐시가 낡은 것이므로 다시 잰다 — 얼린 값을
+ 그대로 쓰면 사람이 고친 숫자가 조용히 버려진다 (validator 검증 2026-07-25: cfg 33 을
+ 줘도 얼린 23 이 구워졌고 경고도 없었다).
+
+ **굽기는 얼린 해부를 쓰지 않는다 — 매번 자기 기준 프레임에서 다시 잰다.** 굽기는
+ 진짜 프레임을 손에 들고 있으니 재는 게 언제나 옳고, 얼린 값은 웹뷰가 미리보기를
+ 그리려고 들고 있는 **캐시**일 뿐이다 (C11: `rigid_row` 는 의도, `anatomy` 는 캐시).
+ 예전엔 여기서 얼린 값을 신뢰할지 판정하려고 프레임 RGBA 를 해시했는데, 그 해시가
+ 웹뷰와 영구 불일치를 만드는 원흉이었다 — `reference_key` 주석 참조.
+
+ 사이드카 캐시가 실제로 구운 값과 어긋났는지는 `anatomy_report` 가 대조해서 보고한다.
+ "재검출했나(proxy)" 보다 "**사이드카와 다른 값을 구웠나**" 가 원칙 6이 요구하는 바로
+ 그 관측이다."""
+ return analyze(reference, rigid_row=cfg.get("rigid_row"),
+ axis_x=cfg.get("axis_x"), torso_half=cfg.get("torso_half"))
+
+
+def anatomy_report(images: list[Image.Image], cfg: dict) -> dict:
+ """굽기가 실제로 쓴 해부를 manifest 에 실을 형태로 — 자가 복구를 관측 가능하게.
+
+ 줄 전체가 **한 벌**을 쓰므로 보고도 한 벌이다. 예전엔 프레임별로 재서
+ `rigid_row_varies` 를 실어 보냈는데, 그건 관측이 아니라 결함의 증상이었다 —
+ 경계가 프레임마다 움직이면 강체 구간이 프레임 간 같은 구간이 아니다."""
+ if not images:
+ return {"anatomy": None, "matches_sidecar": True, "warnings": []}
+ anat = resolve_anatomy(images[0], cfg)
+ baked = anat.as_dict()
+ frozen = cfg.get("anatomy")
+ # 사이드카가 들고 있던 캐시와 실제로 구운 값의 **대조**. 캐시가 없으면 대조할 게 없다.
+ # 지문 비교가 아니라 값 비교인 게 핵심이다 — 지문은 웹뷰가 자기 미리보기의 신선도를
+ # 판정하는 도구이고, 여기서 궁금한 건 "사이드카 숫자와 다른 그림을 구웠나" 다.
+ stale = None
+ if isinstance(frozen, dict):
+ stale = {k: [frozen.get(k), v] for k, v in baked.items()
+ if k in frozen and frozen.get(k) != v}
+ return {
+ "anatomy": baked,
+ "matches_sidecar": not stale,
+ "sidecar_drift": stale or None,
+ "warnings": sorted(anat.warnings),
+ }
+
+
+def freeze_anatomy(frame: Image.Image, cfg: dict, key: str) -> dict:
+ """큐레이션 시점에 해부를 1회 돌려 사이드카에 얼릴 dict 를 만든다.
+
+ 이걸 사이드카에 넣어두면 굽기와 큐레이터 웹뷰가 같은 숫자를 읽는다 — 웹뷰는
+ 검출을 재구현하지 않고 warp 만 미러링하면 된다 (검출 중복 제거)."""
+ anat = analyze(frame, rigid_row=cfg.get("rigid_row"),
+ axis_x=cfg.get("axis_x"), torso_half=cfg.get("torso_half"))
+ return {**anat.as_dict(), "fingerprint": anatomy_fingerprint(key)}
+
+
+# ── 재생 시퀀스 계약 (compose/GIF 진입점) ───────────────────────────
+
+def fit_breathe_pattern(seq_len: int, cfg: dict) -> list[float]:
+ """시퀀스 길이에 딱 맞는 호흡 위상 시퀀스 (길이 == seq_len, 루프 불변).
+
+ 위상은 [0, 1) 의 연속 값이다 — 구 방식의 정수 분할선 단계가 아니다. breaths 회가
+ 시퀀스 안에서 정확히 반복되므로 루프 이음매가 없고, 등분 보정도 필요 없다.
+
+ **정수 나머지를 먼저 취한다.** `(i*breaths/seq_len) % 1.0` 로 쓰면 수학적으로 같은
+ 위상이 서로 다른 double 이 되어(18슬롯 3호흡: 유니크 6 -> 14) 아틀라스 칸 재사용이
+ 표현 노이즈로 깨진다. 분자를 정수로 접고 한 번만 나누면 반복 위상이 비트 동일하다
+ (validator 검증 2026-07-25: 시트 1344x192 -> 576x192)."""
+ if seq_len <= 0:
+ return []
+ breaths = max(1, int(cfg.get("breaths", 1)))
+ return [((i * breaths) % seq_len) / seq_len for i in range(seq_len)]
+
+
+def fitted_breath_count(seq_len: int, cfg: dict) -> int:
+ """실제 적용되는 호흡 횟수 — 연속 위상이라 요청값이 그대로 성립한다."""
+ if seq_len <= 0:
+ return 0
+ return max(1, int(cfg.get("breaths", 1)))
+
+
+def recommended_breathe_frames(cfg: dict, per_cycle: int = SMOOTH_CYCLE_FRAMES) -> int:
+ """호흡이 부드럽게 읽히려면 필요한 최소 재생-시퀀스 길이.
+
+ 정지 1컷 + 링크 복제로 프레임을 찍어내는 레시피(정지자세)는 이 값으로 복제 수를
+ 정한다: `clones = recommended_breathe_frames(cfg) - 1`. 유저가 이미 가진 프레임
+ 수를 줄이거나 호흡 횟수를 바꾸지 않는다 — 오직 프레임을 새로 만들 때의 목표다."""
+ return max(1, int(cfg.get("breaths", 1))) * max(2, per_cycle)
+
+
+def breathe_reads_smoothly(seq_len: int, cfg: dict, per_cycle: int = SMOOTH_CYCLE_FRAMES) -> bool:
+ """요청한 호흡 횟수가 이 시퀀스 길이에서 부드럽게 렌더되는가 (관측용)."""
+ if seq_len <= 0:
+ return False
+ return seq_len // max(1, int(cfg.get("breaths", 1))) >= max(2, per_cycle)
+
+
+def phase_frame(frame: Image.Image, cfg: dict, phase: float,
+ anat: Anatomy | None = None) -> Image.Image:
+ """프레임에 호흡 위상 하나(0 <= phase < 1)를 적용.
+
+ `anat` 를 주면 그것을 쓴다 — 줄 전체가 한 벌을 공유해야 하므로 호출자가 한 번
+ 확정해 넘기는 게 정석이다. 생략하면 이 프레임을 기준으로 확정한다 (단발 호출용)."""
+ if anat is None:
+ anat = resolve_anatomy(frame, cfg)
+ depth = float(cfg.get("depth", DEFAULT_DEPTH))
+ raw_dx = cfg.get("depth_x")
+ depth_x = None if raw_dx is None else float(raw_dx)
+ for axis, d in (("depth", depth), ("depth_x", depth_x)):
+ if d is None:
+ continue
+ strain = row_strain(anat, d)
+ if strain > MAX_ROW_STRAIN:
+ raise SystemExit(
+ f"breathe: 행당 변형({axis}) {strain:.3f} > 상한 {MAX_ROW_STRAIN} — 변형 구간이 너무 "
+ f"좁다 (강체 경계 {anat.rigid_row}/{anat.height}, 정규화 기준 {anat.basis_row}). "
+ f"{axis} 를 낮추거나 rigid_row 를 올려라. 조용히 깎지 않는다.")
+ return _warp(frame, anat, depth, float(cfg.get("lag", DEFAULT_LAG)), phase, depth_x=depth_x)
+
+
+def bake_breathe_sequence(images: list[Image.Image], cfg: dict) -> tuple[list[Image.Image], list[float]]:
+ """재생 시퀀스에 호흡 레이어를 굽는다 -> (프레임들, 적용 위상들).
+
+ 출력 길이 = 입력 길이 (루프 불변 — 루프는 기존 프레임 그대로, 호흡이 그 안에서
+ breaths 회 딱 떨어진다)."""
+ if not images:
+ return images, []
+ phases = fit_breathe_pattern(len(images), cfg)
+ anat = resolve_anatomy(images[0], cfg) # 줄 전체가 한 벌을 공유한다
+ return [phase_frame(images[i], cfg, phases[i], anat) for i in range(len(images))], phases
diff --git a/sprite_gen/effects/interpolate.py b/sprite_gen/effects/interpolate.py
new file mode 100644
index 0000000..4f58cc6
--- /dev/null
+++ b/sprite_gen/effects/interpolate.py
@@ -0,0 +1,273 @@
+# SPDX-License-Identifier: Apache-2.0
+"""AI 프레임 보간 — 한 상태의 두 프레임 사이 중간(in-between) 프레임을 만들어 테이크로 기록한다.
+
+파이프라인 도크트린과의 관계: "AI 개입은 raw 생성 한 곳뿐" — 보간도 raw 단계의
+AI 생성이다. 산출물은 최종 프레임이 아니라 **테이크 raw** (`raw/<state>.takes/<label>.png`
++ request `states.<state>.takes`) 로 기록되고, 논리 프레임은 언제나 기존 결정론
+추출 경로(크로마 제거 → 컴포넌트 → 격자 스냅 → 팔레트)가 굽는다.
+
+백엔드 = **생성형** (`sprite_gen.gen`: codex `image_gen` / grok Imagine, 기본 codex).
+플로우 기반 VFI(RIFE)는 파기했다 (maintainer 확정 2026-07-17): 외형이 변하는 픽셀아트
+보간에서 VFI 는 구조적으로 크로스페이드(블러 잔상)를 내고, 3-way 실측 비교
+(hero down_action 팔스윙: codex/grok/RIFE)에서 생성형이 중간 포즈를 깨끗한
+픽셀로 그려내 압승했다 — 근거 시트 `tween-3way-compare.png` (트레이 2026-07-17).
+
+인증 전제 (GUI 버튼 포함): 생성은 항상 **서버 머신의 provider CLI** (`codex`/`grok`)
+가 수행한다 — 브라우저·웹뷰에는 어떤 자격증명도 지나가지 않는다. 해당 CLI 가
+이 머신에 설치·로그인(ChatGPT OAuth / xAI OAuth)되어 있어야 하며, 미인증이면
+provider 가 요란하게 실패하고 그 메시지가 CLI/뷰 상태줄에 그대로 표면화된다.
+설정 절차는 [`docs/gen.md`](../docs/gen.md), 보간 관점 가이드는
+[`docs/frame-interpolation.md`](../docs/frame-interpolation.md).
+
+사용:
+ python3 scripts/interpolate_frames.py --run-dir <run> --state down_idle \
+ --between 1 2 [--provider codex|grok] [--t 0.5] [--label blink_mid] [--extract]
+
+- `--between A B`: 그 상태 primary 스트립의 프레임 인덱스 두 개 (추출된 컴포넌트 순서).
+- `--provider`: 생성 백엔드 (기본 codex — 3-way 비교 승자).
+- `--t`: 보간 시점 (기본 0.5 = 정중앙). 프롬프트의 포즈 배분 문구로 반영된다.
+- `--label`: 테이크 라벨 (기본 `tween_<A>_<B>_t<t>`). 같은 라벨 재실행 = 같은 파일
+ 덮어쓰기 (멱등).
+- `--extract`: 기록 후 **전체 배치** 재추출까지 수행. 부분 추출은 run-wide 팔레트가
+ 배치 구성에 따라 달라지므로(CHANGELOG v1.56.17 known limitation) 전체 배치만 지원.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import shutil
+import sys
+import tempfile
+from pathlib import Path
+from typing import Any, Callable
+
+from PIL import Image
+
+from sprite_gen.frames.extract import (extract_component_images, register_row_frames,
+ remove_chroma_background_ycbcr, tighten_components)
+from sprite_gen.spec.layout import raw_rel, take_raw_rel
+from sprite_gen.spec.runio import load_request, write_request
+
+PROVIDERS = ("codex", "grok")
+
+# interpolator 시그니처: (img0 RGB, img1 RGB, t, prompt) -> mid RGB. 테스트는 스텁을 주입한다.
+Interpolator = Callable[[Image.Image, Image.Image, float, str], Image.Image]
+
+
+def gen_interpolator(provider: str = "codex") -> Interpolator:
+ """생성형 in-between interpolator — 두 정합 프레임을 ref 로 물려 중간 포즈를 그리게 한다."""
+ if provider not in PROVIDERS:
+ raise SystemExit(f"unknown interpolation provider: {provider} (choose from {PROVIDERS})")
+ from sprite_gen.gen import generate_image
+
+ def run(img0: Image.Image, img1: Image.Image, t: float, prompt: str) -> Image.Image:
+ workdir = Path(tempfile.mkdtemp(prefix="sprite-gen-tween-"))
+ try:
+ ref_a = workdir / "ref-a.png"
+ ref_b = workdir / "ref-b.png"
+ out = workdir / "mid.png"
+ img0.save(ref_a)
+ img1.save(ref_b)
+ generate_image(provider, prompt, out, refs=[ref_a, ref_b])
+ with Image.open(out) as image:
+ return image.convert("RGB").copy()
+ finally:
+ shutil.rmtree(workdir, ignore_errors=True)
+
+ return run
+
+
+def tween_prompt(request: dict[str, Any], t: float) -> str:
+ """보간 생성 프롬프트 — request 의 캐릭터/크로마 진실에서 결정론으로 조립한다."""
+ character = str(request.get("character", {}).get("description") or "the same character")
+ chroma = request["chroma_key"]
+ if abs(t - 0.5) < 1e-9:
+ blend = "the precise halfway in-between of A and B"
+ else:
+ nearer = "A" if t < 0.5 else "B"
+ blend = (f"the in-between of A and B at t={t:g} on the A->B motion "
+ f"(closer to {nearer})")
+ return (
+ "Pixel art animation IN-BETWEEN frame task. Reference image 1 is frame A and "
+ "reference image 2 is frame B of the same character's animation. "
+ f"Draw exactly ONE full-body pose that is {blend}: limbs and body positioned "
+ "between the two reference poses. "
+ f"Character identity must match the references exactly ({character}). "
+ "Same clean pixel-art style, same pixel block size, same scale, and same "
+ "position in the canvas as the references. "
+ f"Flat solid chroma {chroma['name']} {chroma['hex']} background filling the "
+ "entire canvas. No shadows, no text, no labels, no frame borders, no arrows, "
+ "no multiple panels — exactly one figure on the flat background."
+ )
+
+
+def aligned_pair_on_chroma(
+ strip: Image.Image, frame_count: int, index_a: int, index_b: int,
+ chroma_rgb: tuple[int, int, int],
+) -> tuple[Image.Image, Image.Image]:
+ """스트립에서 두 프레임 컴포넌트를 뽑아 상체 정합(register) 후 같은 캔버스에 앉힌다.
+
+ 정합이 핵심이다: 정적인 몸 픽셀이 두 ref 에서 같은 위치에 있어야 생성 모델이
+ "움직인 부위만 다른 같은 그림 두 장" 으로 읽는다. 배경은 요청 크로마 단색 —
+ 생성 결과도 같은 배경을 유지하도록 프롬프트가 요구하고, 추출의 크로마 제거가
+ 그대로 처리한다."""
+ cleaned = remove_chroma_background_ycbcr(strip, chroma_rgb)
+ components = extract_component_images(cleaned, frame_count)
+ if not components:
+ raise SystemExit(f"could not extract {frame_count} components from the strip")
+ for index in (index_a, index_b):
+ if not 0 <= index < len(components):
+ raise SystemExit(f"frame index {index} out of range 0..{len(components) - 1}")
+ tight = tighten_components(components)
+ pair = register_row_frames([tight[index_a], tight[index_b]])
+ width, height = pair[0].size
+ padded_w = (width + 31) // 32 * 32
+ padded_h = (height + 31) // 32 * 32
+ outputs = []
+ for frame in pair:
+ canvas = Image.new("RGBA", (padded_w, padded_h), chroma_rgb + (255,))
+ canvas.alpha_composite(frame, ((padded_w - width) // 2, padded_h - height))
+ outputs.append(canvas.convert("RGB"))
+ return outputs[0], outputs[1]
+
+
+def _chroma_content_bbox(image: Image.Image, chroma_rgb: tuple[int, int, int],
+ tolerance: int = 60) -> tuple[int, int, int, int] | None:
+ """크로마 단색 배경 위 피사체의 bbox — 크로마와 충분히 다른 픽셀만 콘텐츠로 센다."""
+ rgb = image.convert("RGB")
+ pixels = rgb.load()
+ mask = Image.new("L", rgb.size, 0)
+ out = mask.load()
+ cr, cg, cb = chroma_rgb
+ for y in range(rgb.height):
+ for x in range(rgb.width):
+ r, g, b = pixels[x, y]
+ if abs(r - cr) + abs(g - cg) + abs(b - cb) > tolerance:
+ out[x, y] = 255
+ return mask.getbbox()
+
+
+def normalize_tween_scale(mid: Image.Image, img0: Image.Image, img1: Image.Image,
+ chroma_rgb: tuple[int, int, int]) -> Image.Image:
+ """생성된 중간 프레임을 참조 쌍의 스케일에 맞춘다 (raw 단계 전처리, 결정론).
+
+ RIFE 시절엔 입출력 캔버스가 같아 스케일이 보장됐지만, 생성형은 모델이 피사체를
+ 다른 크기로 그릴 수 있다 (회귀 2026-07-17: tween 이 32×58 로 나와 형제 28×48
+ 보다 14% 커짐 — 재생 시 프레임에서 캐릭터가 튐, maintainer 발견). 참조 두 장의 콘텐츠
+ 높이 평균을 목표로 중간 프레임의 콘텐츠 높이를 리스케일하고, 참조와 같은 크로마
+ 캔버스에 바닥 정렬로 다시 앉힌다. 이후의 픽셀 언페이크 추출이 격자를 다시 굽는다."""
+ ref_boxes = [_chroma_content_bbox(im, chroma_rgb) for im in (img0, img1)]
+ mid_box = _chroma_content_bbox(mid, chroma_rgb)
+ if not all(ref_boxes) or not mid_box:
+ raise SystemExit("tween scale normalization failed: could not find content on the chroma background")
+ target_h = sum(b[3] - b[1] for b in ref_boxes) / 2.0
+ mid_h = mid_box[3] - mid_box[1]
+ factor = target_h / mid_h
+ content = mid.convert("RGB").crop(mid_box)
+ scaled = content.resize((max(1, round(content.width * factor)),
+ max(1, round(content.height * factor))),
+ Image.Resampling.LANCZOS)
+ canvas = Image.new("RGB", img0.size, chroma_rgb)
+ left = (canvas.width - scaled.width) // 2
+ top = canvas.height - scaled.height - (img0.height - ref_boxes[0][3]) # 참조와 같은 바닥선
+ canvas.paste(scaled, (left, max(0, top)))
+ return canvas
+
+
+def write_take(run_dir: Path, request: dict[str, Any], state: str, label: str,
+ image: Image.Image) -> Path:
+ """중간 프레임을 테이크 raw 로 기록하고 request 의 takes 선언을 갱신한다 (멱등).
+
+ Isolation (2026-07-19): 생성 동안 다른 쓰기(다른 행 리롤/fps 수정)가 있었을 수
+ 있으므로, 시작 시점 request 객체가 아니라 publish_guard 안에서 fresh 재독으로만
+ takes 를 갱신한다 — lost update 방지 (reroll.record_take 와 같은 계약)."""
+ from sprite_gen.spec.runio import publish_guard
+
+ rel = take_raw_rel(request, state, label)
+ target = run_dir / rel
+ target.parent.mkdir(parents=True, exist_ok=True)
+ image.save(target)
+ with publish_guard(run_dir):
+ # 락 안 fresh 재독도 게이트 경유 — 이관 판정·두 키 hard fail 이 한 곳에만 있어야 한다
+ # (게이트는 읽기만 한다).
+ fresh = load_request(run_dir)
+ takes = fresh["states"][state].setdefault("takes", [])
+ entry = next((t for t in takes if t.get("label") == label), None)
+ if entry is None:
+ takes.append({"label": label, "frames": 1})
+ else:
+ entry["frames"] = 1
+ # 쓰기도 게이트 경유 — 테이크 기록이 디스크 스키마를 바꾸지 않는다 (reroll 과 동일).
+ write_request(run_dir, fresh)
+ return target
+
+
+def interpolate_between(run_dir: Path | str, state: str, index_a: int, index_b: int,
+ t: float = 0.5, label: str | None = None,
+ provider: str = "codex",
+ interpolator: Interpolator | None = None) -> Path:
+ """두 프레임 사이 중간 프레임을 만들어 테이크로 기록한다. 반환 = 테이크 raw 경로."""
+ run_dir = Path(run_dir)
+ # 읽기는 게이트만 (`load_request`): raw 로 읽으면 은퇴 키 런에서 이관이 비껴간다 —
+ # 리롤에서 실제로 났던 회귀와 같은 클래스다 (validator R1).
+ request = load_request(run_dir)
+ if state not in request.get("states", {}):
+ raise SystemExit(f"unknown state: {state}")
+ if not 0.0 < t < 1.0:
+ raise SystemExit(f"t must be inside (0, 1): {t}")
+ strip_path = run_dir / raw_rel(request, state)
+ if not strip_path.is_file():
+ raise SystemExit(f"raw strip missing: {strip_path}")
+ chroma_rgb = tuple(request["chroma_key"]["rgb"])
+ frame_count = int(request["states"][state]["frames"])
+ strip = Image.open(strip_path).convert("RGBA")
+ img0, img1 = aligned_pair_on_chroma(strip, frame_count, index_a, index_b, chroma_rgb)
+ run = interpolator or gen_interpolator(provider)
+ mid = run(img0, img1, t, tween_prompt(request, t))
+ mid = normalize_tween_scale(mid, img0, img1, chroma_rgb)
+ label = label or f"tween_{index_a}_{index_b}_t{t:g}".replace(".", "p")
+ if "/" in label or label.startswith("."):
+ raise SystemExit(f"take label must be filesystem-safe: {label!r}")
+ target = write_take(run_dir, request, state, label, mid)
+ print(f"[interpolate] take written: {target.relative_to(run_dir)} "
+ f"(state={state}, frames {index_a}<->{index_b}, t={t})")
+ return target
+
+
+def _build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
+ parser.add_argument("--run-dir", required=True)
+ parser.add_argument("--state", required=True)
+ parser.add_argument("--between", nargs=2, type=int, required=True,
+ metavar=("FROM", "TO"), help="primary 스트립의 프레임 인덱스 두 개")
+ parser.add_argument("--provider", choices=PROVIDERS, default="codex",
+ help="생성 백엔드 (기본 codex — 3-way 실측 비교 승자)")
+ parser.add_argument("--t", type=float, default=0.5, help="보간 시점 (0..1, 기본 0.5)")
+ parser.add_argument("--label", default=None, help="테이크 라벨 (기본 tween_<A>_<B>_t<t>)")
+ parser.add_argument("--extract", action="store_true",
+ help="기록 후 전체 배치 재추출까지 수행 (부분 추출은 팔레트 배치 결합 때문에 지원하지 않음)")
+ return parser
+
+
+def main(argv: list[str] | None = None) -> int:
+ args = _build_parser().parse_args(argv)
+ interpolate_between(args.run_dir, args.state, args.between[0], args.between[1],
+ t=args.t, label=args.label, provider=args.provider)
+ if args.extract:
+ from sprite_gen.frames import extract as extract_module
+ code = extract_module.run(run_dir=Path(args.run_dir))
+ if code != 0:
+ return code
+ print("[interpolate] full-batch re-extraction done")
+ else:
+ # 인터프리터는 sys.executable 로 찍는다 — 이 힌트는 붙여넣어 바로 실행되는
+ # 명령이고, 전역 `python3` 는 이 패키지의 의존(NumPy/Pillow)이 없는 다른
+ # 인터프리터일 수 있다 (SKILL.md "실행 인터프리터" 게이트).
+ print("[interpolate] next: re-extract the FULL batch so the shared palette stays "
+ f"consistent -> {sys.executable} -m sprite_gen.frames.extract --run-dir {args.run_dir}")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/sprite_gen/effects/recolor.py b/sprite_gen/effects/recolor.py
new file mode 100644
index 0000000..368320b
--- /dev/null
+++ b/sprite_gen/effects/recolor.py
@@ -0,0 +1,486 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Deterministic palette-swap bake: one base sheet + a recolor spec -> N variant
+sheets, in a single command.
+
+Dot art lives and dies by palette control, so this bakes colour variants into
+finished sheets instead of tinting at runtime: a baked sheet is QA-able and
+costs the renderer nothing. The swap is exact by default — a pixel's RGB must
+equal a source colour to be replaced — because a fuzzy match would recolour
+anti-aliased edge pixels the artist never intended. A ``tolerance`` mode exists
+for soft-edged art, but it is opt-in.
+
+No Silent Fallback is the load-bearing rule here (see maintainer's eight invariants):
+a colour outside the map is never quietly left behind. Every bake reports, per
+variant, exactly how many pixels each source colour replaced, which map sources
+never matched (a spec typo), and which opaque colours in the sheet the map did
+not cover (passed through unchanged, but named and counted). Same input bytes ->
+same output bytes: the bake does no floating-point resampling and PIL's PNG
+encoder is deterministic, so a variant sheet is reproducible for regression QA.
+
+Two operations share this module:
+
+- ``recolor-palette`` scans a base sheet and drafts a palette map (the distinct
+ opaque colours, by frequency) so a consumer can author a recolor spec without
+ eyedropping by hand.
+- ``recolor`` bakes the variants from ``base sheet + spec``.
+
+Geometry is never touched — recolour only rewrites RGB on matching pixels and
+preserves alpha — so a manifest describing the base atlas describes every
+variant. Pass ``--manifest`` and each variant gets a sibling manifest with its
+sheet-filename fields repointed, ready to drop into the runtime beside the base.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+from pathlib import Path
+
+from PIL import Image
+
+from sprite_gen._deps import np
+from sprite_gen.spec.runio import atomic_save_image, atomic_write_text
+
+# Opaque-enough to count as art. Edge pixels below this are treated as
+# background bleed, not recolour targets (the extraction chain already soft-keys
+# them). 8/255 matches compose-gif's alpha floor so the two agree on "a pixel".
+DEFAULT_ALPHA_THRESHOLD = 8
+# A passthrough report on a photographic sheet could list thousands of colours;
+# cap the list but announce the cap (no silent truncation) so "0 passthrough"
+# and "capped at 64 of 900" never look the same.
+PASSTHROUGH_REPORT_CAP = 64
+
+PALETTE_KIND = "sprite-gen-palette"
+SPEC_KIND = "sprite-gen-recolor"
+REPORT_KIND = "sprite-gen-recolor-report"
+
+# Where a run-dir bake puts its variants, and what it names the report. These are
+# the one place the convention lives: the bake writes here (`_resolve_base_and_manifest`
+# defaults `--out-dir` to `<run-dir>/variants`) and the curation webview looks here
+# (`load_report`). A second copy of either string is a second truth.
+VARIANTS_DIRNAME = "variants"
+DEFAULT_REPORT_NAME = "recolor.report.json"
+
+# Manifest string fields that name the atlas image, repointed per variant. Only
+# these known keys are rewritten; an unknown schema is copied verbatim.
+MANIFEST_SHEET_FIELDS = ("atlas", "game_input", "sprite_sheet_alpha", "sprite_sheet")
+
+
+def parse_hex(value: str) -> tuple[int, int, int]:
+ """Parse ``#RRGGBB`` (or ``RRGGBB``) into an ``(r, g, b)`` tuple."""
+ text = value.strip().lstrip("#")
+ if len(text) != 6:
+ raise ValueError(f"expected #RRGGBB, got {value!r}")
+ try:
+ return tuple(int(text[i : i + 2], 16) for i in (0, 2, 4)) # type: ignore[return-value]
+ except ValueError as exc:
+ raise ValueError(f"invalid hex colour {value!r}") from exc
+
+
+def format_hex(rgb: tuple[int, int, int]) -> str:
+ return "#{:02x}{:02x}{:02x}".format(*rgb)
+
+
+def _load_rgba(path: Path) -> np.ndarray:
+ """Load an image as an ``(H, W, 4)`` uint8 array."""
+ with Image.open(path) as im:
+ return np.asarray(im.convert("RGBA"), dtype=np.uint8)
+
+
+def _packed_rgb(arr: np.ndarray) -> np.ndarray:
+ """Pack the RGB channels of an ``(H, W, 4)`` array into ``(H, W)`` uint32."""
+ rgb = arr[:, :, :3].astype(np.uint32)
+ return (rgb[:, :, 0] << 16) | (rgb[:, :, 1] << 8) | rgb[:, :, 2]
+
+
+def _pack_color(rgb: tuple[int, int, int]) -> int:
+ return (rgb[0] << 16) | (rgb[1] << 8) | rgb[2]
+
+
+def _color_histogram(
+ arr: np.ndarray, opaque: np.ndarray
+) -> list[tuple[tuple[int, int, int], int]]:
+ """Distinct opaque colours as ``[(rgb, pixels), ...]``, sorted by count desc
+ then hex asc — a total order, so the draft is deterministic."""
+ packed = _packed_rgb(arr)[opaque]
+ if packed.size == 0:
+ return []
+ values, counts = np.unique(packed, return_counts=True)
+ out = []
+ for value, count in zip(values.tolist(), counts.tolist()):
+ rgb = ((value >> 16) & 0xFF, (value >> 8) & 0xFF, value & 0xFF)
+ out.append((rgb, int(count)))
+ out.sort(key=lambda item: (-item[1], item[0]))
+ return out
+
+
+# --- palette extraction helper ------------------------------------------------
+
+
+def extract_palette(
+ base: Path,
+ *,
+ alpha_threshold: int = DEFAULT_ALPHA_THRESHOLD,
+ max_colors: int | None = None,
+) -> dict:
+ """Draft a palette map from a base sheet: its distinct opaque colours by
+ frequency. This is authoring scaffolding, not a swap — the consumer edits
+ the draft into a recolor spec's ``map`` targets."""
+ arr = _load_rgba(base)
+ opaque = arr[:, :, 3] > alpha_threshold
+ histogram = _color_histogram(arr, opaque)
+ dropped = 0
+ if max_colors is not None and len(histogram) > max_colors:
+ dropped = sum(count for _rgb, count in histogram[max_colors:])
+ histogram = histogram[:max_colors]
+ palette = {
+ "version": 1,
+ "kind": PALETTE_KIND,
+ "source": base.name,
+ "alpha_threshold": alpha_threshold,
+ "color_count": len(histogram),
+ "colors": [
+ {"hex": format_hex(rgb), "rgb": list(rgb), "pixels": count}
+ for rgb, count in histogram
+ ],
+ }
+ if dropped:
+ # No silent cap: --max-colors dropped real pixels; say how many.
+ palette["dropped_colors_pixels"] = dropped
+ palette["dropped_below_rank"] = max_colors
+ return palette
+
+
+# --- recolor bake -------------------------------------------------------------
+
+
+def _load_spec(spec_path: Path) -> dict:
+ spec = json.loads(Path(spec_path).read_text(encoding="utf-8"))
+ if spec.get("kind") != SPEC_KIND:
+ raise SystemExit(
+ f"{spec_path}: not a recolor spec (kind must be {SPEC_KIND!r}, got {spec.get('kind')!r})"
+ )
+ variants = spec.get("variants")
+ if not isinstance(variants, list) or not variants:
+ raise SystemExit(f"{spec_path}: spec has no variants")
+ match = spec.get("match", "exact")
+ if match not in ("exact", "tolerance"):
+ raise SystemExit(f"{spec_path}: match must be 'exact' or 'tolerance', got {match!r}")
+ tolerance = int(spec.get("tolerance", 0))
+ if match == "exact" and tolerance:
+ # Two truths for one behaviour: exact means tolerance 0. Fail loud
+ # rather than silently pick one.
+ raise SystemExit(
+ f"{spec_path}: match 'exact' with tolerance {tolerance} is contradictory; "
+ f"set match 'tolerance' to use a non-zero tolerance"
+ )
+ names = [v.get("name") for v in variants]
+ if len(set(names)) != len(names):
+ raise SystemExit(f"{spec_path}: variant names must be unique, got {names}")
+ for variant in variants:
+ if not variant.get("name"):
+ raise SystemExit(f"{spec_path}: every variant needs a name")
+ if not isinstance(variant.get("map"), dict) or not variant["map"]:
+ raise SystemExit(f"{spec_path}: variant {variant.get('name')!r} has an empty map")
+ return {"match": match, "tolerance": tolerance, "variants": variants}
+
+
+def _resolve_map(variant_map: dict, spec_path: Path, name: str) -> list[tuple[tuple[int, int, int], tuple[int, int, int]]]:
+ pairs = []
+ seen_sources: set[tuple[int, int, int]] = set()
+ for src_hex, tgt_hex in variant_map.items():
+ try:
+ src = parse_hex(src_hex)
+ tgt = parse_hex(tgt_hex)
+ except ValueError as exc:
+ raise SystemExit(f"{spec_path}: variant {name!r}: {exc}") from exc
+ if src in seen_sources:
+ raise SystemExit(f"{spec_path}: variant {name!r}: source {src_hex} mapped twice")
+ seen_sources.add(src)
+ pairs.append((src, tgt))
+ return pairs
+
+
+def _bake_variant_exact(
+ arr: np.ndarray, opaque: np.ndarray, pairs
+) -> tuple[np.ndarray, list[dict], np.ndarray]:
+ """Exact-match bake. Returns (recoloured array, per-source hit records,
+ covered mask)."""
+ packed = _packed_rgb(arr)
+ out = arr.copy()
+ covered = np.zeros(arr.shape[:2], dtype=bool)
+ records = []
+ for src, tgt in pairs:
+ mask = (packed == _pack_color(src)) & opaque & ~covered
+ hits = int(mask.sum())
+ if hits:
+ out[mask, 0] = tgt[0]
+ out[mask, 1] = tgt[1]
+ out[mask, 2] = tgt[2]
+ covered |= mask
+ records.append({"from": format_hex(src), "to": format_hex(tgt), "pixels": hits})
+ return out, records, covered
+
+
+def _bake_variant_tolerance(
+ arr: np.ndarray, opaque: np.ndarray, pairs, tolerance: int
+) -> tuple[np.ndarray, list[dict], np.ndarray]:
+ """Tolerance bake: an opaque pixel within Chebyshev ``tolerance`` of a
+ source is recoloured to that source's target; nearest source (L2) wins,
+ ties broken by map order. Deterministic — pure integer arithmetic."""
+ rgb = arr[:, :, :3].astype(np.int32)
+ out = arr.copy()
+ best_dist = np.full(arr.shape[:2], np.iinfo(np.int32).max, dtype=np.int32)
+ best_idx = np.full(arr.shape[:2], -1, dtype=np.int32)
+ for idx, (src, _tgt) in enumerate(pairs):
+ delta = np.abs(rgb - np.array(src, dtype=np.int32))
+ cheb = delta.max(axis=2)
+ l2 = (delta * delta).sum(axis=2)
+ within = opaque & (cheb <= tolerance)
+ # Strict-less keeps the earlier map entry on a tie (stable, deterministic).
+ take = within & (l2 < best_dist)
+ best_dist = np.where(take, l2, best_dist)
+ best_idx = np.where(take, idx, best_idx)
+ covered = best_idx >= 0
+ records = []
+ for idx, (src, tgt) in enumerate(pairs):
+ mask = best_idx == idx
+ hits = int(mask.sum())
+ if hits:
+ out[mask, 0] = tgt[0]
+ out[mask, 1] = tgt[1]
+ out[mask, 2] = tgt[2]
+ records.append({"from": format_hex(src), "to": format_hex(tgt), "pixels": hits})
+ return out, records, covered
+
+
+def _passthrough_report(
+ arr: np.ndarray, opaque: np.ndarray, covered: np.ndarray
+) -> tuple[list[dict], int, int]:
+ """Opaque colours the map did not cover: passed through unchanged, but named
+ and counted. Returns (top colours, total distinct count, total pixels)."""
+ leftover = opaque & ~covered
+ histogram = _color_histogram(arr, leftover)
+ total_colors = len(histogram)
+ total_pixels = sum(count for _rgb, count in histogram)
+ top = [
+ {"hex": format_hex(rgb), "pixels": count}
+ for rgb, count in histogram[:PASSTHROUGH_REPORT_CAP]
+ ]
+ return top, total_colors, total_pixels
+
+
+def _propagate_manifest(manifest_path: Path, out_dir: Path, sheet_name: str, variant_name: str) -> str:
+ manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
+ base_sheet = manifest_path.name # only for reference in log
+ for field in MANIFEST_SHEET_FIELDS:
+ if isinstance(manifest.get(field), str):
+ manifest[field] = sheet_name
+ target = out_dir / f"{variant_name}.manifest.json"
+ atomic_write_text(target, json.dumps(manifest, ensure_ascii=False, indent=2) + "\n")
+ return target.name
+
+
+def bake(
+ base: Path,
+ spec_path: Path,
+ out_dir: Path,
+ *,
+ manifest: Path | None = None,
+ alpha_threshold: int = DEFAULT_ALPHA_THRESHOLD,
+ report_name: str = DEFAULT_REPORT_NAME,
+) -> dict:
+ spec = _load_spec(spec_path)
+ arr = _load_rgba(base)
+ opaque = arr[:, :, 3] > alpha_threshold
+ out_dir.mkdir(parents=True, exist_ok=True)
+
+ variant_reports = []
+ for variant in spec["variants"]:
+ name = variant["name"]
+ pairs = _resolve_map(variant["map"], spec_path, name)
+ if spec["match"] == "exact":
+ recolored, records, covered = _bake_variant_exact(arr, opaque, pairs)
+ else:
+ recolored, records, covered = _bake_variant_tolerance(
+ arr, opaque, pairs, spec["tolerance"]
+ )
+ sheet_name = f"{name}.png"
+ atomic_save_image(Image.fromarray(recolored, "RGBA"), out_dir / sheet_name)
+
+ substituted = sum(record["pixels"] for record in records)
+ unused = [record for record in records if record["pixels"] == 0]
+ top, pass_colors, pass_pixels = _passthrough_report(arr, opaque, covered)
+ variant_report = {
+ "name": name,
+ "sheet": sheet_name,
+ "substituted_pixels": substituted,
+ "substitutions": sorted(records, key=lambda r: r["from"]),
+ "unused_sources": sorted(unused, key=lambda r: r["from"]),
+ "passthrough_pixels": pass_pixels,
+ "passthrough_color_count": pass_colors,
+ "passthrough_colors": top,
+ }
+ if pass_colors > len(top):
+ variant_report["passthrough_colors_truncated"] = pass_colors - len(top)
+ if manifest is not None:
+ variant_report["manifest"] = _propagate_manifest(
+ manifest, out_dir, sheet_name, name
+ )
+ variant_reports.append(variant_report)
+
+ report = {
+ "ok": True,
+ "kind": REPORT_KIND,
+ "base": base.name,
+ "match": spec["match"],
+ "tolerance": spec["tolerance"],
+ "alpha_threshold": alpha_threshold,
+ "variant_count": len(variant_reports),
+ "variants": variant_reports,
+ }
+ atomic_write_text(out_dir / report_name, json.dumps(report, ensure_ascii=False, indent=2) + "\n")
+ return report
+
+
+def load_report(
+ run_dir: Path,
+ *,
+ dirname: str = VARIANTS_DIRNAME,
+ report_name: str = DEFAULT_REPORT_NAME,
+) -> dict | None:
+ """The bake report of a run dir's variants, or ``None`` if nothing was baked.
+
+ ``None`` means exactly one thing — no report file — so a consumer can treat it
+ as "this run has no variants" without guessing. A file that exists but is not
+ a recolor report is an error, never an empty result: silently reading it as
+ "no variants" would hide a bake that wrote somewhere unexpected, and the
+ curation view would show nothing while the sheets sit on disk.
+ """
+ path = run_dir / 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}: not a recolor report (kind must be {REPORT_KIND!r}, got {report.get('kind')!r})"
+ )
+ return report
+
+
+# --- CLI ----------------------------------------------------------------------
+
+
+def _resolve_base_and_manifest(
+ base: Path | None,
+ run_dir: Path | None,
+ atlas: str,
+ manifest: Path | None,
+ out_dir: Path | None,
+) -> tuple[Path, Path | None, Path]:
+ """Resolve the base sheet, optional manifest, and out dir from either an
+ explicit ``--base`` or a ``--run-dir`` (mutually exclusive — no two truths)."""
+ if (base is None) == (run_dir is None):
+ raise SystemExit("pass exactly one of --base <sheet.png> or --run-dir <dir>")
+ if run_dir is not None:
+ resolved_base = run_dir / atlas
+ if not resolved_base.is_file():
+ raise SystemExit(f"no atlas {atlas!r} in run dir: {run_dir}")
+ resolved_manifest = manifest
+ if resolved_manifest is None:
+ candidate = run_dir / "manifest.json"
+ resolved_manifest = candidate if candidate.is_file() else None
+ resolved_out = out_dir if out_dir is not None else run_dir / "variants"
+ return resolved_base, resolved_manifest, resolved_out
+ if out_dir is None:
+ raise SystemExit("--out-dir is required with --base")
+ return base, manifest, out_dir
+
+
+def add_recolor_arguments(p: argparse.ArgumentParser) -> None:
+ p.add_argument("--base", type=Path, help="base sheet PNG to recolour")
+ p.add_argument("--run-dir", type=Path, help="run dir; base = <run-dir>/<atlas>, manifest auto-resolved")
+ p.add_argument("--atlas", default="sprite-sheet-alpha.png", help="atlas filename inside --run-dir")
+ p.add_argument("--spec", required=True, type=Path, help="recolor spec JSON")
+ p.add_argument("--out-dir", type=Path, help="output dir (default <run-dir>/variants)")
+ p.add_argument("--manifest", type=Path, help="source manifest to propagate per variant")
+ p.add_argument("--alpha-threshold", type=int, default=DEFAULT_ALPHA_THRESHOLD)
+ p.add_argument("--report", default=DEFAULT_REPORT_NAME)
+
+
+def run(
+ *,
+ base: Path | None = None,
+ run_dir: Path | None = None,
+ atlas: str = "sprite-sheet-alpha.png",
+ spec: Path,
+ out_dir: Path | None = None,
+ manifest: Path | None = None,
+ alpha_threshold: int = DEFAULT_ALPHA_THRESHOLD,
+ report: str = DEFAULT_REPORT_NAME,
+) -> int:
+ resolved_base, resolved_manifest, resolved_out = _resolve_base_and_manifest(
+ base, run_dir, atlas, manifest, out_dir
+ )
+ report_data = bake(
+ resolved_base,
+ spec,
+ resolved_out,
+ manifest=resolved_manifest,
+ alpha_threshold=alpha_threshold,
+ report_name=report,
+ )
+ summary = {
+ "ok": report_data["ok"],
+ "base": report_data["base"],
+ "match": report_data["match"],
+ "variants": [
+ {
+ "name": v["name"],
+ "sheet": str(resolved_out / v["sheet"]),
+ "substituted_pixels": v["substituted_pixels"],
+ "passthrough_pixels": v["passthrough_pixels"],
+ "passthrough_color_count": v["passthrough_color_count"],
+ }
+ for v in report_data["variants"]
+ ],
+ "report": str(resolved_out / report),
+ }
+ print(json.dumps(summary, ensure_ascii=False, indent=2))
+ return 0
+
+
+def add_palette_arguments(p: argparse.ArgumentParser) -> None:
+ p.add_argument("--base", required=True, type=Path, help="base sheet PNG to scan")
+ p.add_argument("--out", type=Path, help="write the palette map JSON here (default: stdout)")
+ p.add_argument("--alpha-threshold", type=int, default=DEFAULT_ALPHA_THRESHOLD)
+ p.add_argument("--max-colors", type=int, help="keep only the top-N colours by frequency")
+
+
+def run_palette(
+ *,
+ base: Path,
+ out: Path | None = None,
+ alpha_threshold: int = DEFAULT_ALPHA_THRESHOLD,
+ max_colors: int | None = None,
+) -> int:
+ palette = extract_palette(base, alpha_threshold=alpha_threshold, max_colors=max_colors)
+ text = json.dumps(palette, ensure_ascii=False, indent=2) + "\n"
+ if out is not None:
+ out.parent.mkdir(parents=True, exist_ok=True)
+ atomic_write_text(out, text)
+ print(json.dumps({"ok": True, "palette": str(out), "color_count": palette["color_count"]}, ensure_ascii=False, indent=2))
+ else:
+ print(text, end="")
+ return 0
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(description="Bake deterministic palette-swap variant sheets.")
+ add_recolor_arguments(parser)
+ args = parser.parse_args(argv)
+ return run(**vars(args))
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/sprite_gen/effects/reroll.py b/sprite_gen/effects/reroll.py
new file mode 100644
index 0000000..34f8917
--- /dev/null
+++ b/sprite_gen/effects/reroll.py
@@ -0,0 +1,137 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Reroll a state's row as a NEW take — candidate pool, never a replacement.
+
+리롤 = 같은 행을 한 번 더 생성해 **테이크로 병기**한다 (maintainer 2026-07-19 "리롤버튼
+눌러서 후보군에 추가"). primary raw 는 건드리지 않고 `raw/<...>.takes/rerollN.png`
++ request `states.<state>.takes` 로 기록되므로, 추출 후 큐레이션 뷰에는 기존 프레임
+뒤에 `rerollN#i` 라벨 후보가 이어 붙는다. 픽/기각은 사람 몫.
+
+생성 refs 는 행 생성 계약(directional-anchor-workflow)을 따른다 — 결정은 `anchor.py`
+하나가 소유한다 (`identity_ref`): 방향 런의 액션 행이면 그 방향 앵커를 큐레이션 진실에서
+매번 다시 구워 붙이고, 앵커 행 자체/단순 런이면 `base-source.*` 를 붙인다. 여기에
+레이아웃 가이드를 더한 두 장이 리롤 refs 다.
+
+AI 개입은 raw 생성 한 곳 — 최종 프레임은 언제나 결정론 추출이 굽는다. 부분 추출은
+없다 (공유 팔레트가 추출 배치 구성에 결합 — interpolate 와 같은 계약).
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import re
+import sys
+from pathlib import Path
+from typing import Any
+
+from sprite_gen.curate.anchor import identity_ref
+from sprite_gen.spec.runio import load_request, write_request
+from sprite_gen.gen import PROVIDERS, generate_image
+from sprite_gen.spec.layout import guide_rel, prompt_rel, take_raw_rel
+
+
+def next_reroll_label(request: dict[str, Any], state: str) -> str:
+ takes = request["states"][state].get("takes") or []
+ used = set()
+ for take in takes:
+ m = re.fullmatch(r"reroll(\d+)", str(take.get("label") or ""))
+ if m:
+ used.add(int(m.group(1)))
+ n = 1
+ while n in used:
+ n += 1
+ return f"reroll{n}"
+
+
+def record_take(run_dir: Path, state: str, label: str, frames: int) -> None:
+ """request 의 takes 선언 갱신 (멱등) — write_take(interpolate)와 같은 기록 계약.
+
+ Isolation: 생성이 수 분 걸리므로 시작 시점에 읽은 request 로 쓰면 그 사이의
+ 다른 변경(다른 행 리롤·fps 수정)을 덮어쓴다 (lost update). publish_guard
+ 배타락 안에서 **fresh 재독 → 갱신 → 원자 쓰기** 로만 기록한다."""
+ from sprite_gen.spec.runio import publish_guard
+
+ with publish_guard(run_dir):
+ # 락 안 fresh 재독도 게이트를 통과한다 — 이관 판정·두 키 hard fail 이 한 곳에만 있어야
+ # 한다. 게이트는 읽기만 하므로 락 안에서도 안전하다.
+ fresh = load_request(run_dir)
+ takes = fresh["states"][state].setdefault("takes", [])
+ entry = next((t for t in takes if t.get("label") == label), None)
+ if entry is None:
+ takes.append({"label": label, "frames": frames})
+ else:
+ entry["frames"] = frames
+ # 쓰기도 게이트 경유 (`write_request`): 테이크 기록은 스키마와 무관한 편집이라
+ # 디스크의 키 형태를 그대로 둔다 (스키마 이관은 `sprite-gen migrate-request` 만).
+ write_request(run_dir, fresh)
+
+
+def reroll_state(run_dir: Path | str, state: str, provider: str = "codex",
+ label: str | None = None) -> Path:
+ """행 리롤 한 번: 테이크 raw 생성 + request takes 기록. 반환 = 테이크 raw 경로."""
+ run_dir = Path(run_dir)
+ # 읽기는 **게이트만** 쓴다 (`load_request`): 여기서 raw 로 읽으면 아직 이관되지 않은
+ # 레거시 런에서 아래 `fit.pixel_unfake` 검사가 항상 False 가 되어, 언페이크가 켜진 런의
+ # 리롤을 "켜져 있지 않다" 며 거부한다 (validator 검증 2026-07-26 R1 재현). 리롤은 뷰가 **별도
+ # 서브프로세스**로 띄우므로 뷰 프로세스의 in-memory 이관도 여기로 넘어오지 않는다.
+ request = load_request(run_dir)
+ if state not in request.get("states", {}):
+ raise SystemExit(f"unknown state: {state}")
+ label = label or next_reroll_label(request, state)
+ if "/" in label or label.startswith("."):
+ raise SystemExit(f"take label must be filesystem-safe: {label!r}")
+ # 테이크는 pixel_unfake 추출 계약 위에서만 병합된다 — 생성비를 쓰기 전에 막는다
+ # (실측 2026-07-19: 비-pp 런에서 생성까지 간 뒤 추출이 "takes require
+ # fit.pixel_unfake" 로 죽었다 — fail-loud 는 맞지만 늦다).
+ if not (request.get("fit") or {}).get("pixel_unfake"):
+ raise SystemExit("reroll: takes require fit.pixel_unfake on this run "
+ "(candidate pool rides the take pipeline)")
+ prompt_path = run_dir / prompt_rel(request, state)
+ if not prompt_path.is_file():
+ raise SystemExit(f"reroll: prompt file missing: {prompt_path}")
+ refs = [identity_ref(run_dir, state, request=request)]
+ guide_path = run_dir / guide_rel(request, state)
+ if guide_path.is_file():
+ refs.append(guide_path)
+ target = run_dir / take_raw_rel(request, state, label)
+ target.parent.mkdir(parents=True, exist_ok=True)
+ generate_image(provider, prompt_path.read_text(encoding="utf-8"), target, refs=refs)
+ frames = int(request["states"][state]["frames"])
+ record_take(run_dir, state, label, frames)
+ print(f"[reroll] take written: {target.relative_to(run_dir)} "
+ f"(state={state}, frames={frames}, provider={provider})")
+ return target
+
+
+def _build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
+ parser.add_argument("--run-dir", required=True)
+ parser.add_argument("--state", required=True)
+ parser.add_argument("--provider", choices=PROVIDERS, default="codex",
+ help="생성 백엔드 (기본 codex)")
+ parser.add_argument("--label", default=None, help="테이크 라벨 (기본 rerollN 자동 증가)")
+ parser.add_argument("--extract", action="store_true",
+ help="기록 후 전체 배치 재추출까지 수행 (부분 추출은 팔레트 배치 결합 때문에 지원하지 않음)")
+ return parser
+
+
+def main(argv: list[str] | None = None) -> int:
+ args = _build_parser().parse_args(argv)
+ reroll_state(args.run_dir, args.state, provider=args.provider, label=args.label)
+ if args.extract:
+ from sprite_gen.frames import extract as extract_module
+ code = extract_module.run(run_dir=Path(args.run_dir))
+ if code != 0:
+ return code
+ print("[reroll] full-batch re-extraction done")
+ else:
+ # 인터프리터는 sys.executable 로 찍는다 — 이 힌트는 붙여넣어 바로 실행되는
+ # 명령이고, 전역 `python3` 는 이 패키지의 의존(NumPy/Pillow)이 없는 다른
+ # 인터프리터일 수 있다 (SKILL.md "실행 인터프리터" 게이트).
+ print("[reroll] next: re-extract the FULL batch so the shared palette stays "
+ f"consistent -> {sys.executable} -m sprite_gen.frames.extract --run-dir {args.run_dir}")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/sprite_gen/frames/__init__.py b/sprite_gen/frames/__init__.py
new file mode 100644
index 0000000..9881313
--- /dev/null
+++ b/sprite_gen/frames/__init__.py
@@ -0,0 +1 @@
+# SPDX-License-Identifier: Apache-2.0
diff --git a/sprite_gen/frames/check_visible_magenta.py b/sprite_gen/frames/check_visible_magenta.py
new file mode 100644
index 0000000..7f014b3
--- /dev/null
+++ b/sprite_gen/frames/check_visible_magenta.py
@@ -0,0 +1,106 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Fail a browser/game screenshot when visible chroma-key magenta remains."""
+
+from __future__ import annotations
+
+import argparse
+from pathlib import Path
+
+from PIL import Image
+
+
+def is_visible_magenta(r: int, g: int, b: int, a: int, args: argparse.Namespace) -> bool:
+ if a < args.min_alpha:
+ return False
+ return (
+ r >= args.min_red
+ and b >= args.min_blue
+ and g <= args.max_green
+ and (r - g) >= args.min_red_delta
+ and (b - g) >= args.min_blue_delta
+ )
+
+
+def _build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(
+ description="Check Playwright/browser screenshots for visible #FF00FF sprite key color."
+ )
+ parser.add_argument("--image", required=True, type=Path)
+ parser.add_argument("--max-pixels", type=int, default=64)
+ parser.add_argument("--max-ratio", type=float, default=0.00005)
+ parser.add_argument("--min-alpha", type=int, default=128)
+ parser.add_argument("--min-red", type=int, default=230)
+ parser.add_argument("--min-blue", type=int, default=230)
+ parser.add_argument("--max-green", type=int, default=80)
+ parser.add_argument("--min-red-delta", type=int, default=150)
+ parser.add_argument("--min-blue-delta", type=int, default=150)
+ return parser
+
+
+def _namespace_from_kwargs(**kwargs: object) -> argparse.Namespace:
+ parser = _build_parser()
+ values: dict[str, object] = {}
+ remaining = dict(kwargs)
+ for action in parser._actions:
+ if action.dest == "help":
+ continue
+ default = [] if action.nargs == "*" else action.default
+ if default is argparse.SUPPRESS:
+ default = None
+ value = remaining.pop(action.dest, default)
+ if getattr(action, "required", False) and value is None:
+ raise TypeError(f"missing required argument: {action.dest}")
+ values[action.dest] = value
+ if remaining:
+ names = ", ".join(sorted(remaining))
+ raise TypeError(f"unexpected keyword argument(s): {names}")
+ return argparse.Namespace(**values)
+def _run(args: argparse.Namespace):
+
+ image = Image.open(args.image).convert("RGBA")
+ width, height = image.size
+ pixels = image.load()
+ count = 0
+ min_x = width
+ min_y = height
+ max_x = -1
+ max_y = -1
+
+ for y in range(height):
+ for x in range(width):
+ r, g, b, a = pixels[x, y]
+ if is_visible_magenta(r, g, b, a, args):
+ count += 1
+ min_x = min(min_x, x)
+ min_y = min(min_y, y)
+ max_x = max(max_x, x)
+ max_y = max(max_y, y)
+
+ total = width * height
+ ratio = count / total if total else 0
+ bbox = "none" if count == 0 else f"{min_x},{min_y},{max_x},{max_y}"
+ failed = count > args.max_pixels or ratio > args.max_ratio
+
+ print(f"image={args.image}")
+ print(f"size={width}x{height}")
+ print(f"visible_magenta_pixels={count}")
+ print(f"visible_magenta_ratio={ratio:.8f}")
+ print(f"visible_magenta_bbox={bbox}")
+ print(f"threshold_pixels={args.max_pixels}")
+ print(f"threshold_ratio={args.max_ratio:.8f}")
+ print("status=fail" if failed else "status=pass")
+ raise SystemExit(1 if failed else 0)
+
+
+
+def run(**kwargs: object):
+ return _run(_namespace_from_kwargs(**kwargs))
+
+def main() -> int:
+ parser = _build_parser()
+ args = parser.parse_args()
+ return _run(args)
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/sprite_gen/frames/cutout.py b/sprite_gen/frames/cutout.py
new file mode 100644
index 0000000..0b50b88
--- /dev/null
+++ b/sprite_gen/frames/cutout.py
@@ -0,0 +1,405 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Background cutout for externally authored (imported) images — the unified
+post-edit entry point.
+
+The generation pipeline already renders onto a solid magenta/green key and keys
+it out (`gen/chroma.py` / `extract.py`), so its own output never needs this.
+`cutout` is the import/post-edit utility: an image that arrived *with* an opaque
+uniform background (a hand-drawn icon, a downloaded sprite, a messenger
+screenshot) is turned into a clean transparent RGBA here.
+
+It routes on the corner background colour:
+
+- **white / ivory / bright achromatic** → position-based matte (this module).
+ A colour-only key would punch holes in the object's own bright highlights, so
+ a corner flood-fill marks the *connected* background by position; the border
+ gets a decontaminated soft alpha (`F = (P - (1-a)*B) / a`) + soft erode.
+- **magenta / green key colour** → the project's verified chroma engine
+ `extract.remove_chroma_background` is reused as-is (no reimplementation, no
+ drift). Key colours are absent from real objects, so that engine's colour-only
+ cut is safe there — the exact case a white matte's position guard is *not*
+ needed. Empirically (2026-07-20) feeding an ivory key to the extract engine
+ holes out bench stone / lamp glass; the two routes are deliberate.
+
+Sibling note: `unmix_key_blend`/`_matte_ycc` in `extract.py` and the matte
+despill here are the same "despill + soft edge" idea in two colour spaces
+(extract = CbCr chroma projection for saturated keys; here = RGB unmix for
+achromatic backgrounds). Keep them coherent when either edge path changes.
+
+No Silent Fallback: a transparent pixel that still carries non-zero RGB raises
+loudly (same contract as `gen/chroma.py`).
+"""
+
+from __future__ import annotations
+
+from collections import deque
+from pathlib import Path
+from typing import Any
+
+from PIL import Image
+
+# Matte defaults converged on a 4-icon reference set (tree/bench/flower/lamp, ivory bg).
+STRENGTH_DEFAULT = 45 # LO: colour distance at/below which a border pixel is fully background
+HI_OFFSET = 60 # HI = STRENGTH + HI_OFFSET: distance at/above which a pixel is fully opaque
+BAND_DEFAULT = 6 # only pixels within this many px of the border get alpha/decontam; deeper interior is preserved verbatim
+ERODE_DEFAULT = 1.0 # soft-erode radius (fractional part shaves the last ring to partial alpha)
+CHROMA_TOLERANCE = 26 # flood-fill background membership: max per-channel diff from the estimated bg colour
+CORNER_MIN_BRIGHT = 225 # a corner pixel must be at least this bright (min channel) to seed the bg colour estimate
+
+# Key colours reused from the generation contract (chroma.py KEYS). The extract
+# engine keys these out; cutout only detects them and routes.
+KEY_TARGETS: dict[str, tuple[int, int, int]] = {
+ "magenta": (255, 0, 255),
+ "green": (0, 255, 0),
+}
+# extract.remove_chroma_background params — the extract CLI defaults (SSoT: extract.py argparse).
+_EXTRACT_KEY_THRESHOLD = 96.0
+_EXTRACT_FRINGE_THRESHOLD = 180.0
+_EXTRACT_FRINGE_DELTA = 18.0
+
+# 3-primary verification backgrounds — white fringe/spill shows loudest on these.
+WHITE_CHECK_COLORS: dict[str, tuple[int, int, int]] = {
+ "cyan": (0, 255, 255),
+ "magenta": (255, 0, 255),
+ "yellow": (255, 255, 0),
+}
+
+
+def estimate_background(image: Image.Image) -> tuple[int, int, int]:
+ """Average of the bright, near-achromatic corner pixels (the uniform bg colour).
+
+ Only corners that are bright (min channel >= CORNER_MIN_BRIGHT) and non-transparent
+ are sampled, so a corner that is already transparent or covered by the object does
+ not poison the estimate. Falls back to ivory when no corner qualifies.
+ """
+ width, height = image.size
+ px = image.load()
+ corners = [(0, 0), (width - 1, 0), (0, height - 1), (width - 1, height - 1)]
+ samples = []
+ for x, y in corners:
+ r, g, b, a = px[x, y]
+ if a > 0 and min(r, g, b) >= CORNER_MIN_BRIGHT:
+ samples.append((r, g, b))
+ if not samples:
+ return (248, 247, 242)
+ n = len(samples)
+ return (
+ sum(s[0] for s in samples) // n,
+ sum(s[1] for s in samples) // n,
+ sum(s[2] for s in samples) // n,
+ )
+
+
+def _corner_average(image: Image.Image) -> tuple[int, int, int]:
+ """Raw average of the non-transparent corner pixels — no brightness filter.
+
+ Used for route detection so a saturated key colour (magenta/green, which the
+ bright-only `estimate_background` skips) is still seen.
+ """
+ width, height = image.size
+ px = image.load()
+ samples = [
+ px[x, y][:3]
+ for x, y in ((0, 0), (width - 1, 0), (0, height - 1), (width - 1, height - 1))
+ if px[x, y][3] > 0
+ ]
+ if not samples:
+ return (248, 247, 242)
+ n = len(samples)
+ return tuple(sum(s[i] for s in samples) // n for i in range(3)) # type: ignore[return-value]
+
+
+def _detect_key_kind(color: tuple[int, int, int]) -> str:
+ """Classify a corner background colour into a route: magenta | green | white.
+
+ Saturated magenta/green keys route to the extract engine; everything else
+ (bright achromatic ivory/white, or any low-saturation background) routes to
+ the position-based matte.
+ """
+ r, g, b = color
+ if r >= 128 and b >= 128 and g <= 100 and (r - g) >= 60 and (b - g) >= 60:
+ return "magenta"
+ if g >= 128 and r <= 100 and b <= 100 and (g - r) >= 60 and (g - b) >= 60:
+ return "green"
+ return "white"
+
+
+def _background_mask(px: Any, width: int, height: int, bg: tuple[int, int, int], tol: int) -> bytearray:
+ """Corner flood-fill: 1 where a pixel is transparent or within `tol` of `bg` AND connected to a corner."""
+ mask = bytearray(width * height)
+ queue: deque[tuple[int, int]] = deque()
+
+ def is_bg(x: int, y: int) -> bool:
+ r, g, b, a = px[x, y]
+ if a == 0:
+ return True
+ return max(abs(r - bg[0]), abs(g - bg[1]), abs(b - bg[2])) <= tol
+
+ for cx, cy in [(0, 0), (width - 1, 0), (0, height - 1), (width - 1, height - 1)]:
+ if is_bg(cx, cy) and not mask[cy * width + cx]:
+ mask[cy * width + cx] = 1
+ queue.append((cx, cy))
+ while queue:
+ x, y = queue.popleft()
+ for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1)):
+ nx, ny = x + dx, y + dy
+ if 0 <= nx < width and 0 <= ny < height and not mask[ny * width + nx] and is_bg(nx, ny):
+ mask[ny * width + nx] = 1
+ queue.append((nx, ny))
+ return mask
+
+
+def _border_distance(mask: bytearray, width: int, height: int, band: int) -> list[int]:
+ """BFS distance (capped at `band`) from any background pixel into the object."""
+ dist = [band + 1] * (width * height)
+ queue: deque[tuple[int, int]] = deque()
+ for i in range(width * height):
+ if mask[i]:
+ dist[i] = 0
+ queue.append((i % width, i // width))
+ while queue:
+ x, y = queue.popleft()
+ d0 = dist[y * width + x]
+ if d0 >= band:
+ continue
+ for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1)):
+ nx, ny = x + dx, y + dy
+ if 0 <= nx < width and 0 <= ny < height and dist[ny * width + nx] > d0 + 1:
+ dist[ny * width + nx] = d0 + 1
+ queue.append((nx, ny))
+ return dist
+
+
+def _soft_erode(image: Image.Image, amount: float) -> None:
+ """Shave `amount` px off the alpha edge in place. Fractional part = last ring to partial alpha."""
+ if amount <= 0:
+ return
+ width, height = image.size
+ px = image.load()
+ full = int(amount)
+ frac = amount - full
+
+ def edge_pixels() -> list[tuple[int, int]]:
+ out = []
+ for y in range(height):
+ for x in range(width):
+ if not px[x, y][3]:
+ continue
+ if (
+ (x > 0 and px[x - 1, y][3] == 0)
+ or (x < width - 1 and px[x + 1, y][3] == 0)
+ or (y > 0 and px[x, y - 1][3] == 0)
+ or (y < height - 1 and px[x, y + 1][3] == 0)
+ ):
+ out.append((x, y))
+ return out
+
+ for _ in range(full):
+ for x, y in edge_pixels():
+ px[x, y] = (0, 0, 0, 0)
+ if frac > 0:
+ for x, y in edge_pixels():
+ r, g, b, a = px[x, y]
+ px[x, y] = (r, g, b, round(a * (1 - frac)))
+
+
+def _clamp(value: int) -> int:
+ return 0 if value < 0 else 255 if value > 255 else value
+
+
+def _matte_route(
+ image: Image.Image,
+ input_path: Path,
+ strength: int,
+ band: int,
+ erode: float,
+ tolerance: int,
+) -> tuple[Image.Image, dict[str, Any]]:
+ """White/achromatic background → position flood-fill + decontaminated soft alpha."""
+ width, height = image.size
+ src = image.load()
+ bg = estimate_background(image)
+ mask = _background_mask(src, width, height, bg, tolerance)
+ if not any(mask):
+ raise SystemExit(
+ f"cutout: no background located from corners in {input_path} "
+ f"(estimated bg {bg}); is the border actually a uniform colour?"
+ )
+
+ dist = _border_distance(mask, width, height, band)
+ hi = strength + HI_OFFSET
+ span = hi - strength
+
+ result = Image.new("RGBA", (width, height))
+ dst = result.load()
+ keyed = decontaminated = 0
+ for y in range(height):
+ for x in range(width):
+ i = y * width + x
+ r, g, b, a = src[x, y]
+ if mask[i]:
+ dst[x, y] = (0, 0, 0, 0)
+ keyed += 1
+ continue
+ if dist[i] <= band:
+ d = max(abs(r - bg[0]), abs(g - bg[1]), abs(b - bg[2]))
+ alpha_f = 0.0 if d <= strength else (1.0 if d >= hi else (d - strength) / span)
+ if alpha_f <= 0:
+ dst[x, y] = (0, 0, 0, 0)
+ keyed += 1
+ continue
+ if alpha_f < 1.0:
+ r = _clamp(round((r - (1 - alpha_f) * bg[0]) / alpha_f))
+ g = _clamp(round((g - (1 - alpha_f) * bg[1]) / alpha_f))
+ b = _clamp(round((b - (1 - alpha_f) * bg[2]) / alpha_f))
+ decontaminated += 1
+ dst[x, y] = (r, g, b, round(alpha_f * 255))
+ else:
+ dst[x, y] = (r, g, b, 255)
+
+ _soft_erode(result, erode)
+ return result, {
+ "route": "matte",
+ "background": list(bg),
+ "strength": strength,
+ "band": band,
+ "erode": erode,
+ "keyed_pixels": keyed,
+ "decontaminated_pixels": decontaminated,
+ }
+
+
+def _extract_route(image: Image.Image, kind: str) -> tuple[Image.Image, dict[str, Any]]:
+ """Magenta/green key background → reuse the verified `extract` chroma engine (no drift)."""
+ from sprite_gen.frames.extract import remove_chroma_background
+
+ target = KEY_TARGETS[kind]
+ result = remove_chroma_background(
+ image, target, _EXTRACT_KEY_THRESHOLD, _EXTRACT_FRINGE_THRESHOLD, _EXTRACT_FRINGE_DELTA
+ )
+ return result.convert("RGBA"), {"route": f"extract:{kind}", "chroma_key": list(target)}
+
+
+def cutout(
+ input_path: Path,
+ out_path: Path,
+ *,
+ key: str = "auto",
+ strength: int = STRENGTH_DEFAULT,
+ band: int = BAND_DEFAULT,
+ erode: float = ERODE_DEFAULT,
+ tolerance: int = CHROMA_TOLERANCE,
+ white_check_dir: Path | None = None,
+) -> dict[str, Any]:
+ """Cut a uniform-background imported image to a clean transparent RGBA PNG.
+
+ `key`: "auto" (detect from corners) | "white" (matte) | "magenta" | "green"
+ (reuse the extract chroma engine). Returns a stats dict. Raises SystemExit if
+ the key is unknown, the background cannot be located, or any transparent pixel
+ keeps non-zero RGB (No Silent Fallback).
+ """
+ if key not in ("auto", "white", "magenta", "green"):
+ raise SystemExit(f"cutout: unknown key {key!r}; expected one of auto|white|magenta|green")
+
+ image = Image.open(input_path).convert("RGBA")
+ width, height = image.size
+
+ route = _detect_key_kind(_corner_average(image)) if key == "auto" else key
+ if route in ("magenta", "green"):
+ result, route_stats = _extract_route(image, route)
+ else:
+ result, route_stats = _matte_route(image, input_path, strength, band, erode, tolerance)
+
+ out_path.parent.mkdir(parents=True, exist_ok=True)
+ result.save(out_path)
+
+ # No Silent Fallback verification.
+ check = result.load()
+ total = width * height
+ alpha_zero = stale_rgb = 0
+ for y in range(height):
+ for x in range(width):
+ r, g, b, a = check[x, y]
+ if a == 0:
+ alpha_zero += 1
+ if r or g or b:
+ stale_rgb += 1
+ if stale_rgb:
+ raise SystemExit(
+ f"cutout: transparent pixels still contain non-zero RGB ({stale_rgb} px) in {out_path}"
+ )
+
+ stats: dict[str, Any] = {
+ "out": str(out_path),
+ "mode": "RGBA",
+ "size": f"{width}x{height}",
+ "key": key,
+ **route_stats,
+ "alpha_zero_pct": round(alpha_zero / total * 100, 2) if total else 0.0,
+ }
+
+ if white_check_dir is not None:
+ white_check_dir.mkdir(parents=True, exist_ok=True)
+ stem = out_path.stem
+ checks = []
+ for name, color in WHITE_CHECK_COLORS.items():
+ plate = Image.new("RGBA", (width, height), color + (255,))
+ plate.alpha_composite(result)
+ check_path = white_check_dir / f"{stem}_{name}.png"
+ plate.convert("RGB").save(check_path)
+ checks.append(str(check_path))
+ stats["white_check"] = checks
+
+ return stats
+
+
+def add_arguments(p: Any) -> None:
+ p.add_argument("input", type=Path, help="imported image with a uniform (white/ivory or magenta/green key) background")
+ p.add_argument("--out", type=Path, help="output PNG (default: <input>_cutout.png)")
+ p.add_argument(
+ "--key",
+ choices=["auto", "white", "magenta", "green"],
+ default="auto",
+ help="background type; auto detects from corners (white→matte, magenta/green→extract engine)",
+ )
+ p.add_argument(
+ "--strength",
+ type=int,
+ default=STRENGTH_DEFAULT,
+ help=f"matte LO: bg colour-distance cutoff; higher removes brighter bevel (default {STRENGTH_DEFAULT})",
+ )
+ p.add_argument("--band", type=int, default=BAND_DEFAULT, help=f"matte edge processing depth in px (default {BAND_DEFAULT})")
+ p.add_argument("--erode", type=float, default=ERODE_DEFAULT, help=f"matte soft erode radius in px (default {ERODE_DEFAULT})")
+ p.add_argument(
+ "--tolerance",
+ type=int,
+ default=CHROMA_TOLERANCE,
+ help=f"matte flood-fill bg membership tolerance (default {CHROMA_TOLERANCE})",
+ )
+ p.add_argument(
+ "--white-check",
+ dest="white_check",
+ action="store_true",
+ help="also write cyan/magenta/yellow verification composites next to the output",
+ )
+
+
+def run(**kwargs: object) -> int:
+ input_path = Path(kwargs["input"]) # type: ignore[arg-type]
+ out = kwargs.get("out")
+ out_path = Path(out) if out else input_path.with_name(f"{input_path.stem}_cutout.png") # type: ignore[arg-type]
+ white_check = bool(kwargs.get("white_check"))
+ stats = cutout(
+ input_path,
+ out_path,
+ key=str(kwargs.get("key", "auto")), # type: ignore[arg-type]
+ strength=int(kwargs.get("strength", STRENGTH_DEFAULT)), # type: ignore[arg-type]
+ band=int(kwargs.get("band", BAND_DEFAULT)), # type: ignore[arg-type]
+ erode=float(kwargs.get("erode", ERODE_DEFAULT)), # type: ignore[arg-type]
+ tolerance=int(kwargs.get("tolerance", CHROMA_TOLERANCE)), # type: ignore[arg-type]
+ white_check_dir=out_path.parent if white_check else None,
+ )
+ import json
+
+ print(json.dumps(stats, ensure_ascii=False, indent=2))
+ return 0
diff --git a/sprite_gen/frames/extract.py b/sprite_gen/frames/extract.py
new file mode 100644
index 0000000..9f5f103
--- /dev/null
+++ b/sprite_gen/frames/extract.py
@@ -0,0 +1,3331 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Extract component-row sprite strips into clean RGBA frames."""
+
+from __future__ import annotations
+
+import argparse
+import hashlib
+import json
+import math
+import os
+import shutil
+import subprocess
+import sys
+from bisect import bisect_left
+from pathlib import Path
+from statistics import median
+from typing import Any
+
+from PIL import Image, ImageChops
+
+from sprite_gen._deps import np
+from sprite_gen.curate.curation import effective_logical_height, pixel_snap_scale
+from sprite_gen.spec.layout import frames_dir_rel, raw_rel, take_raw_rel
+from sprite_gen.spec.runio import (REQUEST_FILENAME, acquire_run_dir_lock, atomic_save_image,
+ atomic_write_text, load_request, publish_guard, relative_posix,
+ release_run_dir_lock)
+from sprite_gen.frames.segment import separate_fused_poses
+from sprite_gen.spec.subject import SUBJECT_DEFAULT, default_min_used_pixels, sparse_frame_error, subject_kind
+
+
+def color_distance(left: tuple[int, int, int], right: tuple[int, int, int]) -> float:
+ return math.sqrt(sum((left[index] - right[index]) ** 2 for index in range(3)))
+
+
+def alpha_nonzero_count(image: Image.Image) -> int:
+ return sum(image.getchannel("A").histogram()[1:])
+
+
+def edge_alpha_count(image: Image.Image, margin: int) -> int:
+ alpha = image.getchannel("A")
+ width, height = image.size
+ total = 0
+ for box in (
+ (0, 0, width, margin),
+ (0, height - margin, width, height),
+ (0, 0, margin, height),
+ (width - margin, 0, width, height),
+ ):
+ total += sum(alpha.crop(box).histogram()[1:])
+ return total
+
+
+def _key_channel_split(chroma_key: tuple[int, int, int]) -> tuple[list[int], list[int]]:
+ """Which channels the key saturates, and which it leaves dark.
+
+ Depends only on the key, so the whole-image path resolves it once instead of
+ per pixel. Degenerate keys — no saturated channel, or no dark one — have no
+ tint axis at all and come back as two empty lists; that emptiness is the one
+ switch both callers read, and it turns off the unmix and spill passes.
+ """
+ keyed_channels = [index for index, value in enumerate(chroma_key) if value >= 192]
+ unkeyed_channels = [index for index, value in enumerate(chroma_key) if value < 64]
+ if not keyed_channels or not unkeyed_channels:
+ return [], []
+ return keyed_channels, unkeyed_channels
+
+
+def key_tint_score(color: tuple[int, int, int], chroma_key: tuple[int, int, int]) -> float:
+ keyed_channels, unkeyed_channels = _key_channel_split(chroma_key)
+ if not keyed_channels:
+ return 0.0
+ keyed_average = sum(color[index] for index in keyed_channels) / len(keyed_channels)
+ unkeyed_average = sum(color[index] for index in unkeyed_channels) / len(unkeyed_channels)
+ return keyed_average - unkeyed_average
+
+
+
+def despill_color(
+ color: tuple[int, int, int],
+ chroma_key: tuple[int, int, int],
+ key_tint: float,
+ tint: float,
+) -> tuple[float, tuple[int, int, int]]:
+ """Estimate the key fraction of a blend pixel and remove it from the RGB.
+
+ Blend model: observed = (1-k)*subject + k*key. key_tint_score is linear in
+ the channels and scores the key itself at `key_tint`, so k = tint/key_tint
+ recovers a subject estimate whose own tint score is ~0. Returns the
+ subject coverage (1-k) and the despilled color.
+ """
+ k = min(tint / key_tint, 1.0)
+ coverage = 1.0 - k
+ if coverage <= 0:
+ return 0.0, (0, 0, 0)
+ red, green, blue = (
+ min(255, max(0, round((color[index] - k * chroma_key[index]) / coverage)))
+ for index in range(3)
+ )
+ return coverage, (red, green, blue)
+
+
+def unmix_key_blend(
+ color: tuple[int, int, int],
+ alpha: int,
+ chroma_key: tuple[int, int, int],
+ key_tint: float,
+ tint: float,
+) -> tuple[int, int, int, int]:
+ """Separate a key/subject blend pixel into despilled RGB + partial alpha."""
+ coverage, despilled = despill_color(color, chroma_key, key_tint, tint)
+ out_alpha = round(alpha * coverage)
+ if out_alpha <= 0:
+ return (0, 0, 0, 0)
+ return (*despilled, out_alpha)
+
+
+# --- whole-image forms of the two primitives above ---------------------------
+# remove_chroma_background asks `color_distance` and `key_tint_score` the same
+# question of every pixel, which at 1.5 Mpx a row is where the extraction time
+# went. These compute the identical float64 values one array at a time.
+#
+# "Identical" is the contract, not an aspiration: both quantities start as exact
+# integer arithmetic on uint8 channels, and the one float operation in each
+# (`math.sqrt`, `int / int`) is IEEE-754 correctly rounded, so the array form
+# reproduces the scalar form bit for bit. tests/test_chroma_rcb_byte_identity.py
+# holds the scalar side against a frozen pre-vectorization copy.
+
+
+def _key_distance_field(rgb: np.ndarray, chroma_key: tuple[int, int, int]) -> np.ndarray:
+ """`color_distance` for an (H, W, 3) integer array of colors.
+
+ The squared differences accumulate in int64 on purpose. 255**2 * 3 = 195_075
+ overflows uint16 as well as uint8, and a wrapped square does not raise — it
+ returns a plausible distance for the wrong pixel.
+ """
+ diff = rgb - np.asarray(chroma_key, dtype=np.int32)
+ return np.sqrt((diff * diff).sum(axis=-1, dtype=np.int64).astype(np.float64))
+
+
+def _key_tint_field(rgb: np.ndarray, keyed_channels: list[int],
+ unkeyed_channels: list[int]) -> np.ndarray:
+ """`key_tint_score` for an (H, W, 3) integer array of colors.
+
+ Takes the channel split rather than the key, so the degenerate-key decision
+ stays where `_key_channel_split` made it — one answer, read the same way here
+ as in the scalar primitive.
+ """
+ if not keyed_channels:
+ return np.zeros(rgb.shape[:2], dtype=np.float64)
+ keyed_sum = rgb[..., keyed_channels].sum(axis=-1, dtype=np.int64)
+ unkeyed_sum = rgb[..., unkeyed_channels].sum(axis=-1, dtype=np.int64)
+ return keyed_sum / len(keyed_channels) - unkeyed_sum / len(unkeyed_channels)
+
+
+def _grow_chebyshev(mask: np.ndarray) -> np.ndarray:
+ """One step of 8-connected growth: the 3x3 neighborhood of every set pixel.
+
+ Shifts are explicit slices, not `np.roll`, because roll wraps the far edge
+ into the near one and would hand a bottom-row pixel the depth of the top
+ row. The two axes are applied in sequence — a 3x3 dilation is separable, and
+ Chebyshev distance is exactly what repeating this step counts.
+ """
+ grown = mask.copy()
+ grown[:, 1:] |= mask[:, :-1]
+ grown[:, :-1] |= mask[:, 1:]
+ spread = grown.copy()
+ spread[1:, :] |= grown[:-1, :]
+ spread[:-1, :] |= grown[1:, :]
+ return spread
+
+
+# remove_chroma_background pixel classes, decided once on the source colors.
+_KEYED = 0 # erased: transparent input or hard key cut
+_SUBJECT = 1 # not key-tinted — never touched
+_BLEND_IN_BAND = 2 # key-tinted, within fringe_threshold of the key
+_BLEND_OUT_OF_BAND = 3 # key-tinted, farther than fringe_threshold
+_IN_BAND_UNMIX_KEY_DEPTH = 2
+
+# A trapped-spill cluster must contain at least one strongly key-tinted pixel
+# to be treated. This is the plan's visible-residue detector (every keyed
+# channel clears every unkeyed channel by >40): warm subject colors (skin)
+# score a marginal tint just above fringe_delta and must not be "corrected".
+_SPILL_MIN_TINT = 40.0
+
+
+def remove_chroma_background(
+ image: Image.Image,
+ chroma_key: tuple[int, int, int],
+ threshold: float,
+ fringe_threshold: float,
+ fringe_delta: float,
+ *,
+ unmix_reach: int = 4,
+ spill_max_fraction: float = 0.005,
+) -> Image.Image:
+ rgba = image.convert("RGBA")
+ width, height = rgba.size
+ data = np.array(rgba, dtype=np.uint8) # (H, W, 4); written back at the end
+ source_rgb = data[..., :3].astype(np.int32)
+ keyed_channels, unkeyed_channels = _key_channel_split(chroma_key)
+ unseen = 255
+
+ # Classification, decided on the source colors before anything is erased.
+ # np.select takes the first condition that holds, so the condlist order below
+ # *is* the if/elif order it replaces — swapping the subject and in-band rows
+ # changes the output wherever both hold at once (a wide --fringe-key-threshold
+ # makes that reachable, and the gate has a case for it).
+ key_distance = _key_distance_field(source_rgb, chroma_key)
+ source_tint = _key_tint_field(source_rgb, keyed_channels, unkeyed_channels)
+ keyed_mask = (data[..., 3] == 0) | (key_distance <= threshold)
+ classes = np.select(
+ [keyed_mask, source_tint < fringe_delta, key_distance <= fringe_threshold],
+ [_KEYED, _SUBJECT, _BLEND_IN_BAND],
+ default=_BLEND_OUT_OF_BAND,
+ ).astype(np.uint8)
+ data[keyed_mask] = 0
+
+ depths = np.full((height, width), unseen, dtype=np.uint8) # chebyshev distance to keyed region
+ depths[keyed_mask] = 0
+
+ key_tint = key_tint_score(chroma_key, chroma_key)
+ max_reach = min(unseen - 1, unmix_reach if key_tint > 0 else 0)
+
+ # Geometric distance to the nearest keyed-out pixel — outer background
+ # *and* interior holes (hair gaps) alike. This walk is not blocked by
+ # subject pixels, so an isolated key blend locked inside subject material
+ # still gets a depth. Growing the keyed set one ring at a time numbers the
+ # rings in the order a breadth-first walk would reach them.
+ frontier = keyed_mask
+ reached = keyed_mask
+ depth = 0
+ while frontier.any() and depth < max_reach:
+ depth += 1
+ frontier = _grow_chebyshev(frontier) & ~reached
+ depths[frontier] = depth
+ reached = reached | frontier
+
+ # Soft-alpha unmix — binary erase cannot represent antialiased coverage.
+ # Any key-tinted pixel within unmix_reach of the keyed region is separated
+ # into despilled RGB + partial alpha instead:
+ # - out-of-band blends always (they are too subject-heavy to erase);
+ # - in-band blends only within the AA band nearest the key. Deeper
+ # key-tinted material stays byte-identical (v1.10.1 guardrail).
+ # Only the selection is vectorized. The pixels that survive it are the AA
+ # fringe — a thin minority — so the blend itself stays on the scalar
+ # primitives that despill_color and unmix_key_blend already own.
+ if key_tint > 0 and unmix_reach > 0:
+ in_reach = (depths > 0) & (depths <= min(unmix_reach, unseen))
+ unmixable = in_reach & (
+ ((classes == _BLEND_IN_BAND) & (depths <= _IN_BAND_UNMIX_KEY_DEPTH))
+ | (classes == _BLEND_OUT_OF_BAND)
+ )
+ rows, cols = np.nonzero(unmixable)
+ for y, x in zip(rows.tolist(), cols.tolist()):
+ red, green, blue, alpha = (int(value) for value in data[y, x])
+ color = (red, green, blue)
+ out_red, out_green, out_blue, out_alpha = unmix_key_blend(
+ color, alpha, chroma_key, key_tint, key_tint_score(color, chroma_key)
+ )
+ # The scalar path wrote this through `pixels[x, y] = (...)`, and PIL
+ # clamped every channel to 0..255 on the way in. A uint8 array does
+ # not — it raises — so the clamp has to be restored here or the
+ # rewrite changes behavior instead of just its speed.
+ #
+ # Exactly one channel needs it. The three color channels leave
+ # `despill_color` already squeezed by its own `min(255, max(0, …))`,
+ # and re-clamping them here would put that bound in two places; the
+ # alpha is the one value nothing bounds, because `coverage` exceeds
+ # 1 whenever `tint` is negative (reachable with `--fringe-delta < 0`)
+ # and `round(alpha * coverage)` then lands above `alpha`. It cannot
+ # go the other way: `unmix_key_blend` returns a fully transparent
+ # pixel for `out_alpha <= 0`, so the only unbounded direction is up.
+ # Both premises are asserted in tests/test_chroma_rcb_byte_identity.py.
+ data[y, x] = (out_red, out_green, out_blue, min(255, out_alpha))
+
+ # Trapped-spill despill — generators paint key-colored spill *inside* the
+ # subject (a green streak buried in crimson hair, key reflections between
+ # strands) too far from any keyed pixel for depth-based treatment to
+ # reach. Among the still-tinted pixels left after the passes above, a
+ # small connected cluster is spill; a large one is intentional key-tinted
+ # material (the hot-pink seed packet) and stays untouched. Spill keeps its
+ # alpha — it sits inside opaque subject, so this is color correction, not
+ # coverage: partial alpha here would punch pinholes through the sprite.
+ if key_tint > 0 and keyed_mask.any() and spill_max_fraction > 0:
+ subject_count = int(np.count_nonzero(~keyed_mask))
+ spill_limit = max(32, round(subject_count * spill_max_fraction))
+ # Re-scored on the *current* colors: the unmix pass above rewrote part of
+ # the image, and a pixel it despilled is no longer a spill candidate.
+ current_tint = _key_tint_field(data[..., :3].astype(np.int32),
+ keyed_channels, unkeyed_channels)
+ candidates = np.flatnonzero(
+ ((data[..., 3] != 0) & (current_tint >= fringe_delta)).reshape(-1)
+ )
+ tints_left: dict[int, float] = dict(
+ zip(candidates.tolist(), current_tint.reshape(-1)[candidates].tolist())
+ )
+ visited: set[int] = set()
+ for start in tints_left:
+ if start in visited:
+ continue
+ stack = [start]
+ visited.add(start)
+ cluster = []
+ while stack:
+ index = stack.pop()
+ cluster.append(index)
+ x = index % width
+ y = index // width
+ for dy in (-1, 0, 1):
+ for dx in (-1, 0, 1):
+ if 0 <= x + dx < width and 0 <= y + dy < height:
+ neighbor = (y + dy) * width + (x + dx)
+ if neighbor in tints_left and neighbor not in visited:
+ visited.add(neighbor)
+ stack.append(neighbor)
+ if len(cluster) > spill_limit:
+ continue
+ if max(tints_left[index] for index in cluster) <= _SPILL_MIN_TINT:
+ continue
+ for index in cluster:
+ x = index % width
+ y = index // width
+ red, green, blue, alpha = (int(value) for value in data[y, x])
+ color = (red, green, blue)
+ coverage, despilled = despill_color(
+ color, chroma_key, key_tint, key_tint_score(color, chroma_key)
+ )
+ if coverage > 0:
+ data[y, x] = (*despilled, alpha)
+ # Back into the converted copy rather than a fresh Image.fromarray, so the
+ # returned image keeps the mode, size and `info` (icc profile, dpi) that
+ # `convert` carried over from the caller's image.
+ rgba.frombytes(data.tobytes())
+ return rgba
+
+
+# --- YCbCr chrominance matting (opt-in) --------------------------------------
+# Port of the chrominance-plane matting from perfectpixel-studio
+# (https://github.com/gykim80/perfectpixel-studio, internal/sprite/chroma.go),
+# Copyright Andrew Kim (gykim80), MIT License. See NOTICE.
+#
+# The default path above classifies pixels by RGB distance to the key, so
+# background shading and JPEG 4:2:0 chroma subsampling can push background
+# pixels past the erase radius and leave fringe. This path drops luma entirely
+# and separates on the CbCr plane: shading moves Y, not CbCr, so the key stays
+# one tight chroma cluster. Selected with request `chroma.mode: "ycbcr"` or
+# `--chroma-mode ycbcr`; the default "rgb" path stays byte-identical.
+
+_YCC_CHROMA_IN = 24.0 # CbCr distance at/below → fully transparent (key)
+_YCC_CHROMA_OUT = 72.0 # CbCr distance at/above → fully opaque (subject)
+_YCC_DESPILL_BAND = 100.0 # despill pixels whose CbCr distance is inside this
+_YCC_DESPILL_SCALE = 0.92 # despill strength (key-direction chroma suppression)
+_YCC_FLOOD_TOL = 88.0 # border flood fill background tolerance (CbCr, lenient)
+_YCC_ALPHA_EMPTY = 10 # alpha at/below counts as an empty pixel
+_YCC_KEY_RESIDUE_DIST = 55.0 # residue metric radius around the declared key
+_YCC_KEY_BIAS_FRACTION = 0.12 # declared-key border share that overrides the mode
+_YCC_REMATTE_OPAQUE_FRAC = 0.60 # opaque-ratio spike → key likely mis-detected
+_YCC_REMATTE_RESIDUE_FRAC = 0.025 # declared-key residue spike → matting incomplete
+
+
+def rgb_to_ycc(red: int, green: int, blue: int) -> tuple[float, float, float]:
+ """BT.601 YCbCr, 8-bit range, chroma centered on 128."""
+ luma = 0.299 * red + 0.587 * green + 0.114 * blue
+ return luma, (blue - luma) * 0.564 + 128.0, (red - luma) * 0.713 + 128.0
+
+
+def _u8(value: float) -> int:
+ if value <= 0:
+ return 0
+ if value >= 255:
+ return 255
+ return int(value + 0.5)
+
+
+def ycc_to_rgb(luma: float, cb: float, cr: float) -> tuple[int, int, int]:
+ return (
+ _u8(luma + 1.402 * (cr - 128.0)),
+ _u8(luma - 0.344136 * (cb - 128.0) - 0.714136 * (cr - 128.0)),
+ _u8(luma + 1.772 * (cb - 128.0)),
+ )
+
+
+def smoothstep(edge0: float, edge1: float, x: float) -> float:
+ """Hermite 0→1 transition (soft matte edge feathering)."""
+ if edge1 <= edge0:
+ return 0.0
+ t = (x - edge0) / (edge1 - edge0)
+ t = 0.0 if t < 0.0 else 1.0 if t > 1.0 else t
+ return t * t * (3.0 - 2.0 * t)
+
+
+def detect_background_key_ycc(
+ image: Image.Image, declared_key: tuple[int, int, int]
+) -> tuple[int, int, int]:
+ """Estimate the background key from corner patches + thin borders.
+
+ Mode of a quantized CbCr histogram — never a mean: a mean drifts on
+ gradient/compression noise, the mode locks onto the dominant chroma
+ cluster. Wide poses (walk cycles) touch the borders and can crowd the
+ histogram with subject colors, so when a sufficient share of the samples
+ sits in the declared key's chroma family, that cluster wins outright
+ (the original biases toward its always-magenta key the same way).
+ """
+ rgba = image if image.mode == "RGBA" else image.convert("RGBA")
+ width, height = rgba.size
+ if width == 0 or height == 0:
+ return declared_key
+ pixels = rgba.load()
+ _, declared_cb, declared_cr = rgb_to_ycc(*declared_key)
+ bins: dict[int, list[int]] = {}
+ total = 0
+ key_family = [0, 0, 0, 0] # count, sum r, sum g, sum b
+
+ def visit(x: int, y: int) -> None:
+ nonlocal total
+ red, green, blue = pixels[x, y][:3]
+ total += 1
+ _, cb, cr = rgb_to_ycc(red, green, blue)
+ if math.hypot(cb - declared_cb, cr - declared_cr) < _YCC_KEY_RESIDUE_DIST:
+ key_family[0] += 1
+ key_family[1] += red
+ key_family[2] += green
+ key_family[3] += blue
+ slot = (int(cb) >> 3 << 6) | (int(cr) >> 3)
+ acc = bins.get(slot)
+ if acc is None:
+ acc = [0, 0, 0, 0]
+ bins[slot] = acc
+ acc[0] += 1
+ acc[1] += red
+ acc[2] += green
+ acc[3] += blue
+
+ corner_w, corner_h = width // 5, height // 5
+ if corner_w < 2:
+ corner_w = width
+ if corner_h < 2:
+ corner_h = height
+ for x0, y0, x1, y1 in (
+ (0, 0, corner_w, corner_h),
+ (width - corner_w, 0, width, corner_h),
+ (0, height - corner_h, corner_w, height),
+ (width - corner_w, height - corner_h, width, height),
+ ):
+ for y in range(y0, y1):
+ for x in range(x0, x1):
+ visit(x, y)
+ for x in range(width):
+ visit(x, 0)
+ visit(x, height - 1)
+ for y in range(height):
+ visit(0, y)
+ visit(width - 1, y)
+
+ if total > 0 and key_family[0] * 100 >= total * int(_YCC_KEY_BIAS_FRACTION * 100):
+ count = key_family[0]
+ return (key_family[1] // count, key_family[2] // count, key_family[3] // count)
+ best = max(bins.values(), key=lambda acc: acc[0], default=None)
+ if best is None or best[0] == 0:
+ return declared_key
+ return (best[1] // best[0], best[2] // best[0], best[3] // best[0])
+
+
+def _flood_clear_background_ycc(out: Image.Image, source: Image.Image, key_cb: float, key_cr: float) -> None:
+ """4-connected flood fill from the borders clearing key-chroma pixels.
+
+ Connectivity is what preserves the subject: an interior pixel whose chroma
+ happens to sit near the key (isolated highlight, gem) never connects to
+ the border and survives; a gradient/noisy background the soft matte could
+ not fully erase is border-connected and gets cleared.
+ """
+ width, height = source.size
+ if width < 3 or height < 3:
+ return
+ src_pixels = source.load()
+ visited = bytearray(width * height)
+ stack: list[int] = []
+ # floodable(rgb) 는 픽셀값의 순수 함수 (키·톨은 고정) — 색값으로 메모이즈하면
+ # 지배적인 단색 배경의 float 판정(rgb→ycc, hypot)을 색당 한 번만 돈다. 판정
+ # 결과가 동일하므로 방문 집합·클리어 결과가 **바이트 동일**하다.
+ flood_cache: dict[tuple[int, int, int], bool] = {}
+
+ def push(x: int, y: int) -> None:
+ position = y * width + x
+ if visited[position]:
+ return
+ rgb = src_pixels[x, y][:3]
+ ok = flood_cache.get(rgb)
+ if ok is None:
+ _, cb, cr = rgb_to_ycc(rgb[0], rgb[1], rgb[2])
+ ok = math.hypot(cb - key_cb, cr - key_cr) <= _YCC_FLOOD_TOL
+ flood_cache[rgb] = ok
+ if ok:
+ visited[position] = 1
+ stack.append(position)
+
+ for x in range(width):
+ push(x, 0)
+ push(x, height - 1)
+ for y in range(height):
+ push(0, y)
+ push(width - 1, y)
+ # 클리어 대상 = 방문 집합과 정확히 동일 (모든 방문 픽셀이 정확히 한 번 pop 되어
+ # 알파 0 이 된다). 그래서 루프에서 픽셀별로 지우지 않고 방문 집합만 확정한 뒤
+ # 마지막에 PIL 마스크로 한 번에 지운다 — RGB 불변, ~90만 PixelAccess 왕복 제거.
+ while stack:
+ position = stack.pop()
+ x, y = position % width, position // width
+ if x > 0:
+ push(x - 1, y)
+ if x < width - 1:
+ push(x + 1, y)
+ if y > 0:
+ push(x, y - 1)
+ if y < height - 1:
+ push(x, y + 1)
+ # 방문 집합을 마스크로 알파만 0 으로 (RGB 불변). 원본의 픽셀별 클리어와 동일 결과.
+ # visited 는 0/1 → 하드 마스크로 쓰려면 0/255 로 (paste 마스크는 알파 블렌드).
+ clear_mask = Image.frombuffer("L", (width, height), bytes(visited), "raw", "L", 0, 1)
+ clear_mask = clear_mask.point(lambda v: 255 if v else 0)
+ alpha = out.getchannel("A")
+ alpha.paste(0, mask=clear_mask)
+ out.putalpha(alpha)
+
+
+def _matte_ycc(source: Image.Image, key: tuple[int, int, int]) -> tuple[Image.Image, float]:
+ """Soft-matte `source` against `key` on the CbCr plane.
+
+ Returns the matted RGBA image and its opaque-pixel fraction (the
+ self-diagnostic input: a mis-detected key erases the subject instead of
+ the background and the fraction spikes).
+ """
+ width, height = source.size
+ out = Image.new("RGBA", source.size, (0, 0, 0, 0))
+ _, key_cb, key_cr = rgb_to_ycc(*key)
+ key_vb, key_vr = key_cb - 128.0, key_cr - 128.0
+ key_len = math.hypot(key_vb, key_vr)
+ # 핫스팟 (상태당 추출의 ~1/3, 1280×720 전 픽셀). 매트 출력은 픽셀값 (r,g,b) 의
+ # 순수 함수(키는 고정) — 크로마 배경 스프라이트는 고유색이 적어 색값으로
+ # 메모이즈하면 같은 float 연산을 색당 한 번만 돈다. 산술은 **바이트 동일**.
+ # 캐시값: (despill 후 r, g, b, coverage). coverage<=0 이면 원본과 같이 건너뛴다.
+ cache: dict[tuple[int, int, int], tuple[int, int, int, float]] = {}
+ out_data = [(0, 0, 0, 0)] * (width * height)
+ src = list(source.getdata())
+ for i, px in enumerate(src):
+ alpha = px[3]
+ if alpha == 0:
+ continue
+ rgb = (px[0], px[1], px[2])
+ hit = cache.get(rgb)
+ if hit is None:
+ red, green, blue = rgb
+ luma, cb, cr = rgb_to_ycc(red, green, blue)
+ dist = math.hypot(cb - key_cb, cr - key_cr)
+ coverage = smoothstep(_YCC_CHROMA_IN, _YCC_CHROMA_OUT, dist)
+ if coverage <= 0:
+ hit = (0, 0, 0, coverage)
+ else:
+ if key_len > 1 and dist < _YCC_DESPILL_BAND:
+ # Despill: subtract only the key-direction chroma component —
+ # colors orthogonal to the key keep their saturation.
+ pixel_vb, pixel_vr = cb - 128.0, cr - 128.0
+ proj = (pixel_vb * key_vb + pixel_vr * key_vr) / key_len
+ if proj > 0:
+ weight = smoothstep(0.0, 1.0, (_YCC_DESPILL_BAND - dist) / _YCC_DESPILL_BAND) * _YCC_DESPILL_SCALE
+ cb = 128.0 + (pixel_vb - key_vb / key_len * proj * weight)
+ cr = 128.0 + (pixel_vr - key_vr / key_len * proj * weight)
+ red, green, blue = ycc_to_rgb(luma, cb, cr)
+ hit = (red, green, blue, coverage)
+ cache[rgb] = hit
+ cov = hit[3]
+ if cov <= 0:
+ continue
+ out_data[i] = (hit[0], hit[1], hit[2], int(alpha * cov))
+ out.putdata(out_data)
+ _flood_clear_background_ycc(out, source, key_cb, key_cr)
+ opaque = sum(out.getchannel("A").histogram()[_YCC_ALPHA_EMPTY + 1 :])
+ frac = opaque / (width * height) if width and height else 0.0
+ return out, frac
+
+
+def key_residue_fraction_ycc(image: Image.Image, key: tuple[int, int, int]) -> float:
+ """Fraction of pixels still opaque within the key's chroma family.
+
+ Symptom metric for "the matte did not finish removing the background".
+ """
+ width, height = image.size
+ if not width or not height:
+ return 0.0
+ _, key_cb, key_cr = rgb_to_ycc(*key)
+ pixels = image.load()
+ count = 0
+ for y in range(height):
+ for x in range(width):
+ red, green, blue, alpha = pixels[x, y]
+ if alpha <= _YCC_ALPHA_EMPTY:
+ continue
+ _, cb, cr = rgb_to_ycc(red, green, blue)
+ if math.hypot(cb - key_cb, cr - key_cr) < _YCC_KEY_RESIDUE_DIST:
+ count += 1
+ return count / (width * height)
+
+
+def _cleanup_alpha_ycc(image: Image.Image) -> None:
+ """Remove fully isolated opaque dots and fill nearly-enclosed pinholes.
+
+ Decisions are made on an alpha snapshot so the pass cannot cascade; soft
+ matte edges are untouched (only 0-neighbor dots and ≥7-neighbor holes).
+ """
+ width, height = image.size
+ if width < 3 or height < 3:
+ return
+ # PIL 네이티브 스텐실 — 8이웃 불투명 카운트를 시프트-합으로 벡터화한다 (핫스팟:
+ # 상태당 추출의 ~17%, 1280×720 전체 순회). 정수 논리(임계 비교·이웃 카운트)라
+ # 픽셀 루프와 **바이트 동일**하며, numpy 없이 pillow 만으로 된다.
+ alpha = image.getchannel("A")
+ # op: 불투명 마스크 (0/1) — before 스냅샷과 같은 기준 (> EMPTY).
+ op = alpha.point(lambda a: 1 if a > _YCC_ALPHA_EMPTY else 0)
+ # 1px zero-pad 후 8방향 크롭으로 이웃을 꺼내 합산 (경계 밖 = 0, 정수 덧셈은 순서 무관).
+ padded = Image.new("L", (width + 2, height + 2), 0)
+ padded.paste(op, (1, 1))
+ neighbors = None
+ for dx, dy in ((-1, 0), (1, 0), (0, -1), (0, 1),
+ (-1, -1), (1, -1), (-1, 1), (1, 1)):
+ shifted = padded.crop((1 + dx, 1 + dy, 1 + dx + width, 1 + dy + height))
+ neighbors = shifted if neighbors is None else ImageChops.add(neighbors, shifted)
+ # combined = op*16 + neighbors (둘 다 작아 24 이하) → 단일 LUT 로 두 마스크 분리.
+ combined = ImageChops.add(op.point(lambda v: v * 16), neighbors)
+ clear_mask = combined.point(lambda v: 255 if (v >> 4) == 1 and (v & 15) == 0 else 0)
+ fill_mask = combined.point(lambda v: 255 if (v >> 4) == 0 and (v & 15) >= 7 else 0)
+ # 원본은 알파만 바꾼다 (RGB 불변) — 스냅샷에서 시작해 두 disjoint 마스크만 덮어쓴다.
+ new_alpha = alpha.copy()
+ new_alpha.paste(0, mask=clear_mask)
+ new_alpha.paste(255, mask=fill_mask)
+ image.putalpha(new_alpha)
+
+
+def remove_chroma_background_ycbcr(
+ image: Image.Image,
+ chroma_key: tuple[int, int, int],
+ warnings: list[str] | None = None,
+) -> Image.Image:
+ """Chrominance-plane matting with self-diagnostic pure-key rematte.
+
+ Pipeline: detect the background key from the borders (CbCr histogram
+ mode), soft-matte + despill + border flood fill, then check the two
+ mis-detection symptoms — opaque-fraction spike (subject erased instead of
+ background) and declared-key residue spike (background survived). Either
+ symptom triggers a rematte with the declared pure key; the better result
+ wins and the fallback is reported through `warnings` (observable, never
+ silent).
+ """
+
+ def note(message: str) -> None:
+ if warnings is not None:
+ warnings.append(message)
+ print(f"[chroma-ycbcr] {message}", file=sys.stderr)
+
+ rgba = image.convert("RGBA")
+ detected = detect_background_key_ycc(rgba, chroma_key)
+ out, opaque_frac = _matte_ycc(rgba, detected)
+ residue = key_residue_fraction_ycc(out, chroma_key)
+ used_declared = detected == tuple(chroma_key)
+
+ if not used_declared and (
+ opaque_frac > _YCC_REMATTE_OPAQUE_FRAC or residue > _YCC_REMATTE_RESIDUE_FRAC
+ ):
+ retry, retry_frac = _matte_ycc(rgba, chroma_key)
+ retry_residue = key_residue_fraction_ycc(retry, chroma_key)
+ better_frac = retry_frac < opaque_frac - 0.03 and retry_frac > 0.02
+ less_residue = retry_residue < residue
+ if (better_frac or less_residue) and retry_frac > 0.02:
+ note(
+ f"detected key {detected} rejected (opaque {opaque_frac:.3f}, "
+ f"residue {residue:.4f}) — rematted with declared key {tuple(chroma_key)}"
+ )
+ out, opaque_frac, residue = retry, retry_frac, retry_residue
+ used_declared = True
+
+ if not used_declared:
+ # Detected key outside the declared key's chroma family (dark/neutral
+ # border mis-read): also try the declared pure key, keep the cleaner.
+ _, detected_cb, detected_cr = rgb_to_ycc(*detected)
+ _, declared_cb, declared_cr = rgb_to_ycc(*chroma_key)
+ if math.hypot(detected_cb - declared_cb, detected_cr - declared_cr) > _YCC_KEY_RESIDUE_DIST:
+ retry, retry_frac = _matte_ycc(rgba, chroma_key)
+ if retry_frac > 0.02 and key_residue_fraction_ycc(retry, chroma_key) < residue:
+ note(
+ f"detected key {detected} outside declared key family — "
+ f"rematted with declared key {tuple(chroma_key)}"
+ )
+ out = retry
+
+ _cleanup_alpha_ycc(out)
+ return out
+
+
+def connected_components(image: Image.Image) -> list[dict[str, Any]]:
+ alpha = image.getchannel("A")
+ width, height = image.size
+ data = alpha.tobytes()
+ visited = bytearray(width * height)
+ components: list[dict[str, Any]] = []
+
+ for start, alpha_value in enumerate(data):
+ if alpha_value <= 16 or visited[start]:
+ continue
+ stack = [start]
+ visited[start] = 1
+ pixels: list[int] = []
+ min_x = width
+ min_y = height
+ max_x = 0
+ max_y = 0
+
+ while stack:
+ current = stack.pop()
+ pixels.append(current)
+ x = current % width
+ y = current // width
+ min_x = min(min_x, x)
+ min_y = min(min_y, y)
+ max_x = max(max_x, x)
+ max_y = max(max_y, y)
+
+ for neighbor in (current - 1, current + 1, current - width, current + width):
+ if neighbor < 0 or neighbor >= len(data) or visited[neighbor]:
+ continue
+ nx = neighbor % width
+ if abs(nx - x) > 1:
+ continue
+ if data[neighbor] > 16:
+ visited[neighbor] = 1
+ stack.append(neighbor)
+
+ components.append(
+ {
+ "pixels": pixels,
+ "area": len(pixels),
+ "bbox": (min_x, min_y, max_x + 1, max_y + 1),
+ "center_x": (min_x + max_x + 1) / 2,
+ }
+ )
+ return components
+
+
+def component_group_image(source: Image.Image, components: list[dict[str, Any]], padding: int = 4) -> Image.Image:
+ width, height = source.size
+ min_x = max(0, min(component["bbox"][0] for component in components) - padding)
+ min_y = max(0, min(component["bbox"][1] for component in components) - padding)
+ max_x = min(width, max(component["bbox"][2] for component in components) + padding)
+ max_y = min(height, max(component["bbox"][3] for component in components) + padding)
+ output = Image.new("RGBA", (max_x - min_x, max_y - min_y), (0, 0, 0, 0))
+ source_pixels = source.load()
+ output_pixels = output.load()
+ for component in components:
+ for pixel_index in component["pixels"]:
+ x = pixel_index % width
+ y = pixel_index // width
+ output_pixels[x - min_x, y - min_y] = source_pixels[x, y]
+ return output
+
+
+def cell_geometry(cell: dict[str, Any]) -> tuple[int, int, int, int]:
+ width = int(cell.get("width", cell.get("size", 0)))
+ height = int(cell.get("height", cell.get("size", 0)))
+ safe_margin_x = int(cell.get("safe_margin_x", cell.get("safe_margin", 0)))
+ safe_margin_y = int(cell.get("safe_margin_y", cell.get("safe_margin", 0)))
+ if width <= 0 or height <= 0:
+ raise SystemExit("cell width/height must be positive in sprite-request.json")
+ return width, height, safe_margin_x, safe_margin_y
+
+
+# align_x "alpha-centroid" 는 perfectpixel-studio internal/sprite/extract.go 이식
+# (github.com/gykim80/perfectpixel-studio, MIT). bbox 중심 정렬은 팔/무기가 뻗은
+# 프레임에서 면적이 큰 몸통을 반대로 밀어 재생 시 좌우 지터를 만들고, 알파 가중
+# 무게중심 cx=Σ(x·α)/Σα 는 몸통이 지배해 축이 안정된다. α ≤ 10 은 소프트 매팅
+# 프린지로 보고 무게에서 제외한다 (원본 alphaThreshold 와 동일).
+ALPHA_CENTROID_MIN_ALPHA = 10
+
+
+def _alpha_centroid_x(sprite: Image.Image, bottom_fraction: float = 1.0, min_alpha: int = 0) -> float:
+ alpha = sprite.getchannel("A")
+ width, height = sprite.size
+ pixels = alpha.load()
+ y_start = max(0, height - max(2, round(height * bottom_fraction)))
+ total = 0
+ weighted = 0.0
+ for y in range(y_start, height):
+ for x in range(width):
+ value = pixels[x, y]
+ if value > min_alpha:
+ total += value
+ weighted += value * (x + 0.5)
+ if total == 0 and bottom_fraction < 1.0:
+ return _alpha_centroid_x(sprite, 1.0, min_alpha)
+ return (weighted / total) if total else width / 2.0
+
+
+def _alpha_centroid_row_left(frame: Image.Image, cell_width: int, scale: int) -> int:
+ # 픽셀 언페이크 행 경로의 프레임별 가로 배치 (align_x: alpha-centroid 전용).
+ # 행 union 공동 left 는 register_row_frames 의 정합 잔차가 그대로 지터로
+ # 남는다 — perfectpixel 방식대로 프레임마다 무게중심을 셀 중앙에 앉힌다.
+ # NEAREST xN 업스케일은 논리 픽셀 중심 (x+0.5) 을 scale·(x+0.5) 로 보내므로
+ # 논리 해상도에서 잰 무게중심에 scale 을 곱하면 리샘플 없이 정확하다.
+ left = round(cell_width / 2.0 - scale * _alpha_centroid_x(frame, 1.0, ALPHA_CENTROID_MIN_ALPHA))
+ left = max(0, min(cell_width - frame.width * scale, left))
+ return left - left % scale # 논리 픽셀 격자 스냅 (flip 대칭 보존)
+
+
+def _kcentroid_downscale(sprite: Image.Image, target_width: int, target_height: int, detail_bias: bool = False) -> Image.Image:
+ # Astropulse kCentroid-style pixel-art downscale: each output pixel takes the
+ # centroid of the dominant 2-means color cluster of its source block, so dark
+ # outlines survive instead of being averaged away (LANCZOS) or arbitrarily
+ # sampled (NEAREST when the target grid does not match the art's pixel grid).
+ source = sprite.convert("RGBA")
+ source_width, source_height = source.size
+ src = source.load()
+ output = Image.new("RGBA", (target_width, target_height), (0, 0, 0, 0))
+ out = output.load()
+ for oy in range(target_height):
+ y0 = oy * source_height // target_height
+ y1 = max(y0 + 1, (oy + 1) * source_height // target_height)
+ for ox in range(target_width):
+ x0 = ox * source_width // target_width
+ x1 = max(x0 + 1, (ox + 1) * source_width // target_width)
+ block = [src[x, y] for y in range(y0, y1) for x in range(x0, x1)]
+ opaque = [p for p in block if p[3] >= 128]
+ if len(opaque) * 2 < len(block):
+ continue
+ if len(opaque) == 1:
+ out[ox, oy] = opaque[0]
+ continue
+ color = _dominant_block_color(opaque, detail_bias)
+ alpha_value = sum(p[3] for p in opaque) // len(opaque)
+ out[ox, oy] = (color[0], color[1], color[2], alpha_value)
+ return output
+
+
+def fit_to_cell(
+ image: Image.Image,
+ cell_width: int,
+ cell_height: int,
+ safe_margin_x: int,
+ safe_margin_y: int,
+ fit: dict[str, Any] | None = None,
+) -> Image.Image:
+ # `fit` comes from sprite-request.json ("fit" object):
+ # resample: "lanczos" (default) | "nearest" | "kcentroid" — kcentroid is the
+ # pixel-art downscale that keeps 1px dark outlines readable
+ # align_x: "foot-centroid" (default) | "centroid" | "alpha-centroid" |
+ # "bbox-center" —
+ # foot-centroid anchors on the bottom 20% alpha (the legs), so
+ # trailing hair/capes do not pull the body off the cell axis
+ # (critical for runtime horizontal flip); alpha-centroid is the
+ # perfectpixel-studio port — full alpha-weighted centroid that
+ # ignores soft-matte fringe (α ≤ 10), and in the pixel unfake
+ # row path it is applied per frame instead of the row union
+ # align_y: "bottom" (default) | "center" — bottom pins feet to a shared baseline
+ # 2026-07-04 (maintainer): 기본값을 foot-centroid/bottom 으로 승격 — 프레임 간
+ # "무게감"(발밑 기준선)이 기본으로 잡혀야 한다. pixel_unfake 경로와 동일 기본.
+ fit = fit or {}
+ resample_name = str(fit.get("resample", "lanczos")).lower()
+ align_x = str(fit.get("align_x", "foot-centroid")).lower()
+ align_y = str(fit.get("align_y", "bottom")).lower()
+ bbox = image.getbbox()
+ target = Image.new("RGBA", (cell_width, cell_height), (0, 0, 0, 0))
+ if bbox is None:
+ return target
+ sprite = image.crop(bbox)
+ max_width = max(1, cell_width - safe_margin_x * 2)
+ max_height = max(1, cell_height - safe_margin_y * 2)
+ scale = min(max_width / sprite.width, max_height / sprite.height, 1.0)
+ if scale != 1.0:
+ new_size = (max(1, round(sprite.width * scale)), max(1, round(sprite.height * scale)))
+ if resample_name == "kcentroid":
+ sprite = _kcentroid_downscale(sprite, new_size[0], new_size[1])
+ else:
+ sprite = sprite.resize(
+ new_size,
+ Image.Resampling.NEAREST if resample_name == "nearest" else Image.Resampling.LANCZOS,
+ )
+ cropped = sprite.getbbox()
+ if cropped is not None:
+ sprite = sprite.crop(cropped)
+ if align_x == "foot-centroid":
+ left = round(cell_width / 2.0 - _alpha_centroid_x(sprite, 0.2))
+ left = max(0, min(cell_width - sprite.width, left))
+ elif align_x == "centroid":
+ left = round(cell_width / 2.0 - _alpha_centroid_x(sprite))
+ left = max(0, min(cell_width - sprite.width, left))
+ elif align_x == "alpha-centroid":
+ left = round(cell_width / 2.0 - _alpha_centroid_x(sprite, 1.0, ALPHA_CENTROID_MIN_ALPHA))
+ left = max(0, min(cell_width - sprite.width, left))
+ else:
+ left = (cell_width - sprite.width) // 2
+ if align_y == "bottom":
+ top = max(0, cell_height - safe_margin_y - sprite.height)
+ else:
+ top = (cell_height - sprite.height) // 2
+ target.alpha_composite(sprite, (left, top))
+ return target
+
+
+# --- pixel unfake pipeline (fit.pixel_unfake) -----------------------------
+# unfake.js/pixeldetector 계열 접근: ① runs 기반으로 생성물의 논리 픽셀 pitch 검출
+# ② 에지 히스토그램으로 격자 위상(offset) 정렬 ③ 격자 단위 dominant-color 스냅
+# 다운스케일(진짜 해상도 복원) ④ 런 전체 공유 팔레트 양자화 + 알파 이진화
+# ⑤ 정수배 NEAREST 업스케일로 셀 배치. 비정수 리샘플이 전혀 없어 픽셀이 깨지지 않는다.
+
+
+def _edge_histograms(image: Image.Image) -> tuple[list[int], list[int], int, int]:
+ """Color-transition edge counts indexed by x (vertical edges) and y
+ (horizontal edges). AA ramps register near the true block boundary, so the
+ boundary position signal survives anti-aliasing."""
+ pixels = image.convert("RGBA").load()
+ width, height = image.size
+ col_edges = [0] * width
+ row_edges = [0] * height
+ for y in range(0, height, 2):
+ for x in range(1, width):
+ a = pixels[x, y]
+ b = pixels[x - 1, y]
+ if abs(a[0] - b[0]) + abs(a[1] - b[1]) + abs(a[2] - b[2]) + abs(a[3] - b[3]) > 96:
+ col_edges[x] += 1
+ for x in range(0, width, 2):
+ for y in range(1, height):
+ a = pixels[x, y]
+ b = pixels[x, y - 1]
+ if abs(a[0] - b[0]) + abs(a[1] - b[1]) + abs(a[2] - b[2]) + abs(a[3] - b[3]) > 96:
+ row_edges[y] += 1
+ return col_edges, row_edges, width, height
+
+
+def detect_pixel_pitch(strip: Image.Image, max_pitch: int = 48) -> int:
+ """True pixel-block pitch via edge-to-gridline alignment scoring.
+
+ 이전 구현(같은 색 런 길이 최빈값)은 AA 가장자리·블록 내부 질감이 만드는
+ 2px 런에 지배당해 큰 블록(~16px)을 놓치고 항상 2 를 내놨다 — 그 결과
+ 그리드 비정렬 축소로 이웃 픽셀이 섞여 뭉개졌다 (2026-07-05 사고).
+ 새 방식: 후보 피치 p 와 위상마다 "색 경계가 그리드선 ±w 안에 모이는
+ 비율"에서 우연 기대치 (그 창이 덮는 잉여류 수)/p 를 뺀 점수의 argmax.
+ 작은 p 가 공짜로 이기는 문제를 우연 보정이 막는다. 확신 없으면 1(스냅 안 함)로
+ 관측 가능하게 떨어진다.
+
+ 창 폭 w 는 모든 p 에 동일하다. 예전에는 `w = 1 if p >= 8 else 0` 이라
+ p>=8 에서만 창이 열렸고, 그 결과 참 피치(>=8)의 우연 기대치가 3/p 로
+ 부풀어 창 없는 약수(p<8)에게 졌다 — k=8,10,12,14 에서 정확히 k/2 를
+ 반환하던 원인 (합성 정답 테스트 test_pitch_ground_truth 로 고정).
+ 창이 p 를 넘어 잉여류를 중복 합산하지 않도록 잉여류는 집합으로 센다."""
+ image = strip.convert("RGBA")
+ col_edges, row_edges, width, height = _edge_histograms(image)
+
+ # 단순 argmax — 진짜 피치의 약수(p=7 vs 14)는 우연 기대치 |잉여류|/p 가
+ # 커서 자동으로 밀린다. 최고점이 문턱(0.2) 미만이면 그리드 확신 없음 →
+ # 1(스냅 안 함)로 관측 가능하게 폴백.
+ best_pitch, best_score = 1, 0.2
+ for p in range(2, max_pitch + 1):
+ score = _axis_int_score(col_edges, p) + _axis_int_score(row_edges, p)
+ if score > best_score:
+ best_pitch, best_score = p, score
+ return best_pitch
+
+
+def _axis_int_score(edges: list[int], p: int, w: int = 1) -> float:
+ """정수 피치 p 의 축별 점수 = (그리드선 ±w 에 모인 엣지 비율) − 우연 기대치.
+
+ 창 폭 w 는 모든 p 에 동일하고, 창이 덮는 잉여류는 집합으로 세어 중복 합산하지 않는다.
+ """
+ total = sum(edges) or 1
+ best = 0.0
+ for phase in range(p):
+ residues = {(phase + offset) % p for offset in range(-w, w + 1)}
+ hit = sum(sum(edges[r::p]) for r in residues)
+ score = hit / total - len(residues) / p
+ if score > best:
+ best = score
+ return best
+
+
+def _axis_int_seed(edges: list[int], max_pitch: int = 48) -> int:
+ """한 축만 보고 고른 정수 피치 씨앗. 확신 없으면 1."""
+ best_pitch, best_score = 1, 0.1
+ for p in range(2, max_pitch + 1):
+ score = _axis_int_score(edges, p)
+ if score > best_score:
+ best_pitch, best_score = p, score
+ return best_pitch
+
+
+def _axis_refine(edges: list[int], pitch: float, w: float = 1.0, bin_step: float = 0.25) -> tuple[float, float]:
+ """소수 피치 p 에서 최적 위상과 그 점수. 잉여류를 히스토그램으로 접어 O(nnz + p/step).
+
+ 정수 격자만 볼 수 있던 예전에는 참 피치 17.24 를 17 로 반올림했고, 그 0.24 가
+ 스프라이트 폭을 가로지르며 누적돼(23칸이면 5.5px) 셀 경계가 블록 한가운데를
+ 지났다. 작은 디테일은 두 셀에 반씩 걸려 평균에 먹혔다.
+ """
+ total = sum(edges) or 1
+ bins = max(4, int(round(pitch / bin_step)))
+ hist = [0] * bins
+ for x, count in enumerate(edges):
+ if count:
+ hist[int((x % pitch) / pitch * bins) % bins] += count
+ span = min(bins, max(1, int(round((2 * w) / pitch * bins)) + 1))
+ chance = min(1.0, span / bins)
+ doubled = hist + hist
+ window = sum(doubled[:span])
+ best_score, best_bin = window / total - chance, 0
+ for start in range(1, bins):
+ window += doubled[start + span - 1] - doubled[start - 1]
+ score = window / total - chance
+ if score > best_score:
+ best_score, best_bin = score, start
+ # 창의 기하학적 중심이 아니라 창 안 엣지의 가중 무게중심을 쓴다. 중심을 쓰면
+ # 엣지가 한 bin 에 몰린 완전 정렬 격자에서도 위상이 반창(=w) 만큼 밀렸다.
+ weight = sum(doubled[best_bin : best_bin + span])
+ if weight:
+ centre = sum((best_bin + k) * doubled[best_bin + k] for k in range(span)) / weight
+ else:
+ centre = best_bin + (span - 1) / 2.0
+ return best_score, (centre % bins) / bins * pitch
+
+
+def detect_pixel_grid(
+ strip: Image.Image, max_pitch: int = 48
+) -> tuple[tuple[float, float], tuple[float, float]]:
+ """참 픽셀 격자 = ((가로 피치, 세로 피치), (가로 위상, 세로 위상)). 전부 소수.
+
+ AI 가 그린 도트는 블록 폭이 정수로 떨어지지 않는다 (주인공 base = 17.24px).
+ 측정은 소수로 하고, 스냅 결과(논리 픽셀 수)는 정수로 떨어진다.
+
+ **피치는 축마다 다를 수 있다.** 생성물이 비균등 비율로 리스케일되면 가로 블록과 세로 블록의
+ 크기가 어긋난다 (주인공 chibi 베이스: 가로 30.38 / 세로 30.92). 한 피치를 두 축에
+ 강제하면 한 축이 통째로 미끄러진다 — 실측 가로 정렬률 11.7% (축별로 재면 75.7%).
+
+ 격자 확신이 없으면 ((1.0, 1.0), (0,0)) — 스냅하지 않는다.
+ """
+ image = strip.convert("RGBA")
+ combined = detect_pixel_pitch(image, max_pitch)
+ if combined <= 1:
+ return (1.0, 1.0), (0.0, 0.0)
+ col_edges, row_edges, _, _ = _edge_histograms(image)
+
+ half_span, step = 0.75, 0.02
+ span = int(round(half_span / step))
+
+ def refine(edges: list[int]) -> tuple[float, float]:
+ # 씨앗 후보 = 축별 씨앗 + 두 축 합산 씨앗.
+ # - 축별만 쓰면: 한 축의 정수 검출이 노이즈에 흔들려 약수(참 17.24 -> 씨앗 9)로 빠진다.
+ # - 합산만 쓰면: 가로 24 / 세로 30 처럼 축마다 블록이 다른 그림에서 한 축의 참값이
+ # ±0.75 정밀화 창 밖에 놓인다.
+ # 둘 다 후보로 두고 점수로 고르면 두 실패가 모두 막힌다.
+ axis_seed = _axis_int_seed(edges, max_pitch)
+ candidates = {float(s) for s in (axis_seed, combined) if s >= 2}
+ if not candidates:
+ return 1.0, 0.0
+ # 정수 씨앗은 참 피치의 정수배를 집을 수 있다 (참 16.5 -> 씨앗 33: 33 간격선은
+ # 엣지의 절반만 물지만, 정수만 보면 16 도 17 도 어긋나서 33 이 이긴다).
+ # 그래서 씨앗의 약수들도 후보로 함께 정밀화하고 점수로 고른다.
+ seeds = sorted(candidates | {s / d for s in candidates for d in (2, 3) if s / d >= 2.0})
+ best = (-1.0, float(max(candidates)), 0.0)
+ for centre in seeds:
+ # centre 자체가 반드시 샘플에 들어가도록 대칭으로 훑는다 (예전엔 15.99/16.01 만 봐서
+ # 정확히 정수인 격자에서도 소수로 빗나갔다).
+ for i in range(-span, span + 1):
+ pitch = centre + i * step
+ if pitch < 2.0 or pitch > max_pitch:
+ continue
+ score, phase = _axis_refine(edges, pitch)
+ if score > best[0] + 1e-9:
+ best = (score, pitch, phase)
+ return best[1], best[2]
+
+ pitch_x, phase_x = refine(col_edges)
+ pitch_y, phase_y = refine(row_edges)
+
+ # 축별 피치는 서로 크게 다를 수 없다. 비균등 리스케일이어도 실측 차이는 2% 수준이다
+ # (chibi 베이스: 30.38 / 30.92). 한 축이 다른 축의 1.5배를 넘게 벗어나면 그 축의
+ # 검출이 무너진 것이다 — 엣지가 적은 축(균일한 세로 막대가 화면을 채우는 carry 포즈 등)에서
+ # 참 피치의 약수가 이겨 3.00 같은 값이 나왔다 (down_carry_walk, 참값 9).
+ # 엣지 총량이 많은 축을 신뢰해 양쪽에 쓴다. 조용히 고치지 않고 축 하나를 버렸음을 남긴다.
+ lo, hi = sorted((pitch_x, pitch_y))
+ if lo >= 2.0 and hi / lo > 1.5:
+ if sum(col_edges) >= sum(row_edges):
+ pitch_y = pitch_x
+ else:
+ pitch_x = pitch_y
+
+ return (pitch_x, pitch_y), (phase_x, phase_y)
+
+
+# --- run-length pitch estimator (perfectpixel-studio unfake 이식) ------------
+# detect_pixel_grid(경계 히스토그램)의 세컨드 오피니언. 추정 전용 — 스냅 경로는
+# 이 값을 절대 쓰지 않는다. 두 추정기가 벌어지면 경고로만 표면화한다.
+
+RUNLEN_ALPHA_THRESHOLD = 10 # perfectpixel alphaThreshold — 소프트 매팅 프린지 제외
+RUNLEN_RGB_TOLERANCE = 12 # perfectpixel nearRGB tol — AA 미세 노이즈는 같은 색
+RUNLEN_MIN_RUNS = 32 # 축 전체 런이 이보다 적으면 추정 포기 (사진/노이즈)
+RUNLEN_MODE_SHARE = 0.5 # 최빈값 ±1 창이 가중 질량의 절반 미만이면 확신 없음
+
+
+def _runlen_axis_estimate(pixels, outer: int, inner: int, horizontal: bool, cap: int) -> float:
+ """한 축의 동일색 런 길이 히스토그램 → 가중 최빈값의 소수 추정. 확신 없으면 1.0.
+
+ 짧은 런(AA 잔재·질감)이 개수로는 항상 많으므로 원본과 같이 run 길이로 가중한다
+ (hist[s]·s). AI 도트의 블록 폭은 정수로 안 떨어지므로 최빈값 하나가 아니라
+ ±1 창의 가중 무게중심을 쓴다 — 참 피치 30.56 이면 30/31 런이 44:56 으로 섞여
+ 나오고, 그 무게중심이 소수 피치를 복원한다.
+ """
+ hist = [0] * (cap + 2)
+ for o in range(0, outer, 2):
+ prev = pixels[0, o] if horizontal else pixels[o, 0]
+ run = 1
+ for i in range(1, inner):
+ cur = pixels[i, o] if horizontal else pixels[o, i]
+ if (cur[3] <= RUNLEN_ALPHA_THRESHOLD and prev[3] <= RUNLEN_ALPHA_THRESHOLD) or (
+ cur[3] > RUNLEN_ALPHA_THRESHOLD
+ and prev[3] > RUNLEN_ALPHA_THRESHOLD
+ and abs(cur[0] - prev[0]) <= RUNLEN_RGB_TOLERANCE
+ and abs(cur[1] - prev[1]) <= RUNLEN_RGB_TOLERANCE
+ and abs(cur[2] - prev[2]) <= RUNLEN_RGB_TOLERANCE
+ ):
+ run += 1
+ else:
+ if 2 <= run <= cap:
+ hist[run] += 1
+ run = 1
+ prev = cur
+ if 2 <= run <= cap:
+ hist[run] += 1
+ if sum(hist) < RUNLEN_MIN_RUNS:
+ return 1.0
+ weighted = [count * length for length, count in enumerate(hist)]
+ mode = max(range(2, cap + 1), key=weighted.__getitem__)
+ lo, hi = max(2, mode - 1), min(cap, mode + 1)
+ window = sum(weighted[lo : hi + 1])
+ if not weighted[mode]:
+ return 1.0
+ # 확신 게이트: 최빈값의 고조파 패밀리(k·mode ±1)가 가중 질량의 절반은 차지해야
+ # 한다. 인접 논리 픽셀이 같은 색이면 런이 2·mode, 3·mode 로 늘어나므로 고조파는
+ # 최빈값을 반박하는 게 아니라 지지하는 증거다 (실측: synthetic_fixture_a down_idle 은
+ # 11 과 함께 22~23, 34~35 에 질량이 실린다). 패밀리 밖에 질량 절반이 흩어져
+ # 있으면 블록 구조 확신이 없는 것 — 1.0 으로 관측 가능하게 포기한다.
+ family = 0
+ for k in range(1, cap // mode + 2):
+ centre = k * mode
+ family += sum(weighted[max(2, centre - k) : min(cap, centre + k) + 1])
+ if family < sum(weighted) * RUNLEN_MODE_SHARE:
+ return 1.0
+ return sum(length * weighted[length] for length in range(lo, hi + 1)) / window
+
+
+def estimate_pixel_grid_runlen(strip: Image.Image, max_pitch: int = 48) -> tuple[float, float]:
+ """동일색 런 길이 최빈값으로 축별 피치를 추정한다 — 추정 전용 세컨드 오피니언.
+
+ perfectpixel-studio internal/sprite/pixelize.go 의 unfake(DetectPixelScale)
+ 이식 (MIT — NOTICE 표기). 원본은 수평/수직 런을 한 히스토그램에 합치지만,
+ 우리 목적은 detect_pixel_grid 의 축 붕괴 방어라 축별로 분리해 센다 — 회귀:
+ 주인공 컴포넌트에서 y 피치가 x 값(29.52)으로 붕괴, 실측 30.56. 붕괴
+ 메커니즘은 정수 씨앗 로터리 실패(참 소수 피치가 어떤 씨앗의 ±0.75 정밀화 창에도
+ 안 들어감)라 경계 히스토그램 안에서는 자기 진단이 안 된다. 런 길이는 완전히
+ 다른 신호(경계 위치가 아니라 경계 사이 거리)라 세컨드 오피니언이 된다.
+
+ 확신 없는 축은 1.0 — 런 수 부족(RUNLEN_MIN_RUNS), 최빈값 창 질량 미달
+ (RUNLEN_MODE_SHARE), 32px 미만 이미지 전부 관측 가능하게 포기한다.
+ """
+ image = strip.convert("RGBA")
+ width, height = image.size
+ if width < 32 or height < 32:
+ return (1.0, 1.0)
+ cap = min(max_pitch, min(width, height) // 8)
+ if cap < 2:
+ return (1.0, 1.0)
+ pixels = image.load()
+ return (
+ _runlen_axis_estimate(pixels, height, width, True, cap),
+ _runlen_axis_estimate(pixels, width, height, False, cap),
+ )
+
+
+def crosscheck_pitch_runlen(
+ grid_pitch: tuple[float, float],
+ runlen_pitch: tuple[float, float],
+ axis_tolerance: float = 0.12,
+ ratio_tolerance: float = 0.02,
+) -> list[str]:
+ """detect_pixel_grid vs 런길이 추정의 교차검증. 이견은 경고 문자열 목록으로.
+
+ 추정 전용 — 어느 값도 바꾸지 않는다. 자동 교체 금지: 어느 쪽이 맞는지는
+ 사람이/상위 게이트가 판단한다 (No Silent Fallback).
+
+ runlen 의 오차 모델이 규칙 모양을 정한다: AA 가 런 양끝을 갉아먹으므로 runlen 은
+ 참 피치를 **한쪽(하향)으로만** 빗나간다 — 픽셀 단위 절대 바이어스라 작은 피치일수록
+ 상대 오차가 커진다 (실측: 피치 30 에서 −0.8px≈3%, 피치 9 에서 −2px≈20%).
+
+ - 약수 오검출 (runlen 이 grid 보다 훨씬 큼): grid 가 참 피치의 약수로 떨어진 것
+ (참 29.5 를 14.73 으로). runlen 은 과대추정하지 않으므로 슬랙 2px 만 두면 된다.
+ - 배수/고조파 오검출 (grid 가 runlen 보다 훨씬 큼): grid 가 참 피치의 배수·고조파에
+ 낚인 것. runlen 하향 바이어스(≤3px) 를 슬랙으로 흡수한 뒤에도 크게 남으면 경고.
+ - 축비(y/x) 불일치: 축 붕괴 (y 가 x 값으로). 회귀의 축차는 3.5%(29.52 vs 30.56)라
+ 축별 오차로는 임계 밑에 숨는다. AA 하향 바이어스의 공통 성분은 비율에서
+ 상쇄되지만(실측: 붕괴 신호 2.8%, 건강한 검출의 비 오차 0.7%), 축별 편차는
+ 남는다 — 편차는 절대량(서브픽셀, 축당 ~±0.35px)이라 비율 노이즈가 ~0.7/피치 로
+ 작은 피치에서 커진다 (synthetic_fixture_a 실측: 8~15px 대역에서 3~9% 드리프트가 흔함,
+ 진위 판별 불가). 그래서 0.7/피치 를 하한 슬랙으로 둔다: 히어로 스케일(30px)의
+ 실붕괴 신호(2.8%)는 임계(2.4%) 위, 소피치 대역의 판별 불가 드리프트는 밑.
+ """
+ notes: list[str] = []
+ for name, grid, runlen in (
+ ("x", grid_pitch[0], runlen_pitch[0]),
+ ("y", grid_pitch[1], runlen_pitch[1]),
+ ):
+ if grid < 2.0 or runlen < 2.0:
+ continue
+ if runlen - grid > max(axis_tolerance * grid, 2.0):
+ notes.append(
+ f"pitch crosscheck: run-length mode estimates {name}={runlen:.2f} but grid "
+ f"detection returned {name}={grid:.2f} — likely a divisor misdetection"
+ )
+ elif grid - runlen > axis_tolerance * grid + 3.0:
+ notes.append(
+ f"pitch crosscheck: run-length mode estimates {name}={runlen:.2f} but grid "
+ f"detection returned {name}={grid:.2f} — likely a multiple/harmonic misdetection"
+ )
+ if min(*grid_pitch, *runlen_pitch) >= 2.0:
+ grid_ratio = grid_pitch[1] / grid_pitch[0]
+ runlen_ratio = runlen_pitch[1] / runlen_pitch[0]
+ drift = abs(runlen_ratio / grid_ratio - 1.0)
+ if drift > max(ratio_tolerance, 0.7 / min(grid_pitch)):
+ notes.append(
+ f"pitch crosscheck: axis ratio y/x disagrees — run-length {runlen_ratio:.3f} vs "
+ f"grid {grid_ratio:.3f} ({drift:.1%}); one axis may have collapsed to the other"
+ )
+ return notes
+
+
+
+# 임계값 t = ⌊평균⌋ 별 바이트 변환표. `_LE_KEEP[t]` 는 `v ≤ t` 를 그대로 두고 그 위를
+# 0 으로 접어 `sum()` 이 곧 `S_lo` 가 되게 하고, `_LE_ONES[t]` 는 같은 조건을 1/0 으로
+# 접어 `sum()` 이 `C_lo` 가 되게 한다 (`_grid_score_edges` 의 정수 정식화).
+_LE_KEEP: list[bytes] = [bytes(range(t + 1)) + bytes(255 - t) for t in range(256)]
+_LE_ONES: list[bytes] = [b"\x01" * (t + 1) + b"\x00" * (255 - t) for t in range(256)]
+
+
+def _grid_rows(component: Image.Image) -> tuple[list[list[int]], list[bytes]]:
+ """행별 불투명 픽셀 색인 — (행별 x 좌표 오름차순, 그 픽셀들의 RGB 를 이어붙인 bytes).
+
+ 채점은 셀 안의 불투명 픽셀만 본다. 격자 위상이 바뀌어도 이 색인은 그대로이므로
+ 컴포넌트당 한 번만 만들어 `_best_phase` 의 위상 스캔 전체가 공유한다. 압축해 두면
+ 셀 픽셀 수집이 파이썬 픽셀 루프가 아니라 **bytes 슬라이스**가 된다.
+ """
+ if component.mode != "RGBA":
+ # 알파로 걸러 낸다 — 채널 수가 다르면 `row[3::4]` 가 조용히 엉뚱한 바이트를 읽는다.
+ raise ValueError(f"_grid_rows expects an RGBA component, got {component.mode!r}")
+ w, h = component.width, component.height
+ data = component.tobytes() # RGBA, 행 우선
+ row_pos: list[list[int]] = []
+ row_rgb: list[bytes] = []
+ for y in range(h):
+ base = y * w * 4
+ row = data[base:base + w * 4]
+ alpha = row[3::4]
+ # 알파 128 = 이 모듈 전역의 불투명 판정 관례다 (extract.py 안 15곳이 같은 리터럴을
+ # 쓴다). 이 함수만 이름 붙인 상수로 빼면 SSoT 가 반쯤만 옮겨져 더 나빠지므로,
+ # 통일은 모듈 전체를 한 번에 바꾸는 별도 작업으로 둔다 (plan Notes).
+ pos = [x for x in range(w) if alpha[x] >= 128]
+ row_pos.append(pos)
+ row_rgb.append(b"".join(row[4 * x:4 * x + 3] for x in pos))
+ return row_pos, row_rgb
+
+
+def _grid_row_splits(row_pos: list[list[int]], xs: tuple[int, ...] | list[int],
+ w: int) -> list[list[int]]:
+ """행마다 x 절단선이 압축 색인의 어느 인덱스에 떨어지는지 (셀 픽셀 슬라이스 경계).
+
+ x 분할은 6종 정도만 나오는데 격자는 36종이라, 분할별로 한 번 구해 두면 셀마다
+ `bisect` 를 다시 돌리지 않는다.
+ """
+ cuts = [min(e, w) for e in xs]
+ out: list[list[int]] = []
+ for pos in row_pos:
+ lo = 0
+ idx = []
+ for cut in cuts:
+ lo = bisect_left(pos, cut, lo)
+ idx.append(lo)
+ out.append(idx)
+ return out
+
+
+def _grid_uniformity(component: Image.Image, pitch: tuple[float, float],
+ phase: tuple[float, float]) -> float:
+ """격자 가설의 셀 내부 색 분산 (낮을수록 진짜 격자). 불투명 픽셀만, 셀 크기 가중.
+
+ 위상 스캔은 이 함수를 거치지 않는다 — `_best_phase` 는 행 색인을 한 번 만들어
+ `_grid_score_edges` 를 직접 부른다. 여기는 단발 채점(`arbitrate_pitch` 의 진단)
+ 전용이라 색인을 주입받을 자리가 없다.
+ """
+ w, h = component.width, component.height
+ rows = _grid_rows(component)
+ xs = _grid_edges(w, pitch[0], phase[0])
+ ys = _grid_edges(h, pitch[1], phase[1])
+ return _grid_score_edges(rows, w, h, xs, ys)
+
+
+def _grid_score_edges(rows: tuple[list[list[int]], list[bytes]], w: int, h: int,
+ xs: tuple[int, ...] | list[int], ys: tuple[int, ...] | list[int],
+ splits: list[list[int]] | None = None) -> float:
+ """`_grid_uniformity` 의 채점 코어 — 격자 경계가 이미 정해진 뒤의 순수 계산.
+
+ 핫스팟이다 (실측 2026-07-25: `synthetic_fixture_b down_idle` 추출 35.5s 중 `_best_phase` 가
+ 23.9s = 67%, 컴포넌트당 유니크 격자 36 × 셀 1344 ≈ 48k 셀 · 픽셀 방문 6.6M 회).
+
+ **정수 정확 산술** — 셀 편차를 float 로 누적하지 않는다. 셀의 한 채널 값 `v` 와
+ 평균 `m = s/n` 에 대해 `Σ(v − m) = 0` 이므로 평균 아래/위의 절대편차 합이 같고,
+
+ Σ|v − m| = 2·(m·C_lo − S_lo) (C_lo, S_lo = v ≤ ⌊m⌋ 의 개수·합)
+
+ 양변에 `n` 을 곱하면 `n·Σ|v − m| = 2·(s·C_lo − n·S_lo)` 로 **전부 정수**다. 셀의
+ 기여분 `dev·n` 은 `T/n` 이고(`dev = T/n²`), `T` 는 세 채널의 정확한 정수합이다.
+ 부동소수는 셀당 나눗셈 한 번과 누적에만 남는다.
+
+ 이 정식화 이전에는 원본 float 축약식(`sum(sum(abs(...)))`)을 글자 그대로 재현해
+ 바이트 동일을 계약으로 삼았다. 계약을 **정확한 유리수 값**으로 교체했다 (plan
+ `sprite-gen/best-phase-hotspot`): 새 값은 같은 양의 정확판이라 옛 float 누적과
+ 마지막 ULP 에서 갈리지만(실측 최대 상대차 1.8e-16), 파이프라인이 실제로 쓰는
+ 출력인 `_best_phase` 의 argmin 은 전수 동일하다(synthetic_fixture_b 8 컴포넌트 × 64 위상).
+
+ **argmin 불변은 정리가 아니라 측정이다** — argmin 은 점수의 불연속 함수라 "점수가
+ ULP 만큼 바뀌면 argmin 이 안 바뀐다"를 보장하는 정리는 없다. 뒤집히려면 서로 다른
+ 두 위상의 점수가 유효숫자 15자리까지 붙어야 하는데, 관측된 distinct 점수 최소 간격은
+ ~1e-5 다 (validator 독립 측정 2026-07-25: 저대비 팔레트를 포함한 무작위·적대 컴포넌트
+ 160개에서 최소 간격 1.15e-5 vs 신·구 최대 상대차 8.39e-15 = 여유 1.4e9 배, 별도
+ 300 컴포넌트 argmin 불일치 0건). 점수가 수천 개 정수 유래 셀 기여분의 합이라 그렇게
+ 붙기 어렵다. 자기 자산에서 다시 재려면 이 두 수(점수 간격 / 상대차)를 재라.
+
+ **"뒤집히면 새 값이 맞다" 라고는 못 쓴다** — 정확한 건 **셀 단위까지**다. `total_dev` 는
+ 여전히 셀 기여분을 naive float 로 누적하므로 전체 점수의 정확도 우위는 평균적 경향이지
+ 보장이 아니다 (maintainer 실측 2026-07-25, 격자 840개를 `Fraction` 참값과 대조: 신 값이 더
+ 가까움 12.6% / **구 값이 더 가까움 7.0%** / 동률 80.4%, 차이 크기는 상대 4.0e-16 이하라
+ 행동 영향 0). 이 문단은 한때 "뒤집혀도 새 값이 정답 쪽" 이라고 단정했는데, 그게 바로 위
+ 문단이 경계하라고 적은 "측정 안 한 성질을 불변식으로 박기" 였다.
+ 정확 동점은 양쪽 다 안전하다: 순회 순서(`for i / for j`)와 strict `<` 동점 처리가
+ 구 코드와 동일해 동점은 양쪽 다 첫 위상으로 간다.
+
+ `C_lo`/`S_lo` 는 `bytes.translate` + `sum` 으로 C 레벨에서 뽑는다 — 임계값별 변환표는
+ 256개뿐이라 모듈 상수로 굽는다.
+
+ `_best_phase` 가 이 코어를 (xs, ys) 로 메모이즈한다: 8단계 위상 스캔은 `_grid_edges`
+ 의 정수 스냅 때문에 서로 다른 위상이 **같은 정수 경계**로 자주 붕괴한다 (offset 이
+ 피치의 1/4 미만이면 lead=0 등). 같은 경계 → 같은 계산 → 같은 값이므로 캐시는
+ 정확하며, 64회 격자 순회가 고유 경계 수(실측 36)만큼으로 줄어든다.
+ """
+ row_pos, row_rgb = rows
+ if splits is None:
+ splits = _grid_row_splits(row_pos, xs, w)
+ total_dev = 0.0
+ total_n = 0
+ ncol = len(xs) - 1
+ for yi in range(len(ys) - 1):
+ band = range(ys[yi], min(ys[yi + 1], h))
+ for xi in range(ncol):
+ parts = []
+ add = parts.append
+ for y in band:
+ idx = splits[y]
+ lo, hi = idx[xi], idx[xi + 1]
+ if hi > lo:
+ add(row_rgb[y][3 * lo:3 * hi])
+ cell = b"".join(parts)
+ n = len(cell) // 3
+ if n < 2:
+ continue
+ t = 0
+ for k in range(3):
+ vals = cell[k::3]
+ s = sum(vals)
+ floor_mean = s // n
+ t += (s * sum(vals.translate(_LE_ONES[floor_mean]))
+ - n * sum(vals.translate(_LE_KEEP[floor_mean])))
+ # `2 *` 는 위 대칭성(평균 아래 합 = 위 합)의 계수다.
+ total_dev += 2 * t / n
+ total_n += n
+ return (total_dev / total_n) if total_n else 1e9
+
+
+def _best_phase(component: Image.Image, pitch: tuple[float, float]) -> tuple[float, float]:
+ """주어진 피치에서 셀 균일도가 최선인 위상 (축별 8단계 탐색 — 결정론)."""
+ best = (0.0, 0.0)
+ best_score = None
+ steps = 8
+ # 불투명 픽셀 색인을 한 번만 만들어 모든 위상이 공유한다 (재로딩 제거).
+ rows = _grid_rows(component)
+ w, h = component.width, component.height
+ # (xs, ys) 정수 경계로 채점을 메모이즈 — 위상 스캔은 같은 경계로 자주 붕괴한다.
+ cache: dict[tuple, float] = {}
+ split_cache: dict[tuple, list[list[int]]] = {}
+ for i in range(steps):
+ for j in range(steps):
+ phase = (pitch[0] * i / steps, pitch[1] * j / steps)
+ xs = tuple(_grid_edges(w, pitch[0], phase[0]))
+ ys = tuple(_grid_edges(h, pitch[1], phase[1]))
+ key = (xs, ys)
+ score = cache.get(key)
+ if score is None:
+ splits = split_cache.get(xs)
+ if splits is None:
+ splits = split_cache[xs] = _grid_row_splits(rows[0], xs, w)
+ score = _grid_score_edges(rows, w, h, xs, ys, splits)
+ cache[key] = score
+ if best_score is None or score < best_score:
+ best_score = score
+ best = phase
+ return best
+
+
+def arbitrate_pitch(images: list, detect_pitch: tuple[float, float],
+ runlen_pitch: tuple[float, float],
+ tag: str, warnings_out: list) -> tuple[tuple[float, float], str]:
+ """detect 합의와 runlen 세컨드 오피니언이 크게 다를 때 실측 채점으로 승자 채택.
+
+ 하모닉 오검출 (회귀 2026-07-18 side_idle: detect 가 참 피치 9.5 의 하모닉
+ 6.5 를 잡아 45×83 과분할 → 물리캡 강제 리사이즈 = 이중 리샘플 찌그러짐) 방어.
+ 자동 폴백이 아니라 두 가설을 셀 균일도로 결정론 채점해 채택하고, 결과를
+ 경고로 관측 가능하게 남긴다.
+
+ 위상은 받지 않는다 — 채점은 가설마다 `_best_phase` 로 실측 위상을 직접 잡고,
+ 스냅 경로도 위상을 따로 재계산한다 (plan `frame-pitch-consensus-eats-a-row`).
+ 예전에는 프레임별 검출 위상을 받아 그대로 되돌려주기만 했다 (읽지 않는 인자).
+
+ 반환: (채택 피치, 채택 근거 라벨)."""
+ dx, dy = detect_pitch
+ rx, ry = runlen_pitch
+ if rx < 2.0 or ry < 2.0:
+ return detect_pitch, "detect"
+ if abs(dx - rx) <= max(1.0, dx * 0.15) and abs(dy - ry) <= max(1.0, dy * 0.15):
+ return detect_pitch, "detect"
+ # 채택은 하지 않는다 (회귀 2026-07-18: 균일도 지표는 세밀 격자에 자명하게
+ # 유리한 편향이 있어 up_idle 을 잘못 뒤집었다). 관측 로그만 남긴다 — 큰 불일치의
+ # 실제 의미는 대개 '생성 해상도가 셀 계약보다 세밀' (해법 = 굵기 강제 리롤).
+ # 두 가설을 같은 조건으로 채점한다 — 양쪽 다 위상을 실측(`_best_phase`)으로 잡는다.
+ # 예전에는 detect 만 프레임 검출 위상으로 채점했는데, 그 위상은
+ # 참 위상에서 pitch/2 까지 밀릴 수 있어(plan `frame-pitch-consensus-eats-a-row`:
+ # 피치 13.00 에서 2.02 vs 실측 8.12) detect 쪽 균일도만 부당하게 낮게 나왔다.
+ # 채택 로직은 그대로 detect 고정이고 이 점수는 경고 문구에만 쓰이지만, 사람이 읽고
+ # 판단하는 숫자라 편향을 남겨두지 않는다.
+ sample = images[0]
+ detect_score = _grid_uniformity(sample, detect_pitch, _best_phase(sample, detect_pitch))
+ runlen_phase0 = _best_phase(sample, runlen_pitch)
+ runlen_score = _grid_uniformity(sample, runlen_pitch, runlen_phase0)
+ warnings_out.append(
+ f"{tag}: pitch disagreement — detect {dx:.2f}x{dy:.2f} (uniformity {detect_score:.1f}) "
+ f"vs runlen {rx:.2f}x{ry:.2f} ({runlen_score:.1f}); detect kept. "
+ f"large gap usually means the raw was drawn finer than the cell contract — reroll with a "
+ f"block-count hint")
+ return detect_pitch, "detect"
+
+
+PITCH_FAMILY_RATIO = 1.1
+
+
+def resolve_frame_pitch(own: tuple[float, float], consensus: tuple[float, float]) -> tuple[tuple[float, float], bool]:
+ """프레임 자체 검출 피치의 채택 판정 — 합의 '피치 패밀리' 밖이면 오검출 가드.
+
+ 같은 스트립(한 번의 생성) 안에서 참 피치의 프레임 간 편차는 측정 노이즈
+ 수준(수 %)이다 — down_jump frame-0 회귀(합의 13.00 vs 자체 12.50, 4%)는
+ own 이 진실이었고 합의 강제가 눈을 반쪽 냈다 (plan per-frame-pixel-grid).
+ 반면 하모닉/붕괴 오검출은 ×2/×3(또는 ÷2/÷3) 급으로 벗어난다 — up_run
+ frame-2 회귀(합의 7.00x8.86 vs 자체 3.00x3.00, 2026-07-22)는 native
+ 87x162 를 만들었고, 행 일관 축소(conform_row_logical)가 그 캡 배율을 행
+ 전체에 적용해 나머지 프레임을 0.36배 콩알로 붕괴시켰다. 두 회귀 사이
+ 어디에도 참값이 없는 10%(비율 1.1)를 경계로 가른다 — 같은 스트립의 실제
+ 프레임 간 편차는 실측 0.4~2%, 눈반쪽 회귀도 4%였고, 10% 이탈(up_run
+ frame-3 own y 8.00 vs 합의 8.86)조차 native 캡 초과로 행 전체 5% 축소를
+ 유발했다. 이내 = own 채택(측정 진실, 합의 강제 누적오차 없음), 밖 = 합의
+ 채택. 폴백은 호출부가
+ 프레임별 경고로 관측 가능하게 남긴다 (No Silent Fallback).
+
+ 반환: (채택 피치, 패밀리-밖 outlier 여부)."""
+ own_x, own_y = own
+ consensus_x, consensus_y = consensus
+ if min(consensus_x, consensus_y) < 2.0:
+ return own, False
+ ratio = max(own_x / consensus_x, consensus_x / own_x,
+ own_y / consensus_y, consensus_y / own_y)
+ if ratio > PITCH_FAMILY_RATIO:
+ return consensus, True
+ return own, False
+
+
+def _grid_edges(length: int, pitch: float, offset: float) -> list[int]:
+ """소수 피치를 정수 픽셀 경계로 확정한다.
+
+ 두 경우를 가른다. 판정 기준은 body 가 피치의 정수배에 얼마나 가까운가다.
+
+ 1) 정수배에 가까우면(잔차 <= 블록의 1/4) body 를 셀 개수로 **등분**한다. 피치 측정의 미세오차
+ (16.00 을 15.96 으로 재는 것 같은)를 흡수해 격자가 딱 떨어진다.
+ 2) 정수배가 아니면 `lead + i*pitch` 를 직접 곱해 놓고, 남는 자투리는 마지막 셀이 흡수한다.
+ 스프라이트 bbox 는 AA 프린지 때문에 블록의 정수배가 아닐 수 있다 (회귀: 849px =
+ 27.46 블록). 이때 등분하면 셀 폭이 31.44px 로 늘어나 참 블록 30.92px 와 칸마다 0.52px
+ 어긋나고, 오른쪽 끝에서 반 블록이 밀려 스냅 결과의 얼굴이 부서졌다 (v1.56.2 회귀).
+
+ 어느 쪽이든 피치를 누적 덧셈하지 않으므로 부동소수 오차가 쌓이지 않는다.
+ """
+ if pitch <= 1.0:
+ return [0, length]
+ # 선행 부분셀은 스프라이트가 블록 중간에서 시작할 때만 의미가 있다. 컴포넌트는 bbox 로
+ # 잘려 블록 경계에서 시작하므로, 서브픽셀 오프셋(위상 추정 노이즈)은 0 으로 스냅한다.
+ raw_lead = offset % pitch
+ lead = 0 if (raw_lead < pitch * 0.25 or raw_lead > pitch * 0.75) else int(round(raw_lead))
+ body = length - lead
+ if body <= 0:
+ return [0, length]
+ ratio = body / pitch
+ cells = max(1, int(round(ratio)))
+ integral = abs(ratio - cells) <= 0.25
+ edges = [0] if lead == 0 else [0, lead]
+ for i in range(1, cells):
+ e = lead + int(round(body * i / cells if integral else i * pitch))
+ if edges[-1] < e < length:
+ edges.append(e)
+ if edges[-1] != length:
+ edges.append(length)
+ return edges
+
+
+def _grid_phase(image: Image.Image, pitch: int) -> tuple[int, int]:
+ pixels = image.convert("RGBA").load()
+ width, height = image.size
+ col_hits = [0] * pitch
+ row_hits = [0] * pitch
+ for y in range(0, height, 2):
+ for x in range(1, width):
+ a = pixels[x, y]
+ b = pixels[x - 1, y]
+ if abs(a[0] - b[0]) + abs(a[1] - b[1]) + abs(a[2] - b[2]) + abs(a[3] - b[3]) > 96:
+ col_hits[x % pitch] += 1
+ for x in range(0, width, 2):
+ for y in range(1, height):
+ a = pixels[x, y]
+ b = pixels[x, y - 1]
+ if abs(a[0] - b[0]) + abs(a[1] - b[1]) + abs(a[2] - b[2]) + abs(a[3] - b[3]) > 96:
+ row_hits[y % pitch] += 1
+ offset_x = max(range(pitch), key=lambda i: col_hits[i])
+ offset_y = max(range(pitch), key=lambda i: row_hits[i])
+ return offset_x, offset_y
+
+
+def _dominant_block_color(opaque: list, detail_bias: bool = False) -> tuple[int, int, int]:
+ if len(opaque) == 1:
+ return opaque[0][:3]
+
+ def luma(p):
+ return p[0] * 299 + p[1] * 587 + p[2] * 114
+
+ lo = min(opaque, key=luma)
+ hi = max(opaque, key=luma)
+ centroids = [lo[:3], hi[:3]]
+ assign = [0] * len(opaque)
+ # 정수 산술만 (제곱거리·정수합//count) — 순서 무관이라 명시 누적으로 바꿔도
+ # 원본과 값 동일하다. 제너레이터/`sum()` 호출 오버헤드만 제거.
+ for _ in range(3):
+ c00, c01, c02 = centroids[0]
+ c10, c11, c12 = centroids[1]
+ for i, p in enumerate(opaque):
+ p0, p1, p2 = p[0], p[1], p[2]
+ d0 = (p0 - c00) ** 2 + (p1 - c01) ** 2 + (p2 - c02) ** 2
+ d1 = (p0 - c10) ** 2 + (p1 - c11) ** 2 + (p2 - c12) ** 2
+ assign[i] = 0 if d0 <= d1 else 1
+ for cluster in (0, 1):
+ s0 = s1 = s2 = cnt = 0
+ for i, p in enumerate(opaque):
+ if assign[i] == cluster:
+ s0 += p[0]
+ s1 += p[1]
+ s2 += p[2]
+ cnt += 1
+ if cnt:
+ centroids[cluster] = (s0 // cnt, s1 // cnt, s2 // cnt)
+ dominant = 0 if assign.count(0) >= assign.count(1) else 1
+ if detail_bias:
+ # 눈/아웃라인 같은 어두운 소수 디테일 보존: 두 클러스터의 명도차가 크고
+ # 어두운 쪽 점유율이 1/3 이상이면 다수결 대신 어두운 클러스터를 택한다.
+ darker = 0 if luma(centroids[0]) <= luma(centroids[1]) else 1
+ share = assign.count(darker) / len(assign)
+ if (
+ darker != dominant
+ and share >= 0.40
+ and luma(centroids[darker]) < 70000
+ and luma(centroids[1 - darker]) - luma(centroids[darker]) > 50000
+ ):
+ dominant = darker
+ members = [p for i, p in enumerate(opaque) if assign[i] == dominant]
+ return tuple(sum(p[c] for p in members) // len(members) for c in range(3))
+
+
+def _pitch_pair(pitch: float | tuple[float, float]) -> tuple[float, float]:
+ """스칼라 피치는 두 축에 같은 값, 쌍이면 (가로, 세로)."""
+ if isinstance(pitch, (tuple, list)):
+ return float(pitch[0]), float(pitch[1])
+ return float(pitch), float(pitch)
+
+
+def solid_alpha_bbox(image: Image.Image, threshold: int = 128) -> tuple[int, int, int, int] | None:
+ """α>=threshold 픽셀만의 bbox — AA 프린지(반투명 가장자리)를 제외한 실 콘텐츠 범위.
+
+ 픽셀 언페이크 경로의 불투명 판정(α>=128: `grid_snap_downscale`/`binarize_alpha`/
+ `apply_palette`)과 같은 기준이어야 한다. any-alpha `getbbox()` 로 격자를 치면
+ 프린지가 bbox 를 부풀려 `_grid_edges` 의 셀 개수 반올림이 한 칸 늘고, 내용이
+ 프린지뿐인 가장자리 셀이 50% 규칙을 통과해 실루엣 밖 부스러기 픽셀로 굳는다
+ (회귀 2026-07-17: synthetic_fixture_a 150 프레임 중 141 프레임 폭 +1~4px, maintainer 발견 —
+ 회귀 테스트 test_pixel_snap.py::test_fringe_does_not_inflate_grid)."""
+ return image.convert("RGBA").split()[3].point(lambda a: 255 if a >= threshold else 0).getbbox()
+
+
+def tighten_components(images: list[Image.Image]) -> list[Image.Image]:
+ """픽셀 언페이크 스냅 전에 컴포넌트를 실 콘텐츠(solid alpha) bbox 로 타이트하게 조인다.
+
+ `_grid_edges` 의 lead-스냅(위상 < 피치의 1/4 이면 0 으로)은 컴포넌트가 bbox 로
+ 잘려 블록 경계에서 시작한다는 전제다. `component_group_image` 는 사방 4px
+ 패딩을 두르므로, 패딩째 격자를 치면 위상 추정 노이즈가 lead-스냅 문턱 아래로
+ 떨어지는 순간 격자 전체가 패딩만큼 위로 밀린다 — 꼬리에 자투리 셀이 생기고,
+ 경계에서 쪼개진 바닥 블록 + 문턱 근처 알파(~134) 프린지가 유령 픽셀 한 줄로
+ 태어난다 (회귀 2026-07-14: down_idle blink 발밑 1px 돌출, maintainer 발견 —
+ 회귀 테스트 test_pixel_snap.py::test_padded_component_no_ghost_bottom_row).
+ 크롭 기준은 `solid_alpha_bbox` — any-alpha bbox 는 프린지째 격자를 쳐서 같은
+ 유령 픽셀을 사방 가장자리에 만든다 (해당 docstring 참조). 전부 프린지인
+ 퇴화 컴포넌트만 any-alpha bbox 로 폴백한다 (어차피 binarize 에서 빈 프레임)."""
+ return [
+ component.crop(box)
+ if (box := (solid_alpha_bbox(component) or component.getbbox())) else component
+ for component in images
+ ]
+
+
+
+def _boundary_mass(image: Image.Image) -> tuple[list[int], list[int]]:
+ """축별 색/알파 경계 질량 프로파일 — 절단선 스냅의 증거."""
+ px = image.load()
+ w, h = image.size
+ col = [0] * max(1, w)
+ row = [0] * max(1, h)
+ for y in range(h):
+ for x in range(w - 1):
+ a, b = px[x, y], px[x + 1, y]
+ if (a[3] >= 128) != (b[3] >= 128) or (
+ a[3] >= 128 and b[3] >= 128
+ and abs(a[0]-b[0]) + abs(a[1]-b[1]) + abs(a[2]-b[2]) > 48
+ ):
+ col[x + 1] += 1
+ for x in range(w):
+ for y in range(h - 1):
+ a, b = px[x, y], px[x, y + 1]
+ if (a[3] >= 128) != (b[3] >= 128) or (
+ a[3] >= 128 and b[3] >= 128
+ and abs(a[0]-b[0]) + abs(a[1]-b[1]) + abs(a[2]-b[2]) > 48
+ ):
+ row[y + 1] += 1
+ return col, row
+
+
+def refine_edges_to_boundaries(component: Image.Image, x_edges: list[int], y_edges: list[int],
+ pitch: tuple[float, float]) -> tuple[list[int], list[int]]:
+ """등간격 절단선을 실제 블록 경계로 스냅 (maintainer 확정 2026-07-18).
+
+ AI 블록은 국소적으로 흔들려서 등간격 자름은 경계 조각을 옆 칸으로 흘린다
+ (회귀: 눈 아래 유령 픽셀, 발밑 1픽셀 — 같은 뿌리). 각 내부 절단선을
+ ±pitch/3 창 안의 색경계 질량 최대 위치로 옮긴다. 질량이 무의미하면(평탄 영역)
+ 등간격 위치 유지. 단조 증가·최소 칸폭 불변식 강제 — 결정론.
+
+ **슬리버 가드 (maintainer 2026-07-24, plan backbone-sliver-guard)**: 최소 칸폭은
+ 절대 2px 가 아니라 **피치 비례(≥0.6×pitch)** 다. 절대 2px 는 피치 ~13px 소재에서
+ 0.15셀짜리 슬리버 쌍(0.4/1.6)을 허용했고, ~5px 간격의 경계 쌍이 인접 절단선
+ 둘을 서로 향해 당기면 출력 두 행이 소스의 거의 같은 밴드를 이중 샘플링했다 —
+ v8 down_jump 회귀 두 건이 이 한 기전이다: f2 턱 늘어남(턱 라인 세로 복제),
+ f0 눈물점(50/50 걸침 셀의 지배색 플립). 스냅은 창(±pitch/3) 안에서 계속 경계를
+ 따르되, 이웃과 0.6×pitch 미만으로는 절대 붙지 못한다 — 전역 격자(머리끈
+ 일관성)는 그대로다."""
+ col, row = _boundary_mass(component)
+
+ def snap(edges: list[int], mass: list[int], pitch_axis: float, limit: int) -> list[int]:
+ if len(edges) < 3:
+ return edges
+ out = list(edges)
+ window = max(1, int(pitch_axis / 3))
+ min_gap = max(2, int(round(pitch_axis * 0.6)))
+ for i in range(1, len(out) - 1):
+ e = edges[i]
+ lo = max(out[i - 1] + min_gap, e - window)
+ hi = min(edges[i + 1] - min_gap, e + window, limit - 1)
+ if hi < lo:
+ continue
+ best = max(range(lo, hi + 1), key=lambda pos: (mass[pos] if pos < len(mass) else 0))
+ if (mass[best] if best < len(mass) else 0) > 0:
+ out[i] = best
+ # 단조/최소폭 재확인 (스냅 순서상 위반 불가지만 방어적 단정)
+ for i in range(1, len(out)):
+ if out[i] <= out[i - 1]:
+ return list(edges) # 위반 시 통째로 등간격 유지 (관측 불필요 — 발생 불가 경로)
+ return out
+
+ return (snap(x_edges, col, pitch[0], component.width),
+ snap(y_edges, row, pitch[1], component.height))
+
+
+def snap_by_edges(image: Image.Image, x_edges: list[int], y_edges: list[int],
+ detail_bias: bool = False) -> Image.Image:
+ """명시 절단선으로 블록 샘플링 (grid_snap_downscale 의 코어 — 비등간격 지원)."""
+ source = image.convert("RGBA")
+ pixels = source.load()
+ output = Image.new("RGBA", (len(x_edges) - 1, len(y_edges) - 1), (0, 0, 0, 0))
+ out = output.load()
+ for oy in range(len(y_edges) - 1):
+ for ox in range(len(x_edges) - 1):
+ block = [
+ pixels[x, y]
+ for y in range(y_edges[oy], y_edges[oy + 1])
+ for x in range(x_edges[ox], x_edges[ox + 1])
+ ]
+ opaque = [p for p in block if p[3] >= 128]
+ if len(opaque) * 2 < len(block):
+ continue
+ color = _dominant_block_color(opaque, detail_bias)
+ out[ox, oy] = (color[0], color[1], color[2], 255)
+ return output
+
+
+def grid_snap_downscale(
+ image: Image.Image,
+ pitch: float | tuple[float, float],
+ detail_bias: bool = False,
+ phase: tuple[float, float] | None = None,
+) -> Image.Image:
+ """pitch/phase 는 소수를 받는다 — 격자선만 정수 픽셀로 확정한다 (`_grid_edges`).
+
+ pitch 는 스칼라 또는 (가로, 세로) 쌍. 축마다 블록 크기가 다른 생성물이 있어서
+ `detect_pixel_grid` 가 축별 피치를 낸다. 정수 pitch + 정수 phase 를 주면 예전과 같은
+ 경계가 나온다 (골든 추출 회귀 없음).
+ """
+ source = image.convert("RGBA")
+ width, height = source.size
+ pitch_x, pitch_y = _pitch_pair(pitch)
+ if phase is None:
+ offset_x, offset_y = _grid_phase(source, max(2, int(round(pitch_x))))
+ else:
+ offset_x, offset_y = phase
+ x_edges = _grid_edges(width, pitch_x, offset_x)
+ y_edges = _grid_edges(height, pitch_y, offset_y)
+ pixels = source.load()
+ output = Image.new("RGBA", (len(x_edges) - 1, len(y_edges) - 1), (0, 0, 0, 0))
+ out = output.load()
+ for oy in range(len(y_edges) - 1):
+ for ox in range(len(x_edges) - 1):
+ block = [
+ pixels[x, y]
+ for y in range(y_edges[oy], y_edges[oy + 1])
+ for x in range(x_edges[ox], x_edges[ox + 1])
+ ]
+ opaque = [p for p in block if p[3] >= 128]
+ if len(opaque) * 2 < len(block):
+ continue
+ color = _dominant_block_color(opaque, detail_bias)
+ out[ox, oy] = (color[0], color[1], color[2], 255)
+ return output
+
+
+def binarize_alpha(image: Image.Image) -> Image.Image:
+ pixels = image.load()
+ for y in range(image.height):
+ for x in range(image.width):
+ p = pixels[x, y]
+ if p[3] < 128:
+ pixels[x, y] = (0, 0, 0, 0)
+ elif p[3] != 255:
+ pixels[x, y] = (p[0], p[1], p[2], 255)
+ return image
+
+
+def conform_row_logical(images: list, logical_width: int, logical_height: int, detail_bias: bool = True) -> list:
+ # 행(row) 단위 크기 통일: 축소 배율을 행에서 가장 큰 프레임 기준 하나로 계산해
+ # 전 프레임에 동일 적용한다(프레임 간 크기 호흡 제거). 입력은 이미 격자 스냅된
+ # 논리 해상도 프레임들이다.
+ snapped = []
+ for image in images:
+ bbox = image.getbbox()
+ snapped.append(image.crop(bbox) if bbox else image)
+ max_width = max(s.width for s in snapped)
+ max_height = max(s.height for s in snapped)
+ if max_width > logical_width or max_height > logical_height:
+ scale = min(logical_width / max_width, logical_height / max_height)
+ conformed = []
+ for sprite in snapped:
+ resized = _kcentroid_downscale(
+ sprite,
+ max(1, round(sprite.width * scale)),
+ max(1, round(sprite.height * scale)),
+ detail_bias,
+ )
+ bbox = resized.getbbox()
+ conformed.append(resized.crop(bbox) if bbox else resized)
+ snapped = conformed
+ return [binarize_alpha(s) for s in snapped]
+
+
+def register_row_frames(frames: list, slack_x: int = 8, slack_y: int = 3) -> list:
+ # 프레임 간 정합: 로코모션에서 다리는 원래 움직이므로, 안정 부위(상체 65%)의
+ # 알파 겹침을 최대화하는 정수 시프트를 프레임마다 찾아 공통 캔버스에 앉힌다.
+ # 이후 배치는 행 공통(union) 기준 1회 계산 → 프레임 간 몸통 흔들림 제거.
+ cropped = []
+ for frame in frames:
+ bbox = frame.getbbox()
+ cropped.append(frame.crop(bbox) if bbox else frame)
+ canvas_width = max(f.width for f in cropped) + slack_x * 2
+ canvas_height = max(f.height for f in cropped) + slack_y * 2
+
+ def base_pos(f):
+ return ((canvas_width - f.width) // 2, canvas_height - slack_y - f.height)
+
+ reference = cropped[0]
+ ref_x, ref_y = base_pos(reference)
+ upper_limit = ref_y + int(reference.height * 0.65)
+ ref_pixels = reference.load()
+ ref_mask = set()
+ for y in range(reference.height):
+ if ref_y + y >= upper_limit:
+ break
+ for x in range(reference.width):
+ if ref_pixels[x, y][3] >= 128:
+ ref_mask.add((ref_x + x, ref_y + y))
+
+ registered = []
+ for index, frame in enumerate(cropped):
+ base_x, base_y = base_pos(frame)
+ best_dx, best_dy = 0, 0
+ if index > 0 and ref_mask:
+ pixels = frame.load()
+ points = [
+ (x, y)
+ for y in range(frame.height)
+ for x in range(frame.width)
+ if pixels[x, y][3] >= 128 and base_y + y < upper_limit
+ ]
+ best_score = -1
+ for dy in range(-slack_y, slack_y + 1):
+ for dx in range(-slack_x, slack_x + 1):
+ score = sum(1 for (x, y) in points if (base_x + x + dx, base_y + y + dy) in ref_mask)
+ if score > best_score:
+ best_score = score
+ best_dx, best_dy = dx, dy
+ canvas = Image.new("RGBA", (canvas_width, canvas_height), (0, 0, 0, 0))
+ canvas.alpha_composite(frame, (min(max(0, base_x + best_dx), canvas_width - frame.width), min(max(0, base_y + best_dy), canvas_height - frame.height)))
+ registered.append(canvas)
+ # 공통 union bbox 로 크롭 — 슬랙 여백이 셀보다 커져 배치 시 하단(발)이
+ # 잘리는 것을 방지. 동일 박스 크롭이라 프레임 간 정합은 유지된다.
+ union = Image.new("RGBA", (canvas_width, canvas_height), (0, 0, 0, 0))
+ for canvas in registered:
+ union.alpha_composite(canvas)
+ bbox = union.getbbox()
+ if bbox is not None:
+ registered = [canvas.crop(bbox) for canvas in registered]
+ return registered
+
+
+def row_placement(frames: list, cell_width: int, cell_height: int, safe_margin_y: int, scale: int, fit: dict[str, Any]) -> tuple[int, int]:
+ # 가로 배치 오프셋은 행 union 기준으로 1회 계산해 전 프레임에 동일 적용한다
+ # (플립 대칭·수평 안정). 세로는 place_row_frame 이 프레임별로 접지한다.
+ union = Image.new("RGBA", frames[0].size, (0, 0, 0, 0))
+ for frame in frames:
+ union.alpha_composite(frame)
+ sprite = union.resize((union.width * scale, union.height * scale), Image.Resampling.NEAREST)
+ align_x = str(fit.get("align_x", "foot-centroid")).lower()
+ if align_x == "foot-centroid":
+ left = round(cell_width / 2.0 - _alpha_centroid_x(sprite, 0.2))
+ elif align_x == "centroid":
+ left = round(cell_width / 2.0 - _alpha_centroid_x(sprite))
+ elif align_x == "alpha-centroid":
+ # union 기준 값 — 실제 배치는 _run 이 프레임별로 _alpha_centroid_row_left
+ # 를 쓴다 (per-frame 이 이 모드의 핵심).
+ left = round(cell_width / 2.0 - _alpha_centroid_x(sprite, 1.0, ALPHA_CENTROID_MIN_ALPHA))
+ else:
+ left = (cell_width - sprite.width) // 2
+ left = max(0, min(cell_width - sprite.width, left))
+ left -= left % scale
+ bbox = sprite.getbbox()
+ content_bottom = bbox[3] if bbox else sprite.height
+ top = max(0, cell_height - safe_margin_y - content_bottom)
+ return left, top
+
+
+def place_row_frame(frame: Image.Image, cell_width: int, cell_height: int, scale: int, left: int, top: int, safe_margin_y: int | None = None, ground: bool = True) -> Image.Image:
+ # 2026-07-04 (maintainer): 세로는 프레임마다 콘텐츠 바닥을 공유 기준선에 접지한다 —
+ # 행 union 공동 top 만 쓰면 소스 스트립의 상하 요동이 이동으로 남아 프레임 간
+ # "무게감"(발밑 높이)이 들쭉해진다. perfectpixel-studio 의 프레임별 알파 가중
+ # 정렬과 같은 원리의 세로축 버전. 점프 같은 의도적 오프셋은 fit.ground_frames
+ # = false 로 끌 수 있다 (row_placement 의 공동 top 사용).
+ target = Image.new("RGBA", (cell_width, cell_height), (0, 0, 0, 0))
+ if frame.getbbox() is None:
+ return target
+ sprite = frame.resize((frame.width * scale, frame.height * scale), Image.Resampling.NEAREST)
+ frame_top = top
+ if ground and safe_margin_y is not None:
+ bbox = sprite.getbbox()
+ content_bottom = bbox[3] if bbox else sprite.height
+ frame_top = max(0, cell_height - safe_margin_y - content_bottom)
+ target.alpha_composite(sprite, (left, frame_top))
+ return target
+
+
+
+PALETTE_LOCK = "palette.lock.json"
+
+
+def load_pinned_palette(run_dir: Path) -> list | None:
+ """런에 고정된 공유 팔레트 (없으면 None). 팔레트 피닝 (maintainer 확정 2026-07-18):
+ 공유 팔레트가 추출 배치 구성에 따라 재계산되며 확정 행 픽셀을 흔들던 드리프트
+ (회귀 2026-07-17 down_idle, 3회)를 원천 차단한다 — 배치가 어떻게 바뀌어도
+ 팔레트는 이 파일 하나가 진실이다. 재산출은 `--repalette` 명시 시에만."""
+ path = run_dir / PALETTE_LOCK
+ if not path.is_file():
+ return None
+ try:
+ data = json.loads(path.read_text(encoding="utf-8"))
+ colors = [tuple(int(v) for v in c) for c in data["colors"]]
+ except (ValueError, KeyError, TypeError) as exc:
+ raise SystemExit(f"corrupt {PALETTE_LOCK}: {exc} — fix or delete it explicitly")
+ if not colors:
+ raise SystemExit(f"{PALETTE_LOCK} has no colors — fix or delete it explicitly")
+ return colors
+
+
+def write_pinned_palette(run_dir: Path, palette: list, source: str) -> None:
+ atomic_write_text(run_dir / PALETTE_LOCK, json.dumps({
+ "kind": "sprite-gen-palette-lock",
+ "source": source,
+ "colors": [list(c) for c in palette],
+ }, ensure_ascii=False, indent=2) + "\n")
+
+
+def build_shared_palette(frames: list, size: int) -> list:
+ colors: list = []
+ for frame in frames:
+ pixels = frame.load()
+ for y in range(frame.height):
+ for x in range(frame.width):
+ p = pixels[x, y]
+ if p[3] >= 128:
+ colors.append((p[0], p[1], p[2]))
+ if not colors:
+ return []
+
+ def box_widest(box):
+ best_range = -1
+ best_channel = 0
+ for channel in range(3):
+ lo = min(c[channel] for c in box)
+ hi = max(c[channel] for c in box)
+ if hi - lo > best_range:
+ best_range = hi - lo
+ best_channel = channel
+ return best_range, best_channel
+
+ boxes = [colors]
+ while len(boxes) < size:
+ best = None
+ for index, box in enumerate(boxes):
+ if len(box) < 2:
+ continue
+ spread, channel = box_widest(box)
+ if spread > 0 and (best is None or spread > best[0]):
+ best = (spread, channel, index)
+ if best is None:
+ break
+ _, channel, index = best
+ box = boxes.pop(index)
+ box.sort(key=lambda c: c[channel])
+ mid = len(box) // 2
+ boxes.append(box[:mid])
+ boxes.append(box[mid:])
+ return [
+ tuple(sum(c[channel] for c in box) // len(box) for channel in range(3))
+ for box in boxes
+ if box
+ ]
+
+
+def apply_palette(image: Image.Image, palette: list) -> Image.Image:
+ if not palette:
+ return image
+ pixels = image.load()
+ cache: dict = {}
+ for y in range(image.height):
+ for x in range(image.width):
+ p = pixels[x, y]
+ if p[3] < 128:
+ pixels[x, y] = (0, 0, 0, 0)
+ continue
+ key = (p[0], p[1], p[2])
+ if key not in cache:
+ cache[key] = min(
+ palette,
+ key=lambda c: (c[0] - key[0]) ** 2 + (c[1] - key[1]) ** 2 + (c[2] - key[2]) ** 2,
+ )
+ color = cache[key]
+ pixels[x, y] = (color[0], color[1], color[2], 255)
+ return image
+
+
+def enforce_outline(image: Image.Image, strength: float = 0.62) -> Image.Image:
+ # 균일 오토 아웃라인: 실루엣 경계(투명 인접) 픽셀을 자기 색 기준으로 어둡게.
+ # 다운스케일에서 얇은 원본 외곽선이 패치워크로 살아남는 문제를 결정론으로 보정 —
+ # 모든 프레임/행에서 1 논리픽셀 외곽선이 보장돼 프레임 간 플리커도 줄인다.
+ pixels = image.load()
+ width, height = image.size
+ boundary = []
+ for y in range(height):
+ for x in range(width):
+ if pixels[x, y][3] < 128:
+ continue
+ for nx, ny in ((x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)):
+ if nx < 0 or ny < 0 or nx >= width or ny >= height or pixels[nx, ny][3] < 128:
+ boundary.append((x, y))
+ break
+ keep = 1.0 - strength
+ for x, y in boundary:
+ r, g, b, _a = pixels[x, y]
+ pixels[x, y] = (int(r * keep), int(g * keep), int(b * keep), 255)
+ return image
+
+
+def fit_pixel_unfake(logical: Image.Image, cell_width: int, cell_height: int, safe_margin_x: int, safe_margin_y: int, scale: int, fit: dict[str, Any]) -> Image.Image:
+ target = Image.new("RGBA", (cell_width, cell_height), (0, 0, 0, 0))
+ bbox = logical.getbbox()
+ if bbox is None:
+ return target
+ # 콘텐츠 bbox 로 먼저 크롭 — 로지컬 셀의 투명 패딩째 바닥에 붙이면 패딩만큼
+ # 프레임마다 발이 떠서 바닥선("무게감")이 흔들린다 (maintainer 2026-07-04).
+ logical = logical.crop(bbox)
+ sprite = logical.resize((logical.width * scale, logical.height * scale), Image.Resampling.NEAREST)
+ align_x = str(fit.get("align_x", "foot-centroid")).lower()
+ align_y = str(fit.get("align_y", "bottom")).lower()
+ if align_x == "foot-centroid":
+ left = round(cell_width / 2.0 - _alpha_centroid_x(sprite, 0.2))
+ elif align_x == "centroid":
+ left = round(cell_width / 2.0 - _alpha_centroid_x(sprite))
+ elif align_x == "alpha-centroid":
+ left = round(cell_width / 2.0 - _alpha_centroid_x(sprite, 1.0, ALPHA_CENTROID_MIN_ALPHA))
+ else:
+ left = (cell_width - sprite.width) // 2
+ left = max(0, min(cell_width - sprite.width, left))
+ left -= left % scale # 논리 픽셀 격자에 스냅(짝수 배치로 flip 대칭 보존)
+ if align_y == "bottom":
+ top = max(0, cell_height - safe_margin_y - sprite.height)
+ else:
+ top = (cell_height - sprite.height) // 2
+ target.alpha_composite(sprite, (left, top))
+ return target
+
+
+def fit_component_to_bbox(component: Image.Image, cell_width: int, cell_height: int,
+ bbox: tuple[int, int, int, int], scale: int = 1,
+ ) -> tuple[Image.Image, dict[str, float] | None]:
+ """원본 컴포넌트를 픽셀 언페이크 프레임의 콘텐츠 bbox(×scale) 풋프린트에 앉힌다.
+
+ plain/orig 쌍둥이용: 픽셀 언페이크 결과와 같은 크기·같은 자리에 원본 화질 스프라이트를
+ 두어, 큐레이터의 픽셀 언페이크 토글이 크기 변화 없이 픽셀 처리 품질만 비교하게 한다
+ (contain 맞춤 + 하단 정렬 + 가로 중앙 — bbox 종횡비와의 오차는 격자 반올림 수준).
+
+ 두 번째 반환값은 컴포넌트 좌표 → 쌍둥이 좌표 매핑 {crop_x, crop_y, ratio, left, top}
+ (twin = (raw - crop) * ratio + offset) — 검출 격자선을 쌍둥이 위에 겹칠 때 쓴다."""
+ target = Image.new("RGBA", (cell_width * scale, cell_height * scale), (0, 0, 0, 0))
+ src_bbox = component.getbbox()
+ if src_bbox is None:
+ return target, None
+ src = component.crop(src_bbox)
+ x0, y0, x1, y1 = (v * scale for v in bbox)
+ box_w, box_h = max(1, x1 - x0), max(1, y1 - y0)
+ ratio = min(box_w / src.width, box_h / src.height)
+ tw, th = max(1, round(src.width * ratio)), max(1, round(src.height * ratio))
+ resized = src.resize((tw, th), Image.Resampling.LANCZOS)
+ left = x0 + (box_w - tw) // 2
+ top = y1 - th
+ target.alpha_composite(resized, (left, top))
+ mapping = {"crop_x": float(src_bbox[0]), "crop_y": float(src_bbox[1]),
+ "ratio": ratio, "left": float(left), "top": float(top)}
+ return target, mapping
+
+
+def extract_component_images(strip: Image.Image, frame_count: int) -> list[Image.Image] | None:
+ components = connected_components(strip)
+ if not components:
+ return None
+ largest_area = max(component["area"] for component in components)
+ seed_threshold = max(120, largest_area * 0.20)
+ seeds = [component for component in components if component["area"] >= seed_threshold]
+ if len(seeds) < frame_count:
+ seeds = sorted(components, key=lambda component: component["area"], reverse=True)[:frame_count]
+ if len(seeds) < frame_count:
+ return None
+
+ seeds = sorted(
+ sorted(seeds, key=lambda component: component["area"], reverse=True)[:frame_count],
+ key=lambda component: component["center_x"],
+ )
+ seed_ids = {id(seed) for seed in seeds}
+ groups: list[list[dict[str, Any]]] = [[seed] for seed in seeds]
+ noise_threshold = max(12, largest_area * 0.002)
+
+ dropped = 0
+ for component in components:
+ if id(component) in seed_ids or component["area"] < noise_threshold:
+ continue
+ nearest_index = min(
+ range(len(seeds)),
+ key=lambda index: abs(seeds[index]["center_x"] - component["center_x"]),
+ )
+ # x 거리로만 붙이면 멀리 떨어진 파편(크로마 잔여물·분리된 이펙트)까지
+ # 병합돼 bbox 가 늘어나고 프레임 바닥선/크롭이 흔들린다 (maintainer 2026-07-04
+ # "이상한 거 딸려나오게 하지 마"). 시드 bbox 를 살짝 넓힌 근접 영역과
+ # 겹치는 위성만 병합하고, 나머지는 관측 가능하게 버린다.
+ sx0, sy0, sx1, sy1 = seeds[nearest_index]["bbox"]
+ pad_x = max(6, round((sx1 - sx0) * 0.15))
+ pad_y = max(6, round((sy1 - sy0) * 0.15))
+ cx0, cy0, cx1, cy1 = component["bbox"]
+ if cx0 < sx1 + pad_x and cx1 > sx0 - pad_x and cy0 < sy1 + pad_y and cy1 > sy0 - pad_y:
+ groups[nearest_index].append(component)
+ else:
+ dropped += 1
+ if dropped:
+ print(f"[extract] dropped {dropped} stray satellite component(s) outside seed proximity", file=sys.stderr)
+
+ return [component_group_image(strip, group) for group in groups]
+
+
+def extract_component_frames(strip: Image.Image, frame_count: int, cell_width: int, cell_height: int, safe_margin_x: int, safe_margin_y: int, fit: dict[str, Any] | None = None) -> list[Image.Image] | None:
+ images = extract_component_images(strip, frame_count)
+ if images is None:
+ return None
+ return [fit_to_cell(image, cell_width, cell_height, safe_margin_x, safe_margin_y, fit) for image in images]
+
+
+def extract_slot_frames(strip: Image.Image, frame_count: int, cell_width: int, cell_height: int, safe_margin_x: int, safe_margin_y: int, fit: dict[str, Any] | None = None) -> list[Image.Image]:
+ slot_width = strip.width / frame_count
+ frames = []
+ for index in range(frame_count):
+ left = round(index * slot_width)
+ right = round((index + 1) * slot_width)
+ frames.append(fit_to_cell(strip.crop((left, 0, right, strip.height)), cell_width, cell_height, safe_margin_x, safe_margin_y, fit))
+ return frames
+
+
+def chroma_adjacent_count(image: Image.Image, chroma_key: tuple[int, int, int], threshold: float) -> int:
+ count = 0
+ data = image.convert("RGBA").tobytes()
+ for index in range(0, len(data), 4):
+ red, green, blue, alpha = data[index : index + 4]
+ if alpha > 16 and color_distance((red, green, blue), chroma_key) <= threshold:
+ count += 1
+ return count
+
+
+def inspect_frames(frames: list[Image.Image], chroma_key: tuple[int, int, int], args: argparse.Namespace) -> tuple[list[str], list[str], list[dict[str, Any]]]:
+ errors: list[str] = []
+ warnings: list[str] = []
+ records: list[dict[str, Any]] = []
+ areas = [alpha_nonzero_count(frame) for frame in frames]
+ frame_median = median(areas) if areas else 0
+ for index, frame in enumerate(frames):
+ nontransparent = areas[index]
+ edge = edge_alpha_count(frame, args.edge_margin)
+ adjacent = chroma_adjacent_count(frame, chroma_key, args.chroma_adjacent_threshold)
+ bbox = frame.getbbox()
+ records.append(
+ {
+ "index": index,
+ "nontransparent_pixels": nontransparent,
+ "bbox": list(bbox) if bbox else None,
+ "edge_pixels": edge,
+ "chroma_adjacent_pixels": adjacent,
+ }
+ )
+ if nontransparent < args.min_used_pixels:
+ errors.append(sparse_frame_error(index, nontransparent, args.min_used_pixels,
+ getattr(args, "_subject_kind", SUBJECT_DEFAULT)))
+ if edge > args.edge_pixel_threshold:
+ warnings.append(f"frame {index:02d} has {edge} non-transparent edge pixels")
+ if adjacent > args.chroma_adjacent_pixel_threshold:
+ errors.append(f"frame {index:02d} has {adjacent} chroma-adjacent pixels")
+ if frame_median and nontransparent < frame_median * args.small_outlier_ratio:
+ warnings.append(f"frame {index:02d} is much smaller than median ({nontransparent} vs {frame_median:.0f})")
+ if frame_median and nontransparent > frame_median * args.large_outlier_ratio:
+ warnings.append(f"frame {index:02d} is much larger than median ({nontransparent} vs {frame_median:.0f})")
+ return errors, warnings, records
+
+
+def _build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--run-dir", required=True, type=Path)
+ parser.add_argument("--states", default="all")
+ parser.add_argument("--key-threshold", type=float, default=96.0)
+ parser.add_argument("--fringe-key-threshold", type=float, default=180.0)
+ parser.add_argument("--fringe-delta", type=float, default=18.0)
+ parser.add_argument(
+ "--fringe-unmix-reach",
+ type=int,
+ default=None,
+ help="peel depth for soft-alpha unmix of out-of-band key blends; "
+ "default from request chroma.unmix_reach, else 4; 0 disables",
+ )
+ parser.add_argument(
+ "--spill-max-fraction",
+ type=float,
+ default=None,
+ help="max size of a trapped key-spill cluster to despill, as a fraction "
+ "of subject pixels; default from request chroma.spill_max_fraction, "
+ "else 0.005; 0 disables",
+ )
+ parser.add_argument(
+ "--chroma-mode",
+ choices=("rgb", "ycbcr"),
+ default=None,
+ help="background matting path; overrides request chroma.mode "
+ "(ycbcr = chrominance-plane matting with border-mode key detection, "
+ "despill and flood fill — perfectpixel-studio port; default rgb)",
+ )
+ parser.add_argument(
+ "--segmentation",
+ choices=("components", "projection"),
+ default=None,
+ help="frame separation mode; overrides request fit.segmentation "
+ "(projection = projection-profile + DP optimal cut for fused poses, "
+ "default components)",
+ )
+ parser.add_argument("--allow-slot-fallback", action="store_true")
+ parser.add_argument("--repalette", action="store_true",
+ help="고정 팔레트(palette.lock.json)를 무시하고 재산출·재고정")
+ # Default is None on purpose: the floor's SSoT is the request's subject
+ # resolution-aware profile (sprite_gen.spec.subject); the CLI is an
+ # explicit override only, same rule as the chroma tunables below.
+ parser.add_argument("--min-used-pixels", type=int, default=None)
+ parser.add_argument("--edge-margin", type=int, default=2)
+ parser.add_argument("--edge-pixel-threshold", type=int, default=24)
+ parser.add_argument("--chroma-adjacent-threshold", type=float, default=150.0)
+ parser.add_argument("--chroma-adjacent-pixel-threshold", type=int, default=120)
+ parser.add_argument("--small-outlier-ratio", type=float, default=0.35)
+ parser.add_argument("--large-outlier-ratio", type=float, default=2.75)
+ return parser
+
+
+def _namespace_from_kwargs(**kwargs: object) -> argparse.Namespace:
+ parser = _build_parser()
+ values: dict[str, object] = {}
+ remaining = dict(kwargs)
+ for action in parser._actions:
+ if action.dest == "help":
+ continue
+ default = [] if action.nargs == "*" else action.default
+ if default is argparse.SUPPRESS:
+ default = None
+ value = remaining.pop(action.dest, default)
+ if getattr(action, "required", False) and value is None:
+ raise TypeError(f"missing required argument: {action.dest}")
+ values[action.dest] = value
+ if remaining:
+ names = ", ".join(sorted(remaining))
+ raise TypeError(f"unexpected keyword argument(s): {names}")
+ return argparse.Namespace(**values)
+def _load_validated(path: Path, name: str, require) -> dict:
+ """Read a canonical run JSON record, FAILING LOUD on any corruption — unreadable,
+ unparseable, or a broken schema — instead of silently treating it as absent/empty. EVERY
+ reader (extract's subset seeding + commit, inspect / the correction loop) goes through here:
+ silently reading a `{}`, a missing-field, or a wrong-`ok` record as empty would drop a
+ still-unresolved failure (extract-failure.json) or a real generation (frames-manifest.json)
+ from view, so a corrupt record would read as "all clear" (No Silent Fallback / Consistency).
+ Returns {} ONLY when the file is genuinely absent — an existing-but-broken record never reads
+ as empty. `require` enforces the kind-specific contract on top of the shared shape."""
+ if not path.is_file():
+ return {}
+ try:
+ data = json.loads(path.read_text(encoding="utf-8"))
+ except (OSError, ValueError) as exc:
+ raise SystemExit(
+ f"corrupt {name} {path}: {exc}\n"
+ f" refusing to treat a canonical run record as empty; inspect/repair or delete it deliberately."
+ )
+ if not isinstance(data, dict):
+ raise SystemExit(f"corrupt {name} {path}: expected a JSON object, got {type(data).__name__}")
+ for key in ("errors", "warnings", "rows"):
+ if not isinstance(data.get(key), list): # required list, not merely list-if-present
+ raise SystemExit(f"corrupt {name} {path}: '{key}' must be a list")
+ for key in ("errors", "warnings"):
+ for item in data[key]:
+ if not isinstance(item, str) or not item.strip(): # e.g. null / "" slipping through
+ raise SystemExit(f"corrupt {name} {path}: every '{key}' entry must be a non-empty string")
+ for row in data["rows"]:
+ if not isinstance(row, dict) or not isinstance(row.get("state"), str) or not row.get("state"):
+ raise SystemExit(f"corrupt {name} {path}: every 'rows' entry needs a non-empty string 'state'")
+ require(data, path, name)
+ return data
+
+
+def _require_complete_manifest(data: dict, path: Path, name: str) -> None:
+ if data.get("ok") is not True:
+ raise SystemExit(f"corrupt {name} {path}: a published frames manifest must have 'ok': true")
+
+
+def _require_failure_evidence(data: dict, path: Path, name: str) -> None:
+ if data.get("ok") is not False:
+ raise SystemExit(f"corrupt {name} {path}: failure evidence must have 'ok': false")
+ if not data["errors"]:
+ raise SystemExit(f"corrupt {name} {path}: failure evidence must have a non-empty 'errors' list")
+ # every diagnostic is a per-state message (`<state>: ...`) — the correction loop keys on the
+ # state prefix, so a prefix-less or empty entry is a silently-lost failure (e.g. a `null`
+ # entry would be dropped by the per-state merge and delete the whole record on next success).
+ for key in ("errors", "warnings"):
+ for item in data[key]:
+ if ":" not in item or not item.split(":", 1)[0].strip():
+ raise SystemExit(f"corrupt {name} {path}: every '{key}' entry must be state-scoped ('<state>: ...'), got {item!r}")
+
+
+def load_frames_manifest(path: Path) -> dict:
+ """Read a published frames-manifest.json (a COMPLETE generation), failing loud on corruption
+ or a broken schema (`ok`:true, required `rows`/`errors`/`warnings` lists, rows carry a
+ `state`). Returns {} only when genuinely absent (No Silent Fallback — see _load_validated)."""
+ return _load_validated(path, "frames manifest", _require_complete_manifest)
+
+
+def load_failure_evidence(path: Path) -> dict:
+ """Read extract-failure.json (the run's unresolved per-state failures), failing loud on
+ corruption or a broken schema (`ok`:false, non-empty state-scoped `errors`, `warnings`/`rows`
+ lists). Returns {} only when genuinely absent (No Silent Fallback — see _load_validated)."""
+ return _load_validated(path, "failure evidence", _require_failure_evidence)
+
+
+def _require_generation_consistency(run_dir: Path, manifest: dict, name: str,
+ allow_pending_states: bool = False) -> None:
+ """Beyond JSON schema, a published generation must AGREE with the physical frame tree and the
+ request. Frames and the manifest are published together as one transaction, so a disagreement
+ means corruption/staleness: fail loud rather than let a consumer build output from stale,
+ partial, or orphan frames (Consistency / No Silent Fallback). Checks:
+ - every request state has exactly one row (no missing state, no duplicate row);
+ - no physical frame state dir is an orphan the manifest omits;
+ - every row's canonical frames exist on disk.
+
+ `allow_pending_states` (관찰자 전용 — 큐레이션 뷰): 아직 생성되지 않은 요청 상태
+ (manifest 행도 없고 물리 프레임도 없음)는 '진행 중'으로 허용한다. 부분 추출이
+ 정식 흐름(단계별 생성·증분 추출)이 된 뒤 뷰가 미생성 상태 때문에 죽으면 안 된다.
+ 소비자(compose/export 등)는 기본값(False)으로 완결 세대를 계속 강제한다."""
+ frames_root = run_dir / "frames"
+ try:
+ request = load_request(run_dir)
+ except (OSError, ValueError) as exc:
+ raise SystemExit(f"cannot read sprite-request.json for {run_dir}: {exc}")
+ request_states = set(request.get("states", {}))
+ row_states = [row["state"] for row in manifest["rows"]]
+ dupes = sorted({s for s in row_states if row_states.count(s) > 1})
+ if dupes:
+ raise SystemExit(f"corrupt {name} {run_dir}: duplicate manifest rows for state(s) {dupes}")
+ row_state_set = set(row_states)
+ # request states and manifest row states must match EXACTLY, both directions: a missing row is
+ # an incomplete generation, an extra row is a stale/unknown state some consumers would render
+ # while serve (request-driven) hides it — a per-consumer divergence.
+ missing = sorted(request_states - row_state_set)
+ if missing:
+ pending_only = [
+ m for m in missing
+ if not (run_dir / frames_dir_rel(request, m)).is_dir()
+ ]
+ if not (allow_pending_states and pending_only == missing):
+ raise SystemExit(f"corrupt {name} {run_dir}: manifest missing row(s) for request state(s) {missing} — incomplete generation")
+ unknown = sorted(row_state_set - request_states)
+ if unknown:
+ raise SystemExit(f"corrupt {name} {run_dir}: manifest has row(s) for state(s) {unknown} not in the request (stale/unknown state)")
+ # 물리 고아 탐지 (경로 기반): 캐노니컬 프레임을 직접 담은 모든 디렉토리가
+ # 어떤 row 의 파일 디렉토리이거나 요청 상태의 예약 위치여야 한다.
+ row_dirs = set()
+ for row in manifest["rows"]:
+ for rel in row.get("files") or []:
+ if isinstance(rel, str):
+ row_dirs.add(str(Path(rel).parent))
+ physical_dirs = set()
+ if frames_root.is_dir():
+ for frame in frames_root.rglob("frame-*.png"):
+ if frame.name.endswith(".plain.png") or frame.parent.name == "orig":
+ continue
+ physical_dirs.add(str(Path("frames") / frame.parent.relative_to(frames_root)))
+ orphan = sorted(physical_dirs - row_dirs)
+ if orphan:
+ raise SystemExit(f"corrupt {name} {run_dir}: physical frames under {orphan} have no manifest row (orphan/stale generation)")
+ request_states_spec = request.get("states", {})
+ for row in manifest["rows"]:
+ state = row["state"]
+ files = row.get("files")
+ if not isinstance(files, list) or not files:
+ raise SystemExit(f"corrupt {name} {run_dir}: manifest row '{state}' has no frame files (empty generation)")
+ prefix = frames_dir_rel(request, state) + "/"
+ for rel in files:
+ if not isinstance(rel, str) or not rel.startswith(prefix):
+ raise SystemExit(f"corrupt {name} {run_dir}: row '{state}' file {rel!r} is not under {prefix} (state boundary)")
+ if not (run_dir / rel).is_file():
+ raise SystemExit(f"corrupt {name} {run_dir}: manifest row '{state}' references missing frame {rel}")
+ # the canonical physical frames for this state must EXACTLY equal the row's files — no
+ # missing (the `files:[]` / deleted-frames case) and no extra (a stale frame on disk).
+ state_dir = run_dir / frames_dir_rel(request, state)
+ physical = sorted(
+ f"{prefix}{f.name}" for f in state_dir.glob("frame-*.png") if not f.name.endswith(".plain.png")
+ ) if state_dir.is_dir() else []
+ if physical != sorted(files):
+ raise SystemExit(f"corrupt {name} {run_dir}: row '{state}' files {sorted(files)} != physical canonical frames {physical}")
+ # a complete generation has exactly the request's frame count for the state —
+ # 행 프레임 풀 = primary + 선언된 테이크들 (takes 1급 계약)
+ state_spec = request_states_spec.get(state, {})
+ expected = int(state_spec.get("frames", len(files)))
+ expected += sum(int(take.get("frames", 0)) for take in (state_spec.get("takes") or []))
+ if len(files) != expected:
+ raise SystemExit(f"corrupt {name} {run_dir}: row '{state}' has {len(files)} frame(s), request expects {expected}")
+ if "frames" in row and row["frames"] != len(files):
+ raise SystemExit(f"corrupt {name} {run_dir}: row '{state}' row.frames={row['frames']} != {len(files)} files")
+
+
+def load_consistent_frames_manifest(run_dir: Path, name: str = "frames manifest",
+ allow_pending_states: bool = False) -> dict:
+ """For readers that TOLERATE an ungenerated run (serve scaffold, inspect from raw): return the
+ validated + consistent manifest if present; {} only when the run genuinely has NO generation
+ (no manifest AND no physical frame dirs); fail loud if the manifest is corrupt/inconsistent, OR
+ absent while physical frames exist (an orphan/stale generation — not a fresh scaffold).
+ `allow_pending_states=True` (뷰 전용) 는 아직 생성 전인 요청 상태의 행 부재를 허용한다."""
+ frames_root = run_dir / "frames"
+ manifest = load_frames_manifest(frames_root / "frames-manifest.json")
+ if not manifest:
+ physical = sorted(d.name for d in frames_root.iterdir() if d.is_dir()) if frames_root.is_dir() else []
+ if physical:
+ raise SystemExit(
+ f"orphan frames in {run_dir}: physical frame dir(s) {physical} exist but "
+ f"frames/frames-manifest.json is absent — not a fresh scaffold. Re-extract or remove them."
+ )
+ return {}
+ _require_generation_consistency(run_dir, manifest, name, allow_pending_states=allow_pending_states)
+ return manifest
+
+
+def require_frames_manifest(run_dir: Path) -> dict:
+ """Gate for a finished-generation consumer (compose / export / preview / gif / cycle): the
+ published frames manifest must be present, schema-valid, AND consistent with the physical frame
+ tree + request (No Silent Fallback / Consistency). A consumer of a completed generation must
+ call this before reading physical frames, so it never silently produces output from a missing,
+ broken, stale, partial, or orphan generation."""
+ manifest = load_consistent_frames_manifest(run_dir)
+ if not manifest:
+ raise SystemExit(
+ f"frames/frames-manifest.json not found in {run_dir}; run a successful extract before "
+ f"consuming this generation."
+ )
+ return manifest
+
+
+def _merged_failure_lists(prior: dict, result: dict, target_states: set, all_states: set):
+ """Compute the union of the run's CURRENTLY-UNRESOLVED per-state failures. A subset
+ `--states` extract only determines the outcome of the states it targets, so carry forward
+ prior failures for untouched states and replace the target states with this attempt's
+ outcome (a target state that succeeded drops out). Warnings are scoped to states that still
+ have an error, so a resolved state never leaves a stray warning in the failure evidence.
+ Returns (errors, warnings); empty errors means every recorded failure is resolved."""
+ def _state_of(message: object):
+ head = str(message).split(":", 1)[0]
+ return head if head in all_states else None
+
+ kept_errors = [e for e in prior.get("errors", []) if _state_of(e) is not None and _state_of(e) not in target_states]
+ new_errors = [e for e in result.get("errors", []) if _state_of(e) is not None]
+ merged_errors = kept_errors + new_errors
+ unresolved = {str(e).split(":", 1)[0] for e in merged_errors}
+ kept_warnings = [w for w in prior.get("warnings", []) if _state_of(w) not in target_states and _state_of(w) in unresolved]
+ new_warnings = [w for w in result.get("warnings", []) if _state_of(w) in unresolved]
+ return merged_errors, kept_warnings + new_warnings
+
+
+def _commit_generation(run_dir: Path, staging: Path | None, result: dict, target_states: set, all_states: set) -> None:
+ """Advance the run's two canonical surfaces — the frames/ generation and the per-state
+ failure evidence (extract-failure.json) — as ONE transaction under a single publish_guard.
+
+ `staging` is the new complete frames dir to swap into frames/ on success, or None to leave
+ frames/ untouched on failure. The evidence is (re)written from the merged unresolved
+ failures, or removed when none remain. Either BOTH surfaces advance or, on any I/O failure,
+ both roll back to their pre-commit state (Atomicity/Consistency). Because the whole commit
+ holds publish_guard, a reader under read_guard never observes the new frames alongside a
+ stale failure record (Isolation) — the old defect where a swapped-in generation and a not-
+ yet-merged prior failure were briefly visible together."""
+ frames_final = run_dir / "frames"
+ evidence = run_dir / "extract-failure.json"
+ frames_backup = run_dir / ".frames.sg-backup"
+ evidence_backup = run_dir / ".extract-failure.sg-backup"
+
+ def _discard(p: Path) -> None:
+ if p.is_dir():
+ shutil.rmtree(p, ignore_errors=True)
+ elif p.exists():
+ p.unlink()
+
+ with publish_guard(run_dir):
+ prior = load_failure_evidence(evidence) # fail-loud on a corrupt/broken-schema record
+ merged_errors, merged_warnings = _merged_failure_lists(prior, result, target_states, all_states)
+
+ _discard(frames_backup)
+ _discard(evidence_backup)
+ frames_backed_up = False
+ frames_swapped = False
+ evidence_backed_up = False
+ evidence_written = False
+ try:
+ if staging is not None:
+ if frames_final.exists():
+ frames_final.rename(frames_backup)
+ frames_backed_up = True
+ staging.rename(frames_final)
+ frames_swapped = True
+ if evidence.exists():
+ evidence.rename(evidence_backup)
+ evidence_backed_up = True
+ if merged_errors:
+ payload = dict(result)
+ payload["ok"] = False
+ payload["errors"] = merged_errors
+ payload["warnings"] = merged_warnings
+ atomic_write_text(evidence, json.dumps(payload, ensure_ascii=False, indent=2) + "\n")
+ evidence_written = True
+ # else: leave evidence absent — every recorded per-state failure is resolved
+ except BaseException:
+ # roll BOTH surfaces back to their pre-commit state, in reverse order
+ if evidence_written:
+ _discard(evidence)
+ if evidence_backed_up and not evidence.exists():
+ evidence_backup.rename(evidence)
+ if frames_swapped:
+ _discard(frames_final)
+ if frames_backed_up:
+ frames_backup.rename(frames_final)
+ elif frames_backed_up and not frames_final.exists():
+ frames_backup.rename(frames_final)
+ raise
+ _discard(frames_backup)
+ _discard(evidence_backup)
+
+
+def _run(args: argparse.Namespace):
+ if args.fringe_key_threshold < args.key_threshold:
+ raise SystemExit("--fringe-key-threshold must be greater than or equal to --key-threshold")
+ if args.fringe_unmix_reach is not None and args.fringe_unmix_reach < 0:
+ raise SystemExit("--fringe-unmix-reach must be zero or positive")
+ if args.spill_max_fraction is not None and args.spill_max_fraction < 0:
+ raise SystemExit("--spill-max-fraction must be zero or positive")
+
+ run_dir = args.run_dir.expanduser().resolve()
+ acquire_run_dir_lock(run_dir, "extract_sprite_row_frames")
+ try:
+ return _run_locked(args, run_dir)
+ finally:
+ # 작업 단위 상호배제 — atexit 까지 쥐고 있으면 장수 프로세스(테스트 러너 등)가
+ # in-process 추출 뒤 heal_run 서브프로세스를 자기 락으로 막는다.
+ release_run_dir_lock(run_dir)
+
+
+def _run_locked(args: argparse.Namespace, run_dir: Path):
+ request = load_request(run_dir)
+ # Sparse-floor SSoT is the request's subject profile; the CLI flag is an
+ # explicit override only. Profile-derived values are NOT stamped into
+ # extract_args (frames are a derived cache of raw + request + engine, so a
+ # later subject change must re-resolve on heal); explicit flags are.
+ args._subject_kind = subject_kind(request)
+ args._min_used_pixels_explicit = args.min_used_pixels is not None
+ if args.min_used_pixels is None:
+ args.min_used_pixels = default_min_used_pixels(request)
+ # 크로마 튜너블의 SSoT 는 request JSON `chroma` — CLI 는 명시 override 만.
+ # 실제 적용값은 request 에 되써서 런이 스스로 재현 가능하게 남긴다.
+ chroma_config = dict(request.get("chroma") or {})
+ unmix_reach = (
+ args.fringe_unmix_reach
+ if args.fringe_unmix_reach is not None
+ else int(chroma_config.get("unmix_reach", 4))
+ )
+ if unmix_reach < 0:
+ raise SystemExit("chroma.unmix_reach must be zero or positive")
+ spill_max_fraction = (
+ args.spill_max_fraction
+ if args.spill_max_fraction is not None
+ else float(chroma_config.get("spill_max_fraction", 0.005))
+ )
+ if spill_max_fraction < 0:
+ raise SystemExit("chroma.spill_max_fraction must be zero or positive")
+ chroma_mode = (
+ args.chroma_mode
+ if args.chroma_mode is not None
+ else str(chroma_config.get("mode", "rgb"))
+ )
+ if chroma_mode not in ("rgb", "ycbcr"):
+ raise SystemExit("chroma.mode must be 'rgb' or 'ycbcr'")
+ effective_chroma = {
+ **chroma_config,
+ "mode": chroma_mode,
+ "unmix_reach": unmix_reach,
+ "spill_max_fraction": spill_max_fraction,
+ }
+ if effective_chroma != chroma_config:
+ request["chroma"] = effective_chroma
+ atomic_write_text(
+ run_dir / "sprite-request.json",
+ json.dumps(request, ensure_ascii=False, indent=2) + "\n",
+ )
+ states = list(request["states"]) if args.states == "all" else [state.strip() for state in args.states.split(",") if state.strip()]
+ cell_width, cell_height, safe_margin_x, safe_margin_y = cell_geometry(request["cell"])
+ fit_config = request.get("fit") or {}
+ chroma_key = tuple(int(value) for value in request["chroma_key"]["rgb"])
+ # Build the new frames in a staging dir, then swap it into place as one generation under
+ # publish_guard (below). Extract rewrites many frame files; without this, a live curation
+ # reader (serve_curation read_guard) would observe a mix of old/new frame generations
+ # mid-extract. The manifest records the FINAL `frames/<state>/...` paths regardless of the
+ # staging write location. Writer-writer exclusion stays the separate `.sprite-gen.lock`.
+ frames_final = run_dir / "frames"
+ frames_root = run_dir / ".frames.sg-staging"
+ target = set(states)
+ # A subset `--states` re-extract (auto-correction / single-row regeneration) must preserve
+ # the states it is NOT rebuilding — the staging generation, which is swapped in whole, is
+ # seeded with those states' current frames and carries their prior manifest rows, so the
+ # swap replaces only the rebuilt states and never deletes the others (SSoT/Idempotency).
+ # Read+validate the prior manifest FIRST, before staging is even created: a corrupt prior
+ # generation fails loud here (No Silent Fallback), so the prior generation stays byte-intact
+ # and we never publish an incomplete manifest that disagrees with the carried frame tree.
+ rows = []
+ if frames_final.is_dir():
+ prior_manifest = load_frames_manifest(frames_final / "frames-manifest.json")
+ rows = [row for row in prior_manifest.get("rows", []) if row.get("state") not in target]
+ if frames_root.exists():
+ shutil.rmtree(frames_root)
+ frames_root.mkdir(parents=True)
+ if frames_final.is_dir():
+ for state_name in request["states"]:
+ if state_name not in target:
+ rel = frames_dir_rel(request, state_name).removeprefix("frames/")
+ src = frames_final / rel
+ if src.is_dir():
+ (frames_root / rel).parent.mkdir(parents=True, exist_ok=True)
+ shutil.copytree(src, frames_root / rel)
+ all_errors: list[str] = []
+ all_warnings: list[str] = []
+
+ pixel_unfake = bool(fit_config.get("pixel_unfake"))
+ # 기본 = 셀과 동일(1:1) — 생성 프롬프트가 "TRUE 셀xN pixel grid" 를 명시하는
+ # 현행 레시피에서 원본 그리드를 그대로 따라간다. 청키 2x 룩을 원할 때만
+ # 절반 값(예: 셀 64 + 로지컬 32)을 명시한다. (2026-07-05, 이전 기본은 usable//2)
+ # 배율·유효 논리 높이의 SSoT 는 `curation.pixel_snap_scale` / `effective_logical_height`
+ # 다 — 여기서 식을 손으로 복제하면 소비자(웹뷰·compose)와 조용히 갈린다 (원칙 1).
+ pp_scale = pixel_snap_scale(request) or 1
+ logical_height = effective_logical_height(request) or cell_height
+ logical_width = max(1, cell_width // pp_scale)
+ # 정수 격자가 선언을 반올림해 무효로 만들면 관측시킨다 — 아무 일도 안 하는 값이
+ # 요청 파일에 남아 라벨과 지문만 오염시키던 조용한 실패다 (원칙 6, maintainer 2026-07-25).
+ declared_logical_height = fit_config.get("logical_height")
+ if (pixel_unfake and declared_logical_height is not None
+ and int(declared_logical_height) != logical_height):
+ all_warnings.append(
+ f"fit.logical_height={declared_logical_height} is not applied as declared: the "
+ f"integer logical grid rounds it to {logical_height} (scale {pp_scale}x). Declare a "
+ f"divisor of cell height {cell_height} (e.g. {cell_height}, {max(1, cell_height // 2)}) "
+ f"for a chunkier look, or drop the key — as declared it changes nothing.")
+ pp_detail_bias = bool(fit_config.get("detail_bias", True))
+ # 기본 48 (24 에서 상향, 2026-07-17): run-wide 팔레트는 배치의 모든 행이 나눠 쓴다.
+ # 24 는 다상태 배치(hero 36상태×150프레임)에서 희소 포인트 컬러를 굶겼다 —
+ # population median-cut 이 금색(머리끈·목걸이) 클러스터를 갈색 박스에 흡수해
+ # 디테일이 통째로 사라졌다 (실측: 24색 배치 팔레트에서 금색 최근접 ΔRGB 59,
+ # 48색이면 5.5). 레트로 감축이 필요한 런은 request `fit.palette_size` 로 명시한다.
+ palette_size = int(fit_config.get("palette_size", 48))
+ # 원본 화질 표시 쌍둥이(orig/)의 배율 상한: 배율 자체는 행별 네이티브 비율로
+ # 정한다 (_orig_display_scale). 고정 ×4 캡은 raw 피치가 4px 를 넘는 런에서
+ # 다운스케일 열화를 만들어 "원본" 뷰가 원본이 아니게 됐다 (synthetic_fixture_b down
+ # 피치 ~19px → 4.8× 축소 뭉갬, maintainer 발견 2026-07-23). 상한은 파일/메모리
+ # 바운드일 뿐 화질 정책이 아니다.
+ plain_display_cap = max(1, 2048 // max(1, cell_width, cell_height))
+
+ def _orig_display_scale(components: list, frames: list) -> int:
+ """행별 orig 트윈 배율 = 네이티브 비율의 ceil (다운스케일 금지, cap 바운드).
+
+ ratio = 컴포넌트 crop 크기 / 최종 콘텐츠 bbox 크기 (축별 max). S ≥ ratio 면
+ fit_component_to_bbox 의 리샘플이 경미한 업스케일이 돼 raw 블록이 뭉개지지
+ 않는다. 트윈 = 셀×S 정사각이라는 셀 좌표 계약은 그대로다."""
+ ratio = 0.0
+ for component, frame in zip(components, frames):
+ frame_bbox = frame.getbbox()
+ comp_bbox = component.getbbox()
+ if frame_bbox is None or comp_bbox is None:
+ continue
+ ratio = max(
+ ratio,
+ (comp_bbox[2] - comp_bbox[0]) / max(1, frame_bbox[2] - frame_bbox[0]),
+ (comp_bbox[3] - comp_bbox[1]) / max(1, frame_bbox[3] - frame_bbox[1]),
+ )
+ return min(plain_display_cap, max(1, math.ceil(ratio)))
+
+ pending: list = []
+
+ def finalize_state(state: str, frames: list, frame_count: int, method: str,
+ plain_frames: list | None = None, orig_frames: list | None = None,
+ input_grids: list | None = None, labels: list | None = None,
+ takes: list | None = None) -> None:
+ rel_dir = frames_dir_rel(request, state) # e.g. frames/down/idle (taxonomy) | frames/down_idle (legacy)
+ state_dir = frames_root / rel_dir.removeprefix("frames/")
+ state_dir.mkdir(parents=True, exist_ok=True)
+ output_paths = []
+ for index, frame in enumerate(frames):
+ output = state_dir / f"frame-{index}.png"
+ atomic_save_image(frame, output)
+ output_paths.append(f"{rel_dir}/frame-{index}.png") # final location (staging is swapped in)
+ # 픽셀 언페이크 전 원본 변형(.plain.png) — curation.json `pixel_unfake: false`
+ # 굽기(compose)가 이 셀 크기 쌍둥이를 읽는다. 아틀라스 슬롯 = 셀 크기라 여긴
+ # 셀 해상도로 유지한다 (compose_atlas 가 정확히 셀 크기를 요구, 기하 불변).
+ plain_paths = []
+ if plain_frames is not None:
+ for index, frame in enumerate(plain_frames):
+ output = state_dir / f"frame-{index}.plain.png"
+ atomic_save_image(frame, output)
+ plain_paths.append(f"{rel_dir}/frame-{index}.plain.png")
+ # 원본 화질 표시용 고해상 쌍둥이 — 큐레이션뷰 pp 해제 토글이 읽는다. 셀 크기
+ # .plain.png 는 확대 시 흐리므로 별도 서브폴더(orig/)에 S×셀로 굽는다. 서브폴더라
+ # frame-*.png glob 소비자(inspect/measure/compose)와 충돌하지 않고 순수 표시용이다.
+ orig_paths = []
+ if orig_frames is not None:
+ orig_dir = state_dir / "orig"
+ orig_dir.mkdir(parents=True, exist_ok=True)
+ for index, frame in enumerate(orig_frames):
+ output = orig_dir / f"frame-{index}.png"
+ atomic_save_image(frame, output)
+ orig_paths.append(f"{rel_dir}/orig/frame-{index}.png")
+
+ errors, warnings, frame_records = inspect_frames(frames, chroma_key, args)
+ all_errors.extend(f"{state}: {error}" for error in errors)
+ all_warnings.extend(f"{state}: {warning}" for warning in warnings)
+ row = {
+ "state": state,
+ "frames": frame_count,
+ "method": method,
+ "files": output_paths,
+ "frame_records": frame_records,
+ "ok": not errors,
+ # 파생 캐시 키 — 이 행을 구운 엔진 리비전. heal_run 이 현재 엔진과
+ # 비교해 stale 행을 raw 에서 자동 재유도한다 (self-heal).
+ "engine_revision": engine_revision(),
+ }
+ if labels and any(labels):
+ row["labels"] = labels
+ if takes:
+ row["takes"] = takes
+ if plain_paths:
+ row["plain_files"] = plain_paths
+ if orig_paths:
+ row["orig_files"] = orig_paths
+ if input_grids is not None and any(g is not None for g in input_grids):
+ # 프레임별 검출 입력 격자(셀 좌표 절단선) — 큐레이터 원본 뷰 오버레이용
+ row["input_grids"] = input_grids
+ rows.append(row)
+
+ def _load_strip(state: str, tag: str, rel: str, frame_count: int) -> Image.Image | None:
+ raw_path = run_dir / rel
+ if not raw_path.is_file():
+ all_errors.append(f"{tag}: missing raw strip {raw_path}")
+ return None
+ with Image.open(raw_path) as opened:
+ if chroma_mode == "ycbcr":
+ ycc_notes: list[str] = []
+ strip = remove_chroma_background_ycbcr(opened, chroma_key, ycc_notes)
+ all_warnings.extend(f"{tag}: {note}" for note in ycc_notes)
+ else:
+ strip = remove_chroma_background(
+ opened,
+ chroma_key,
+ args.key_threshold,
+ args.fringe_key_threshold,
+ args.fringe_delta,
+ unmix_reach=unmix_reach,
+ spill_max_fraction=spill_max_fraction,
+ )
+ return separate_fused_poses(strip, frame_count, fit_config, args.segmentation, state)
+
+ def _snap_strip(tag: str, strip: Image.Image, frame_count: int) -> dict[str, Any] | None:
+ """한 생성 스트립(primary 또는 take)을 컴포넌트 분리→합의 스냅→캡까지.
+
+ 프레임별 픽셀 언페이크 (2026-07-05 재설계, 2026-07-20 per-frame 확정): 포즈
+ 컴포넌트를 먼저 분리한 뒤 각 프레임마다 피치·위상을 독립 검출해 **자기
+ 검출값으로** 스냅한다. 스트립 전역 단일 격자는 프레임 간 위상 드리프트로
+ 미끄러졌고(maintainer 관찰: "격자가 픽셀에 안 맞음"), 합의 피치 강제는 측정차를
+ 폭 전체에 누적시켰다(maintainer 관찰: "눈이 반쪽", plan per-frame-pixel-grid).
+ 스트립(=한 번의 생성) 단위 합의는 검출 실패 프레임의 fallback 전용이다
+ — 테이크마다 생성이 달라 블록 크기가 다를 수 있어 합의도 스트립 단위다.
+ """
+ images = extract_component_images(strip, frame_count)
+ method = "components"
+ if images is None:
+ if not args.allow_slot_fallback:
+ all_errors.append(f"{tag}: could not extract {frame_count} sprite components")
+ return None
+ slot_width = strip.width / frame_count
+ images = [
+ strip.crop((round(i * slot_width), 0, round((i + 1) * slot_width), strip.height))
+ for i in range(frame_count)
+ ]
+ method = "slots-explicit"
+ images = tighten_components(images)
+ # 프레임 자체 검출 (피치·위상) 이 1순위 진실이다. 프레임별 검출값의
+ # 중앙값(합의)은 검출 실패 프레임의 fallback 전용으로만 계산한다 —
+ # 합의를 프레임에 강제하면 측정차가 폭 전체에 누적된다 (아래 스냅 루프 주석).
+ # 피치는 소수이고 축마다 다를 수 있다 — AI 가 그린 블록은 정수 픽셀로 떨어지지
+ # 않고(예: 17.24), 비균등 리스케일된 생성물은 가로/세로 블록 크기가 어긋난다.
+ # 정수로 반올림하면 그 오차가 폭 전체에 누적돼 셀 경계가 블록 한가운데를 지난다.
+ # 측정은 소수·축별로 하고, 격자선은 `_grid_edges` 가 정수로 확정한다.
+ hint = int(fit_config.get("pitch_hint", 0))
+ grids = [detect_pixel_grid(component) for component in images]
+
+ def _consensus(axis: int) -> float:
+ confident = sorted(g[0][axis] for g in grids if g[0][axis] >= 2.0)
+ if confident:
+ # 붕괴한 프레임(참 피치의 약수로 떨어진 값)이 중앙값을 오염시킨다 —
+ # down_carry_run 은 6 프레임 중 절반이 3.00 으로 무너져 합의가 5.00 이 됐다.
+ # 스트립 안에서 참 피치는 거의 같으므로, 최대값의 60% 미만은 붕괴로 보고 버린다.
+ ceiling = confident[-1]
+ trusted = [p for p in confident if p >= ceiling * 0.6]
+ dropped = len(confident) - len(trusted)
+ if dropped:
+ all_warnings.append(
+ f"{tag}: dropped {dropped} collapsed per-frame pitch(es) below {ceiling * 0.6:.2f}"
+ )
+ return trusted[len(trusted) // 2]
+ if hint >= 2:
+ all_warnings.append(
+ f"{tag}: pitch from fit.pitch_hint={hint} (all per-frame detections inconclusive)"
+ )
+ return float(hint)
+ strip_pitch, _ = detect_pixel_grid(strip)
+ if strip_pitch[axis] >= 2.0:
+ all_warnings.append(
+ f"{tag}: pitch from whole-strip detection={strip_pitch[axis]:.2f}"
+ )
+ return strip_pitch[axis]
+
+ consensus_x, consensus_y = _consensus(0), _consensus(1)
+ # 세컨드 오피니언 (perfectpixel unfake 이식): 동일색 런 최빈값으로 축별
+ # 피치를 따로 추정해 합의 피치와 교차검증한다. 경고 전용 — 스냅은 아래에서
+ # 계속 detect_pixel_grid 합의만 쓴다 (자동 교체 금지, No Silent Fallback).
+ runlen_axes = [estimate_pixel_grid_runlen(component) for component in images]
+
+ def _runlen_consensus(axis: int) -> float:
+ confident = sorted(e[axis] for e in runlen_axes if e[axis] >= 2.0)
+ return confident[len(confident) // 2] if confident else 1.0
+
+ for note in crosscheck_pitch_runlen(
+ (consensus_x, consensus_y), (_runlen_consensus(0), _runlen_consensus(1))
+ ):
+ all_warnings.append(f"{tag}: {note}")
+ print(f"[pitch-crosscheck] {tag}: {note}", file=sys.stderr)
+ # 피치 중재 (하모닉 오검출 방어): 세컨드 오피니언과 크게 어긋나면 셀 균일도
+ # 실측으로 승자 채택 — 채택 결과는 경고로 관측된다 (arbitrate_pitch docstring).
+ # 위상은 주고받지 않는다 — 채점도 스냅도 각자 `_best_phase` 로 실측한다
+ # (plan `frame-pitch-consensus-eats-a-row`). 프레임 검출 위상을 넘겨 그대로
+ # 돌려받던 인자/반환은 읽는 곳이 없어 걷어냈다.
+ (consensus_x, consensus_y), _pitch_src = arbitrate_pitch(
+ images, (consensus_x, consensus_y),
+ (_runlen_consensus(0), _runlen_consensus(1)), tag, all_warnings)
+ # 프레임 자체 검출 격자가 1순위 진실이다 (maintainer 2026-07-20, plan
+ # sprite-gen/per-frame-pixel-grid): 합의 피치를 프레임에 강제하면 측정차
+ # (0.5px/셀 수준)가 폭 전체에 누적돼 경계가 블록 중앙을 지난다 (회귀
+ # synthetic_fixture_a down_jump frame-0: 합의 13.00 vs 자체 12.50 → 눈이 반쪽).
+ # 단 own 채택은 합의 '피치 패밀리'(비율 1.1) 이내에서만이다 — 하모닉/붕괴
+ # 오검출(×2/×3·÷2/÷3)까지 믿으면 한 프레임의 거대 native 가
+ # conform_row_logical 의 행 일관 배율을 끌어내려 행 전체가 붕괴한다
+ # (회귀 synthetic_fixture_a up_run frame-2, 2026-07-22 — 판정 근거는
+ # resolve_frame_pitch docstring). 패밀리 밖 = 합의로 스냅하고 프레임별
+ # 경고로 관측한다 (No Silent Fallback). 합의는 자체 검출이 실패한
+ # 프레임의 fallback 이기도 하다. 기록(cut_edges)은 실제 샘플링한 그
+ # 선이라 표시 격자 = 샘플링 진실 (maintainer 확정 2026-07-18) 유지.
+ snapped = []
+ cut_edges: list[tuple[list[int], list[int]] | None] = []
+ used_pitches: list[tuple[float, float]] = []
+ for index, (component, ((own_x, own_y), _own_phase)) in enumerate(zip(images, grids)):
+ if min(own_x, own_y) >= 2.0:
+ (use_x, use_y), outlier = resolve_frame_pitch(
+ (own_x, own_y), (consensus_x, consensus_y))
+ if outlier:
+ all_warnings.append(
+ f"{tag}: frame {index} own pitch {own_x:.2f}x{own_y:.2f} is outside the "
+ f"consensus pitch family {consensus_x:.2f}x{consensus_y:.2f} — "
+ f"harmonic/collapsed misdetection; snapped at consensus")
+ elif min(consensus_x, consensus_y) >= 2.0:
+ use_x, use_y = consensus_x, consensus_y
+ all_warnings.append(
+ f"{tag}: frame {index} pitch detection inconclusive — consensus fallback "
+ f"{consensus_x:.2f}x{consensus_y:.2f}")
+ else:
+ snapped.append(component)
+ cut_edges.append(None)
+ used_pitches.append((1.0, 1.0))
+ continue
+ # 위상은 엣지 히스토그램의 무게중심(`_axis_refine` 반환값)이 아니라 실제
+ # 셀 균일도로 다시 고른다 (maintainer 관측 2026-07-25 "눈이 8칸이어야 하는데 7칸",
+ # synthetic_fixture_b down_jump frame-0). 히스토그램 위상은 1차원 신호의 근사라
+ # 참 위상에서 반 칸까지 밀린다 — 실측: 피치 13.00 에서 검출 위상 y=2.02 vs
+ # 실측 최적 8.12 (차이 6.1 ≈ pitch/2). `refine_edges_to_boundaries` 는
+ # ±pitch/3 창 안에서만 절단선을 당기므로 이 크기의 위상 오차는 구조적으로
+ # 복구되지 않고, 눈 4행이 3행으로 병합됐다. 피치가 고정된 상태에서 위상만
+ # 비교하므로 균일도 지표의 '거친 격자 편애' 편향은 개입하지 않는다.
+ frame_phase = _best_phase(component, (use_x, use_y))
+ xs = _grid_edges(component.width, use_x, frame_phase[0])
+ ys = _grid_edges(component.height, use_y, frame_phase[1])
+ xs, ys = refine_edges_to_boundaries(component, xs, ys, (use_x, use_y))
+ snapped.append(snap_by_edges(component, xs, ys, pp_detail_bias))
+ cut_edges.append((xs, ys))
+ used_pitches.append((use_x, use_y))
+ rounded = [(round(px_, 2), round(py_, 2)) for (px_, py_) in used_pitches]
+ def _pitch_repr(pair: tuple[float, float]):
+ return pair[0] if abs(pair[0] - pair[1]) < 0.05 else pair
+ pitch = (_pitch_repr(rounded[0]) if len(set(rounded)) == 1
+ else [_pitch_repr(pair) for pair in rounded])
+ # 눌림 없음 — 스냅된 네이티브 논리 크기를 유지한다 (maintainer 확정 2026-07-14,
+ # 옵트인 잔재까지 완전 제거 2026-07-17): 계약(logical_height)으로의 conform
+ # 축소는 칸을 병합해 디테일을 갈라먹는다. 과거의 `fit.conform: true` 옵트인은
+ # 제거된 결정이 플래그 하나로 되살아나는 회귀 경로였다 (회귀 2026-07-17:
+ # 높이 통일 시도가 이 플래그로 재발) — 선언되어 있으면 요란하게 거부한다.
+ # 물리 한계(셀에서 바닥 마진만 지킴)만 캡으로 강제하고, 캡에 걸리면 관측
+ # 가능하게 경고한다.
+ if fit_config.get("conform") is not None:
+ raise SystemExit(
+ "fit.conform was removed (maintainer 2026-07-14/17): native logical size is "
+ "the only behavior — squashing to logical_height merges cells and eats "
+ "detail. Remove the key from sprite-request.json.")
+ cap_w = max(1, cell_width // pp_scale)
+ cap_h = max(1, (cell_height - safe_margin_y) // pp_scale)
+ over = [f"{i}:{s.width}x{s.height}" for i, s in enumerate(snapped)
+ if s.width > cap_w or s.height > cap_h]
+ if over:
+ all_warnings.append(
+ f"{tag}: native logical exceeds the physical cap "
+ f"{cap_w}x{cap_h} — capped frames (reroll candidates): {', '.join(over)}")
+ # 안전영역(사방 여백 준수 상한)은 넘었지만 물리캡 이내 = 여백 침범.
+ # 리롤 대상 아님 — 정보성 알림만 (maintainer 확정 2026-07-14).
+ safe_w = max(1, (cell_width - safe_margin_x * 2) // pp_scale)
+ safe_h = max(1, (cell_height - safe_margin_y * 2) // pp_scale)
+ soft = [f"{i}:{s.width}x{s.height}" for i, s in enumerate(snapped)
+ if (s.width > safe_w or s.height > safe_h)
+ and s.width <= cap_w and s.height <= cap_h]
+ if soft:
+ all_warnings.append(
+ f"{tag}: frames exceed the safe area {safe_w}x{safe_h} but fit "
+ f"within the margin zone (informational, no action): {', '.join(soft)}")
+ logical_frames = conform_row_logical(snapped, cap_w, cap_h, pp_detail_bias)
+ return {"method": method, "pitch": pitch, "logical": logical_frames,
+ "components": images, "cut_edges": cut_edges}
+
+ total_steps = len(states) * 2 # 1패스(컴포넌트/스냅) + 2패스(팔레트/배치)
+ progress_step = 0
+ for state in states:
+ _write_progress(run_dir, "extract", progress_step, total_steps, state, "components")
+ progress_step += 1
+ if state not in request["states"]:
+ raise SystemExit(f"unknown state in request: {state}")
+ state_cfg = request["states"][state]
+ frame_count = int(state_cfg["frames"])
+ takes_cfg = state_cfg.get("takes") or []
+ if takes_cfg and not pixel_unfake:
+ all_errors.append(f"{state}: takes require fit.pixel_unfake")
+ continue
+ if not pixel_unfake:
+ strip = _load_strip(state, state, raw_rel(request, state), frame_count)
+ if strip is None:
+ continue
+ frames = extract_component_frames(strip, frame_count, cell_width, cell_height, safe_margin_x, safe_margin_y, fit_config)
+ method = "components"
+ if frames is None:
+ if not args.allow_slot_fallback:
+ all_errors.append(f"{state}: could not extract {frame_count} sprite components")
+ continue
+ frames = extract_slot_frames(strip, frame_count, cell_width, cell_height, safe_margin_x, safe_margin_y, fit_config)
+ method = "slots-explicit"
+ finalize_state(state, frames, frame_count, method)
+ continue
+ # 테이크 1급 계약: 한 상태의 프레임 풀 = primary 스트립 + 선언된 테이크들.
+ # 각 스트립은 독립 생성이므로 따로 스냅하고(스트립별 합의 피치), 행 정합·
+ # 팔레트·배치는 행 단위로 함께 한다. 어느 스트립 하나라도 실패하면 행 전체를
+ # 이전 세대로 남긴다 (Atomicity — 부분 풀 게시 금지).
+ specs: list[tuple[str, str, int, str]] | None = [
+ (state, raw_rel(request, state), frame_count, "")]
+ for take in takes_cfg:
+ label = str(take.get("label") or "")
+ if not label or "/" in label or label.startswith("."):
+ all_errors.append(f"{state}: take needs a filesystem-safe label: {take!r}")
+ specs = None
+ break
+ specs.append((f"{state}[{label}]", take_raw_rel(request, state, label),
+ int(take["frames"]), label))
+ if specs is None:
+ continue
+ parts: list[dict[str, Any]] | None = []
+ for tag, rel, count, label in specs:
+ strip = _load_strip(state, tag, rel, count)
+ part = _snap_strip(tag, strip, count) if strip is not None else None
+ if part is None:
+ parts = None
+ break
+ part.update({"label": label, "count": count, "raw": rel})
+ parts.append(part)
+ if parts is None:
+ continue
+ registered = register_row_frames([f for p in parts for f in p["logical"]])
+ labels = None
+ takes_summary = None
+ if len(parts) > 1:
+ labels = [
+ f"{p['label']}#{i}" if p["label"] else ""
+ for p in parts for i in range(p["count"])
+ ]
+ starts = [0]
+ for p in parts[:-1]:
+ starts.append(starts[-1] + p["count"])
+ takes_summary = [
+ {"label": p["label"] or None, "start": start, "frames": p["count"], "raw": p["raw"]}
+ for p, start in zip(parts, starts)
+ ]
+ # 전/후 비교 쌍둥이(plain/orig)는 픽셀 언페이크 프레임의 최종 콘텐츠 bbox 가
+ # 확정된 뒤(아래 pending 루프) 같은 풋프린트에 앉힌다 — 여기서는 원본
+ # 컴포넌트만 보관한다. (이전: legacy fit 이 가용영역을 채워 pp 결과보다
+ # 크게 앉음 → 토글 순간 크기가 튀어 품질 비교가 안 됐다.)
+ pending.append({
+ "state": state, "frame_count": len(registered), "method": parts[0]["method"],
+ "pitch": parts[0]["pitch"] if len(parts) == 1 else [p["pitch"] for p in parts],
+ "frames": registered,
+ "components": [c for p in parts for c in p["components"]],
+ "cut_edges": [e for p in parts for e in p["cut_edges"]],
+ "labels": labels, "takes": takes_summary,
+ })
+
+ if pixel_unfake and pending:
+ # 팔레트는 런 전체(모든 state 의 논리 프레임)에서 한 번 뽑아 공유한다 —
+ # 프레임/행 간 색 흔들림(플리커) 제거 + 아이덴티티 색 고정.
+ pinned = None if getattr(args, "repalette", False) else load_pinned_palette(run_dir)
+ if pinned is not None:
+ palette = pinned
+ all_warnings.append(f"palette: pinned ({len(palette)} colors, {PALETTE_LOCK})")
+ else:
+ palette = build_shared_palette([f for entry in pending for f in entry["frames"]], palette_size)
+ write_pinned_palette(run_dir, palette,
+ f"batch:{','.join(entry['state'] for entry in pending)}")
+ all_warnings.append(f"palette: rebuilt+pinned ({len(palette)} colors → {PALETTE_LOCK})")
+ total_steps = progress_step + len(pending) # 스킵된 행 반영 재산정
+ outline_cfg = fit_config.get("outline", True)
+ for entry in pending:
+ _write_progress(run_dir, "extract", progress_step, total_steps, entry["state"], "pixel unfake")
+ progress_step += 1
+ quantized = [apply_palette(frame, palette) for frame in entry["frames"]]
+ if outline_cfg:
+ strength = 0.62 if outline_cfg is True else float(outline_cfg)
+ quantized = [enforce_outline(frame, strength) for frame in quantized]
+ left, top = row_placement(quantized, cell_width, cell_height, safe_margin_y, pp_scale, fit_config)
+ ground_frames = bool(fit_config.get("ground_frames", True))
+ # alpha-centroid 는 프레임별 가로 배치 — 행 union 공동 left 로는
+ # register_row_frames 의 정합 잔차가 지터로 남는다.
+ per_frame_centroid = str(fit_config.get("align_x", "foot-centroid")).lower() == "alpha-centroid"
+ frames = [
+ place_row_frame(
+ frame, cell_width, cell_height, pp_scale,
+ _alpha_centroid_row_left(frame, cell_width, pp_scale) if per_frame_centroid else left,
+ top, safe_margin_y, ground_frames)
+ for frame in quantized
+ ]
+ # 전/후 비교 쌍둥이: 픽셀 언페이크 프레임의 최종 콘텐츠 bbox 와 같은 풋프린트에
+ # 원본 컴포넌트를 앉힌다 (plain=셀 크기 굽기용, orig=S×셀 표시용). 빈 프레임은
+ # 관측 가능하게 스킵 — 조용한 폴백 없음.
+ plain_frames = []
+ orig_scale = _orig_display_scale(entry["components"], frames)
+ orig_frames = [] if orig_scale > 1 else None
+ input_grids: list[dict | None] = []
+ for index, (component, frame) in enumerate(zip(entry["components"], frames)):
+ frame_bbox = frame.getbbox()
+ if frame_bbox is None:
+ all_warnings.append(
+ f"{entry['state']}: frame {index} is empty — plain/orig twin skipped")
+ plain_frames.append(Image.new("RGBA", (cell_width, cell_height), (0, 0, 0, 0)))
+ if orig_frames is not None:
+ orig_frames.append(Image.new(
+ "RGBA", (cell_width * orig_scale, cell_height * orig_scale), (0, 0, 0, 0)))
+ input_grids.append(None)
+ continue
+ plain, mapping = fit_component_to_bbox(component, cell_width, cell_height, frame_bbox)
+ plain_frames.append(plain)
+ if orig_frames is not None:
+ orig_frames.append(fit_component_to_bbox(
+ component, cell_width, cell_height, frame_bbox, orig_scale)[0])
+ # 검출된 입력 격자(실제 절단선)를 쌍둥이(셀) 좌표로 매핑해 manifest 에 남긴다
+ edges = entry["cut_edges"][index] if index < len(entry["cut_edges"]) else None
+ if edges is not None and mapping is not None:
+ input_grids.append({
+ "x": [round(mapping["left"] + (e - mapping["crop_x"]) * mapping["ratio"], 1)
+ for e in edges[0]],
+ "y": [round(mapping["top"] + (e - mapping["crop_y"]) * mapping["ratio"], 1)
+ for e in edges[1]],
+ })
+ else:
+ input_grids.append(None)
+ finalize_state(entry["state"], frames, entry["frame_count"], entry["method"],
+ plain_frames=plain_frames, orig_frames=orig_frames,
+ input_grids=input_grids, labels=entry.get("labels"),
+ takes=entry.get("takes"))
+ all_warnings.append(
+ "pixel unfake: pitch=%s scale=%dx logical<=%dx%d palette=%d"
+ % (",".join(str(entry["pitch"]) for entry in pending), pp_scale, logical_width, logical_height, len(palette))
+ )
+
+ result = {
+ "ok": not all_errors,
+ "engine": "component-row",
+ "engine_revision": engine_revision(),
+ # 이 생성에 실제로 쓰인 비기본 추출 플래그 — heal_run 재유도가 같은
+ # 조건으로 재현하도록 기록한다 (조건 드리프트 = 조용한 결과 변화 금지).
+ "extract_args": _nondefault_args(args),
+ "run_dir": str(run_dir),
+ "cell": request["cell"],
+ "chroma_key": request["chroma_key"],
+ "rows": rows,
+ "errors": all_errors,
+ "warnings": all_warnings,
+ }
+ all_state_names = set(request["states"])
+ _clear_progress(run_dir)
+ if result["ok"]:
+ # Whole-generation atomicity: canonical frames/ only ever holds a COMPLETE generation.
+ # Swap in the staging generation AND resolve this attempt's target states in the failure
+ # evidence as ONE publish transaction — a subset --states extract does not touch the other
+ # states, so their unresolved failures are preserved (file removed only once nothing
+ # remains, Consistency), and a reader never sees new frames beside a stale failure record.
+ atomic_write_text(frames_root / "frames-manifest.json", json.dumps(result, ensure_ascii=False, indent=2) + "\n")
+ _commit_generation(run_dir, frames_root, result, target, all_state_names)
+ else:
+ # A failed extract — FIRST or re-extract — never publishes a partial/ok:false generation
+ # to canonical frames/ (strict Atomicity: the operation fully succeeds or leaves canonical
+ # state untouched). The per-state failure signal is recorded OUTSIDE frames/ as
+ # extract-failure.json so it stays observable (No Silent Fallback) and still drives the
+ # automatic correction loop (inspect._manifest_state_notes reads it → score → hint →
+ # regenerate). The evidence merges per state, so one state's failure never overwrites
+ # another's still-unresolved failure. A failed re-extract leaves the prior complete
+ # generation byte-intact. Exit code 1 + printed errors signal the failure.
+ _commit_generation(run_dir, None, result, target, all_state_names)
+ shutil.rmtree(frames_root, ignore_errors=True)
+ print(json.dumps({k: v for k, v in result.items() if k != "rows"}, ensure_ascii=False, indent=2))
+ return 0 if result["ok"] else 1
+
+
+
+def _nondefault_args(args: argparse.Namespace) -> dict[str, Any]:
+ """파서 기본값과 다른 플래그만 추린다 (run_dir/states 제외) — manifest 기록용."""
+ diff: dict[str, Any] = {}
+ for action in _build_parser()._actions:
+ dest = action.dest
+ if dest in ("help", "run_dir", "states"):
+ continue
+ if dest == "min_used_pixels" and not getattr(args, "_min_used_pixels_explicit", True):
+ continue # 프로필 유래값 — heal 은 request 의 subject 에서 재해소한다
+ value = getattr(args, dest, None)
+ if value != action.default:
+ diff[dest] = value
+ return diff
+
+
+_ENGINE_REVISION: str | None = None
+_ENGINE_REVISION_KEY: tuple | None = None
+
+
+def engine_revision() -> str:
+ """추출 엔진 리비전 = 엔진 소스 해시. 프레임 파일은 (raw + request + 엔진)의
+ 파생 캐시고 이 값이 캐시 키다 — 행 스탬프와 불일치하면 stale.
+
+ 캐시 키 = 소스 파일 mtime. 프로세스-수명 캐시는 장수 프로세스(큐레이션 서버)가
+ 엔진 갱신 후에도 옛 리비전을 들고 있게 만들어, 새 리비전으로 스탬프하는
+ 서브프로세스 힐과 서로를 stale 로 보는 **힐 무한 루프**를 만들었다
+ (회귀 2026-07-17: 3초 폴링마다 전체 36행 재추출 재점화 — 뷰 빈 화면, maintainer 발견)."""
+ global _ENGINE_REVISION, _ENGINE_REVISION_KEY
+ # The engine revision hashes this module plus layout.py. They no longer sit in
+ # the same folder (extract=frames/, layout=spec/), so resolve layout by its
+ # module file, not as a sibling of __file__.
+ import sprite_gen.spec.layout as _layout_module
+ sources = (Path(__file__), Path(_layout_module.__file__))
+ key = tuple(source.stat().st_mtime_ns for source in sources)
+ if _ENGINE_REVISION is None or _ENGINE_REVISION_KEY != key:
+ digest = hashlib.sha256()
+ for source in sources:
+ digest.update(source.read_bytes())
+ _ENGINE_REVISION = digest.hexdigest()[:12]
+ _ENGINE_REVISION_KEY = key
+ return _ENGINE_REVISION
+
+
+def heal_run(run_dir: Path | str) -> dict[str, Any]:
+ """파생 프레임 캐시의 자가치유 — 소비자(큐레이션 뷰/합성/내보내기) 진입점이 부른다.
+
+ 큐레이션 뷰에는 '재추출' 이라는 개념이 없다 (maintainer 확정 2026-07-14): 뷰가
+ 보여주는 것은 항상 (raw + request + 현재 엔진 + 큐레이션)의 실시간 결과다.
+ frames/ 는 그 파생 캐시일 뿐이므로, 행의 engine_revision 이 현재 엔진과
+ 다르면 raw 에서 조용히 다시 굽는다. raw 가 없는 행은 재료가 없어 재유도할
+ 수 없다 — 지우지도 속이지도 않고 그대로 두되 노트로 관측 가능하게 남긴다.
+ 재추출은 상태별 독립 서브프로세스로 격리해 돌린다 — 한 행의 검증 실패가
+ 다른 행의 스왑을 막지 않고(부분 실패의 전체 연좌 금지, 2026-07-22), 실패한
+ 행은 스테이징+스왑 경로가 이전 세대를 바이트 그대로 남긴다 (Atomicity).
+ """
+ run_dir = Path(run_dir)
+ report: dict[str, Any] = {"healed": [], "kept_stale": [], "notes": []}
+ manifest_path = run_dir / "frames" / "frames-manifest.json"
+ request_path = run_dir / REQUEST_FILENAME
+ if not manifest_path.is_file() or not request_path.is_file():
+ return report
+ manifest = load_frames_manifest(manifest_path)
+ request = load_request(run_dir) # 게이트 경유 — heal 도 은퇴 키 런에서 돈다
+ current = engine_revision()
+ # 확정 행 동결 (maintainer 확정 2026-07-18): curation states.<state>.frozen == true 인
+ # 행은 사용자가 승인·편집을 끝낸 확정본 — 엔진이 바뀌어도 자가치유가 절대
+ # 재유도하지 않는다 (회귀: 서버 가동 중 엔진 편집 → heal 이 확정 down_idle 을
+ # 재양자화해 드리프트). 해제는 사용자가 frozen 을 끄는 것뿐 — 관측 노트로 남긴다.
+ frozen: set[str] = set()
+ curation_path = run_dir / "curation.json"
+ if curation_path.is_file():
+ try:
+ cur_states = json.loads(curation_path.read_text(encoding="utf-8")).get("states", {})
+ frozen = {s for s, e in cur_states.items() if isinstance(e, dict) and e.get("frozen")}
+ except ValueError:
+ pass # 손상 사이드카는 로드 경로가 별도로 보고한다
+ frozen_kept = []
+ for row in manifest.get("rows", []):
+ state = row.get("state")
+ if state not in request.get("states", {}) or row.get("engine_revision") == current:
+ continue
+ if state in frozen:
+ frozen_kept.append(state)
+ continue
+ raws = [raw_rel(request, state)] + [
+ take_raw_rel(request, state, str(take.get("label") or ""))
+ for take in (request["states"][state].get("takes") or [])
+ ]
+ if all((run_dir / rel).is_file() for rel in raws):
+ report["healed"].append(state)
+ else:
+ report["kept_stale"].append(state)
+ if frozen_kept:
+ report["frozen"] = frozen_kept
+ report["notes"].append("frozen rows kept (user-approved, heal skipped): " + ", ".join(frozen_kept))
+ if report["kept_stale"]:
+ report["notes"].append(
+ "stale rows kept as-is (raw missing, cannot re-derive): "
+ + ", ".join(report["kept_stale"]))
+ if report["healed"]:
+ # 서브프로세스로 재추출한다: run-dir 락은 atexit 해제라, 장수 프로세스
+ # (큐레이션 서버)가 인프로세스로 추출하면 락을 영구 보유해 이후의
+ # compose/export 서브프로세스가 전부 죽는다. 자식 프로세스면 락 수명이
+ # 그 실행으로 끝나고, 추출의 SystemExit 도 격리된다.
+ #
+ # 상태별 격리 (2026-07-22): 전체를 한 서브프로세스로 돌리고 exit code
+ # 하나로 판정하면 부분 실패가 전체 실패로 연좌된다 (회귀 synthetic_fixture_a
+ # heal — 검증 실패 6행이 33행 전체를 "재계산 실패"로 묶고 통과 가능한
+ # 27행까지 이전 세대에 남겼다). 상태마다 독립 실행하면 통과 행은 그대로
+ # 스왑되고(추출 커밋은 원래 상태 단위 병합) 실패 행만 failed 로 남는다.
+ # extract-failure.json 병합/해소는 _commit_generation 이 상태 단위로
+ # 처리하므로 durable 재시도 차단 evidence 도 호출 횟수와 무관하게
+ # 미해결 상태 전체를 유지한다.
+ extract_flags: list[str] = []
+ for dest, value in (manifest.get("extract_args") or {}).items():
+ flag = "--" + dest.replace("_", "-")
+ if isinstance(value, bool):
+ if value:
+ extract_flags.append(flag)
+ else:
+ extract_flags.extend([flag, str(value)])
+ # 자식은 부모의 sys.path 조작(스크립트 shim 등)을 상속하지 않는다 —
+ # 패키지 루트를 PYTHONPATH 로 명시해 어디서 불러도 -m 이 뜬다.
+ env = dict(os.environ)
+ env["PYTHONPATH"] = (str(Path(__file__).resolve().parents[1])
+ + os.pathsep + env.get("PYTHONPATH", ""))
+ candidates = report["healed"]
+ report["healed"] = []
+ report["failed"] = []
+ for state in candidates:
+ cmd = [sys.executable, "-m", "sprite_gen.frames.extract",
+ "--run-dir", str(run_dir), "--states", state, *extract_flags]
+ proc = subprocess.run(cmd, capture_output=True, text=True, env=env)
+ if proc.returncode == 0:
+ report["healed"].append(state)
+ else:
+ report["failed"].append(state)
+ tail = (proc.stderr or proc.stdout or "").strip().splitlines()[-3:]
+ report["notes"].append(
+ f"heal re-extract failed for {state} — prior generation kept: "
+ + " | ".join(tail))
+ if not report["failed"]:
+ del report["failed"]
+ return report
+
+
+
+PROGRESS_REL = ".sprite-gen.progress.json"
+
+
+def _write_progress(run_dir: Path, op: str, done: int, total: int, label: str, phase: str) -> None:
+ """오래 걸리는 파이프라인의 잘게 쪼갠 진행도 (maintainer 요청 2026-07-18 "잘게잘게").
+
+ 한 파일 SSoT — 큐레이터가 폴링해 퍼센트로 표시한다. 완료 시 삭제 (아래
+ _clear_progress). 기록 실패는 파이프라인을 막지 않는다 (진행도는 관측용)."""
+ import time as _time
+ try:
+ atomic_write_text(run_dir / PROGRESS_REL, json.dumps({
+ "op": op, "done": done, "total": total, "label": label,
+ "phase": phase, "ts": _time.time()}, ensure_ascii=False))
+ except OSError:
+ pass
+
+
+def _clear_progress(run_dir: Path) -> None:
+ try:
+ (run_dir / PROGRESS_REL).unlink(missing_ok=True)
+ except OSError:
+ pass
+
+
+def run(**kwargs: object):
+ return _run(_namespace_from_kwargs(**kwargs))
+
+def main() -> int:
+ parser = _build_parser()
+ args = parser.parse_args()
+ return _run(args)
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/sprite_gen/frames/segment.py b/sprite_gen/frames/segment.py
new file mode 100644
index 0000000..6345cb5
--- /dev/null
+++ b/sprite_gen/frames/segment.py
@@ -0,0 +1,386 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Projection-profile + DP optimal-cut frame segmentation (opt-in).
+
+Ported from perfectpixel-studio `internal/sprite/segment.go`
+(https://github.com/gykim80/perfectpixel-studio, Copyright (c) gykim80,
+MIT License — 이식 허용, 출처 표기). OCR 라인/단어 분리에서 쓰는
+projection-profile + optimal-cut 기법.
+
+connected-components 추출은 팔·소품이 이웃 프레임과 닿으면 붙은 포즈를
+한 덩어리로 합쳐 프레임 분리가 실패한다. 이 모듈은 컬럼별 알파 질량
+P[x] = Σ_y α(x,y) 의 골(gutter)로 자연 포즈 수를 세고, 포즈가 닿아 골이
+사라졌을 때는 DP 로 `Σ P[cut] + λ·(width−ideal)²` 최소 컷을 찾아
+정확히 기대 프레임 수의 컬럼 세그먼트로 나눈다.
+
+엔진 통합은 `separate_fused_poses` 하나로 한다: 옵트인(sprite-request
+`fit.segmentation: "projection"` 또는 extract CLI `--segmentation
+projection`)일 때만 스트립을 세그먼트 경계에서 갈라 투명 거터를 넣어
+재조립한다. 이후의 connected-components 추출·위성 병합·pixel unfake
+경로는 무변경으로 그대로 동작한다. 기본은 off — 기존 런 골든 재현성
+보존 (No Silent Fallback: 분리 실패는 stderr 로 보고하고 스트립을
+건드리지 않아 하류가 기존 에러로 관측 가능하게 실패한다).
+"""
+
+from __future__ import annotations
+
+import sys
+
+from PIL import Image
+
+# 재조립 시 세그먼트 사이에 넣는 투명 거터 폭(px). 4-연결 flood fill 분리에는
+# 1px 이면 충분하지만 하류 위성 병합 근접 판정이 인접 프레임을 물지 않도록 여유를 둔다.
+_GUTTER = 8
+
+
+def project_alpha(image: Image.Image) -> list[float]:
+ """컬럼별 알파 질량 P[x] = Σ_y α(x,y)."""
+ rgba = image.convert("RGBA")
+ width, height = rgba.size
+ data = rgba.getchannel("A").tobytes()
+ profile = [0.0] * width
+ for y in range(height):
+ row = data[y * width : (y + 1) * width]
+ for x, value in enumerate(row):
+ if value:
+ profile[x] += value
+ return profile
+
+
+def mask_components(mask: list[bool], w: int, h: int, min_area: int = 1,
+ max_area: int | None = None) -> list[tuple[int, int, int, int]]:
+ """불리언 마스크의 4-이웃 연결요소 -> bbox 리스트.
+
+ `extract.connected_components` 는 알파 채널 전용(불투명 덩어리)이라 "어두운
+ 픽셀"처럼 임의 술어로 만든 마스크에는 못 쓴다. 이 함수가 그 자리를 맡는다 —
+ `unpack_atlas` 의 아틀라스 블롭 검출과 `anatomy` 의 눈 후보 검출이 같은 구현을
+ 공유한다 (2026-07-25: anatomy 이식 때 세 번째 사본을 만들지 않으려 여기로 옮겼다).
+
+ `max_area` 는 **너무 큰 덩어리를 아예 후보에서 뺀다**. 눈 검출처럼 "작고 컴팩트한
+ 것만" 찾는 쪽은 이 상한이 있어야 아웃라인·팔 같은 큰 어두운 영역이 걸러진다 —
+ bbox 만으로 사후 필터하면 픽셀 수가 아니라 외접 사각형을 재게 되어 판정이 달라진다."""
+ visited = bytearray(len(mask))
+ boxes: list[tuple[int, int, int, int]] = []
+ for seed in range(len(mask)):
+ if not mask[seed] or visited[seed]:
+ continue
+ stack = [seed]
+ visited[seed] = 1
+ minx = miny = 1 << 30
+ maxx = maxy = -1
+ area = 0
+ while stack:
+ cur = stack.pop()
+ area += 1
+ x, y = cur % w, cur // w
+ minx, miny, maxx, maxy = min(minx, x), min(miny, y), max(maxx, x), max(maxy, y)
+ if x > 0 and mask[cur - 1] and not visited[cur - 1]:
+ visited[cur - 1] = 1; stack.append(cur - 1)
+ if x < w - 1 and mask[cur + 1] and not visited[cur + 1]:
+ visited[cur + 1] = 1; stack.append(cur + 1)
+ if y > 0 and mask[cur - w] and not visited[cur - w]:
+ visited[cur - w] = 1; stack.append(cur - w)
+ if y < h - 1 and mask[cur + w] and not visited[cur + w]:
+ visited[cur + w] = 1; stack.append(cur + w)
+ if area >= min_area and (max_area is None or area <= max_area):
+ boxes.append((minx, miny, maxx + 1, maxy + 1))
+ return boxes
+
+
+def smooth_profile(profile: list[float], window: int) -> list[float]:
+ """박스 이동평균으로 프로파일을 평활한다 (압축 잡음/얇은 틈 억제)."""
+ if window < 1 or not profile:
+ return profile
+ length = len(profile)
+ half = window // 2
+ output = [0.0] * length
+ for i in range(length):
+ lo = max(0, i - half)
+ hi = min(length - 1, i + half)
+ output[i] = sum(profile[lo : hi + 1]) / (hi - lo + 1)
+ return output
+
+
+def content_runs(
+ profile: list[float], eps: float, peak_min: float, min_width: int
+) -> list[tuple[int, int]]:
+ """P 가 eps 를 넘는 연속 구간(포즈) [start, end). 좁거나 봉우리가 낮은 구간은 잡티로 버린다."""
+ runs: list[tuple[int, int]] = []
+ i = 0
+ length = len(profile)
+ while i < length:
+ if profile[i] <= eps:
+ i += 1
+ continue
+ j = i
+ peak = 0.0
+ while j < length and profile[j] > eps:
+ if profile[j] > peak:
+ peak = profile[j]
+ j += 1
+ if j - i >= min_width and peak >= peak_min:
+ runs.append((i, j))
+ i = j
+ return runs
+
+
+def run_mass(profile: list[float], span: tuple[int, int]) -> float:
+ start, end = span
+ return sum(profile[start : min(end, len(profile))])
+
+
+def drop_minor_runs(
+ profile: list[float], runs: list[tuple[int, int]], fraction: float
+) -> list[tuple[int, int]]:
+ """최대 런 질량의 fraction 미만인 런(원거리 잔여물/잡티)을 제거한다.
+
+ 연결요소 방식의 "최대 blob 면적 대비 시드 임계값" 가드와 같은 취지.
+ """
+ if len(runs) <= 1:
+ return runs
+ max_mass = max(run_mass(profile, run) for run in runs)
+ threshold = max_mass * fraction
+ return [run for run in runs if run_mass(profile, run) >= threshold]
+
+
+def median_run_width(runs: list[tuple[int, int]]) -> float:
+ """런 폭의 중앙값 (전형적 단일 포즈 폭 추정)."""
+ if not runs:
+ return 0.0
+ widths = sorted(end - start for start, end in runs)
+ return float(widths[len(widths) // 2])
+
+
+def pose_peaks(profile: list[float], start: int, end: int) -> list[int]:
+ """[start, end) 구간에서 prominence(돌출도) 기준의 강한 봉우리(=포즈) 컬럼.
+
+ 봉우리 후보는 런 최대값의 45% 이상인 국소 최대이고, 더 높은 봉우리와의
+ 사이 골이 충분히 깊어야(자기 높이의 62% 미만으로 내려가야) 별개 포즈로 인정된다.
+ """
+ if end - start < 3:
+ return [(start + end) // 2]
+ run_max = max(profile[start:end])
+ if run_max <= 0:
+ return [(start + end) // 2]
+ candidates = [
+ x
+ for x in range(start + 1, end - 1)
+ if profile[x] >= profile[x - 1]
+ and profile[x] > profile[x + 1]
+ and profile[x] >= 0.45 * run_max
+ ]
+ if not candidates:
+ return [(start + end) // 2]
+ keep: list[int] = []
+ for peak in candidates:
+ prominent = True
+ for other in candidates:
+ if other == peak or profile[other] < profile[peak]:
+ continue # 자기보다 높은 봉우리에 대해서만 골 깊이 검사
+ lo, hi = (peak, other) if peak < other else (other, peak)
+ valley = min(profile[lo : hi + 1])
+ if valley > 0.62 * profile[peak]: # 사이 골이 얕다 → 같은 포즈의 일부
+ prominent = False
+ break
+ if prominent:
+ keep.append(peak)
+ return keep or [candidates[0]]
+
+
+def dp_n_cut(profile: list[float], x0: int, x1: int, count: int) -> list[int] | None:
+ """[x0, x1) 구간을 정확히 count 개 세그먼트로 나누는 count-1 개 컷 컬럼.
+
+ 비용 = Σ P[cut] (질량이 적은 곳을 자르는 게 저렴) + 폭 정규화(이상폭에서
+ 벗어날수록 벌점). 닿아 있는 포즈를 강제로 기대 개수로 분리할 때 쓴다.
+ """
+ if count <= 1 or x1 - x0 < count:
+ return None
+ width = x1 - x0
+ ideal = width / count
+ min_width = max(2, int(ideal * 0.45))
+ lam = 0.0015 # 폭 정규화 가중 (질량 비용 대비)
+ infinity = 1e18
+
+ cuts = count - 1
+ cost = [[infinity] * (x1 + 1) for _ in range(cuts + 1)]
+ previous = [[-1] * (x1 + 1) for _ in range(cuts + 1)]
+ cost[0][x0] = 0.0 # 가상 시작 경계
+ for k in range(1, cuts + 1):
+ lo = x0 + (k - 1) * min_width
+ prior_row = cost[k - 1]
+ row = cost[k]
+ back = previous[k]
+ for x in range(x0 + k * min_width, x1 - (cuts - k + 1) * min_width + 1):
+ best = infinity
+ best_previous = -1
+ mass = profile[x]
+ for xp in range(lo, x - min_width + 1):
+ base = prior_row[xp]
+ if base >= 1e17:
+ continue
+ deviation = (x - xp) - ideal
+ candidate = base + mass + lam * deviation * deviation
+ if candidate < best:
+ best = candidate
+ best_previous = xp
+ row[x] = best
+ back[x] = best_previous
+ best_end, best_cost = -1, infinity
+ for x in range(x0 + cuts * min_width, x1 - min_width + 1):
+ deviation = (x1 - x) - ideal
+ candidate = cost[cuts][x] + lam * deviation * deviation
+ if candidate < best_cost:
+ best_cost, best_end = candidate, x
+ if best_end < 0:
+ return None
+ output = [0] * cuts
+ x = best_end
+ for k in range(cuts, 0, -1):
+ output[k - 1] = x
+ x = previous[k][x]
+ if x < 0:
+ return None
+ return output
+
+
+def split_range(profile: list[float], start: int, end: int, count: int) -> list[tuple[int, int]]:
+ """[start, end) 구간을 DP 최소 절단으로 count 개 세그먼트로 나눈다 (실패 시 균등)."""
+ if count <= 1 or end - start < count:
+ return [(start, end)]
+ cuts = dp_n_cut(profile, start, end, count)
+ if cuts is not None and len(cuts) == count - 1:
+ spans: list[tuple[int, int]] = []
+ anchor = start
+ for cut in cuts:
+ spans.append((anchor, cut))
+ anchor = cut
+ spans.append((anchor, end))
+ return spans
+ return [
+ (start + (end - start) * i // count, start + (end - start) * (i + 1) // count)
+ for i in range(count)
+ ]
+
+
+def segment_strip(image: Image.Image, expected: int) -> tuple[list[tuple[int, int]], int]:
+ """스트립을 expected 개 컬럼 세그먼트로 나눈다. 반환 = (세그먼트, 자연 포즈 수).
+
+ 자연 포즈 수(강제 복구 전 추정치)가 expected 와 같으면 골(gutter) 중심에서
+ 깔끔히 잘리고, 아니면 DP 로 expected 개를 강제 분할한다. 강제 분할이
+ 불가능하면(폭 부족) 추정 세그먼트를 그대로 반환한다 — 호출자가 개수
+ 불일치를 관측 가능하게 처리한다.
+ """
+ width = image.width
+ if width == 0 or expected < 1:
+ return [], 0
+ raw = project_alpha(image)
+ window = max(3, width // 220)
+ profile = smooth_profile(raw, window)
+ peak_max = max(profile, default=0.0)
+ if peak_max <= 0:
+ return [], 0
+ eps = 0.045 * peak_max
+ peak_min = 0.18 * peak_max
+ min_run = max(4, width // 100)
+ runs = content_runs(profile, eps, peak_min, min_run)
+ runs = drop_minor_runs(profile, runs, 0.20)
+ if not runs:
+ return [], 0
+
+ # 런마다 "토르소 봉우리(prominence peak)" 수로 포즈 수를 추정하되, 런 폭으로
+ # 상한을 둔다. 봉우리는 "어디서 자를지", 폭은 "몇 개로 자를지"를 정한다:
+ # 발차기처럼 한 포즈가 토르소+뻗은 다리로 두 봉우리를 만들어도, 런 폭이 단일
+ # 포즈 폭(중앙값)이면 1개로 묶어 과분할을 막는다. 닿아 넓어진 런만 그만큼 쪼갠다.
+ med = median_run_width(runs)
+ width_total = float(sum(end - start for start, end in runs))
+ segments: list[tuple[int, int]] = []
+ for start, end in runs:
+ peak_count = len(pose_peaks(profile, start, end))
+ if len(runs) > 1 and med > 0:
+ max_by_width = max(1, int((end - start) / med + 0.5))
+ if peak_count > max_by_width:
+ peak_count = max_by_width
+ # 포즈 사이 간격이 거의 없어(overlapping) 봉우리가 1개뿐이지만
+ # 런 폭이 평균 포즈 폭의 1.45배 이상이면 강제로 2개로 의심한다.
+ if peak_count == 1 and (end - start) > med * 1.45:
+ peak_count = 2
+ if peak_count <= 1:
+ segments.append((start, end))
+ else:
+ segments.extend(split_range(profile, start, end, peak_count))
+
+ natural = len(segments)
+ # 강제 복구: 감지된 수가 기대와 다르고, 전체 콘텐츠 폭이 기대 개수의
+ # 최소 폭을 감당할 수 있다면 전체 strip 을 DP 로 expected 개 분할.
+ # AI 가 포즈를 gutter 없이 완전히 붙여 그리는 경우를 방어한다.
+ if natural != expected and width_total / expected >= 16 and width // expected >= 16:
+ segments = split_range(profile, 0, width, expected)
+ return segments, natural
+
+
+def segment_boundaries(image: Image.Image, expected: int) -> tuple[list[int] | None, int]:
+ """스트립 전체를 타일링하는 expected-1 개 컷 컬럼. 실패 시 (None, 자연 포즈 수).
+
+ 세그먼트 사이 골은 골 중심에서 자르고, DP 컷(인접 세그먼트가 경계를 공유)은
+ 그 컬럼 그대로 쓴다. 경계 밖 콘텐츠(잡티로 버려진 런)도 어느 한 슬라이스에
+ 남도록 전체 폭을 타일링한다 — 버릴지는 하류 위성 병합 로직이 판단한다.
+ """
+ segments, natural = segment_strip(image, expected)
+ if len(segments) != expected:
+ return None, natural
+ boundaries = [
+ (left_end + right_start) // 2
+ for (_, left_end), (right_start, _) in zip(segments, segments[1:])
+ ]
+ width = image.width
+ if any(not 0 < cut < width for cut in boundaries) or any(
+ later <= earlier for earlier, later in zip(boundaries, boundaries[1:])
+ ):
+ return None, natural
+ return boundaries, natural
+
+
+def resolve_segmentation(fit: dict | None, cli_mode: str | None) -> str:
+ """분리 모드 SSoT = sprite-request `fit.segmentation`, CLI 는 명시 override 만."""
+ if cli_mode:
+ return str(cli_mode).lower()
+ return str((fit or {}).get("segmentation", "components")).lower()
+
+
+def separate_fused_poses(
+ strip: Image.Image,
+ frame_count: int,
+ fit: dict | None = None,
+ cli_mode: str | None = None,
+ label: str = "strip",
+) -> Image.Image:
+ """옵트인 융착 포즈 분리 훅 — 활성일 때만 스트립을 갈라 거터를 넣어 재조립한다.
+
+ 분리가 기대 개수를 못 내면 스트립을 건드리지 않고 stderr 로 보고한다 —
+ 하류 connected-components 추출이 기존 에러로 관측 가능하게 실패한다.
+ """
+ if resolve_segmentation(fit, cli_mode) != "projection":
+ return strip
+ boundaries, natural = segment_boundaries(strip, frame_count)
+ if boundaries is None:
+ print(
+ f"[segment] {label}: projection segmentation found {natural} pose(s) "
+ f"for expected {frame_count} — strip left untouched",
+ file=sys.stderr,
+ )
+ return strip
+ width, height = strip.size
+ edges = [0, *boundaries, width]
+ slices = [strip.crop((edges[i], 0, edges[i + 1], height)) for i in range(len(edges) - 1)]
+ total_width = sum(piece.width for piece in slices) + _GUTTER * (len(slices) + 1)
+ rebuilt = Image.new("RGBA", (total_width, height), (0, 0, 0, 0))
+ x = _GUTTER
+ for piece in slices:
+ rebuilt.paste(piece, (x, 0))
+ x += piece.width + _GUTTER
+ forced = ", DP-forced" if natural != frame_count else ""
+ print(
+ f"[segment] {label}: projection split at columns {boundaries} "
+ f"(natural poses={natural}{forced})",
+ file=sys.stderr,
+ )
+ return rebuilt
diff --git a/sprite_gen/frames/slice_sheet.py b/sprite_gen/frames/slice_sheet.py
new file mode 100644
index 0000000..6951aeb
--- /dev/null
+++ b/sprite_gen/frames/slice_sheet.py
@@ -0,0 +1,325 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Slice a multi-figure grid sheet into per-cell standing cuts (tachi-e).
+
+One generated image contains a COLSxROWS grid of the same character in
+different expressions/poses on a flat chroma background. This module turns
+that sheet into per-cell RGBA cuts on a fixed canvas with a shared feet
+baseline and a normalized subject height.
+
+Alpha truth is `sprite_gen.frames.extract.remove_chroma_background` (the 4-pass
+chain: hard key cut -> key-depth in-band unmix -> soft-alpha unmix ->
+trapped-spill despill). This module owns only cell geometry:
+
+- whole-sheet connected components assigned to grid cells by centroid, so a
+ figure's own cape/prop keeps its overflow past the cell border while a
+ neighbour's overflow stays with the neighbour;
+- components wider/taller than ~1.5 cells (figures fused through touching
+ props) are split at cell borders and re-labelled *inside* each cell, so a
+ neighbour's overhang does not stay fused to the cell's main figure;
+- small split fragments touching the cell border are dropped as neighbour
+ debris, while detached effects (hearts, sparkles, ZZZ) survive because
+ they sit inside the cell;
+- every cell's main figure is scaled so its height equals ``target_height``
+ (per-cell normalization — generators routinely draw rows at different
+ sizes) and its feet rest on ``baseline_y`` of the output canvas.
+
+Field lessons baked in here (a cut-in overhaul, 2026-07-09):
+sheet-wide max-height scaling preserves the generator's size jitter, grid
+cropping without component logic imports neighbour fragments, and skipping
+the in-cell re-label leaves a neighbour's hair fused to the figure.
+"""
+
+from __future__ import annotations
+
+import argparse
+from collections import deque
+from pathlib import Path
+
+from PIL import Image
+
+from sprite_gen.frames.extract import remove_chroma_background
+
+CHROMA_KEYS = {
+ "magenta": (255, 0, 255),
+ "green": (0, 255, 0),
+}
+
+DEFAULT_KEY_THRESHOLD = 96.0
+DEFAULT_FRINGE_KEY_THRESHOLD = 180.0
+DEFAULT_FRINGE_DELTA = 18.0
+DEFAULT_NOISE_MIN = 60
+DEFAULT_DEBRIS_FRACTION = 0.30
+MERGED_SPAN_FACTOR = 1.5
+
+
+def parse_chroma_key(value: str) -> tuple[int, int, int]:
+ name = value.strip().lower()
+ if name in CHROMA_KEYS:
+ return CHROMA_KEYS[name]
+ text = name.lstrip("#")
+ if len(text) == 6:
+ return tuple(int(text[i : i + 2], 16) for i in (0, 2, 4)) # type: ignore[return-value]
+ raise ValueError(f"unsupported chroma key {value!r}; use magenta, green, or #RRGGBB")
+
+
+def _components(alpha: bytearray, width: int, height: int) -> list[list[int]]:
+ label = bytearray(width * height)
+ comps: list[list[int]] = []
+ for start in range(width * height):
+ if not alpha[start] or label[start]:
+ continue
+ queue = deque([start])
+ label[start] = 1
+ pixels: list[int] = []
+ while queue:
+ index = queue.popleft()
+ pixels.append(index)
+ x, y = index % width, index // width
+ for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1)):
+ nx, ny = x + dx, y + dy
+ if 0 <= nx < width and 0 <= ny < height:
+ other = ny * width + nx
+ if alpha[other] and not label[other]:
+ label[other] = 1
+ queue.append(other)
+ comps.append(pixels)
+ return comps
+
+
+def _relabel_within_cell(part: list[int], width: int) -> list[list[int]]:
+ """Re-run connectivity inside one cell's pixel set.
+
+ After a merged component is split at cell borders, the cell's figure and
+ a neighbour's overhang are disconnected *within* the cell even though
+ they were one component sheet-wide.
+ """
+ part_set = set(part)
+ seen: set[int] = set()
+ subs: list[list[int]] = []
+ for start in part:
+ if start in seen:
+ continue
+ queue = deque([start])
+ seen.add(start)
+ sub: list[int] = []
+ while queue:
+ index = queue.popleft()
+ sub.append(index)
+ x, y = index % width, index // width
+ for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1)):
+ other = (y + dy) * width + (x + dx)
+ if other in part_set and other not in seen:
+ seen.add(other)
+ queue.append(other)
+ subs.append(sub)
+ return subs
+
+
+def slice_sheet(
+ sheet: Path,
+ out_dir: Path,
+ chroma_key: tuple[int, int, int],
+ *,
+ grid: tuple[int, int] = (3, 2),
+ names: list[str] | None = None,
+ prefix: str = "",
+ canvas: tuple[int, int] = (512, 768),
+ baseline_y: float = 725.0,
+ target_height: float = 645.0,
+ key_threshold: float = DEFAULT_KEY_THRESHOLD,
+ fringe_key_threshold: float = DEFAULT_FRINGE_KEY_THRESHOLD,
+ fringe_delta: float = DEFAULT_FRINGE_DELTA,
+ unmix_reach: int = 4,
+ spill_max_fraction: float = 0.005,
+ noise_min: int = DEFAULT_NOISE_MIN,
+ debris_fraction: float = DEFAULT_DEBRIS_FRACTION,
+) -> list[Path]:
+ cols, rows = grid
+ cell_count = cols * rows
+ if names is not None and len(names) != cell_count:
+ raise ValueError(f"--names needs exactly {cell_count} entries for grid {cols}x{rows}")
+ if target_height > baseline_y:
+ raise ValueError("target height must fit above the feet baseline")
+
+ rgba = remove_chroma_background(
+ Image.open(sheet).convert("RGBA"),
+ chroma_key,
+ key_threshold,
+ fringe_key_threshold,
+ fringe_delta,
+ unmix_reach=unmix_reach,
+ spill_max_fraction=spill_max_fraction,
+ )
+ width, height = rgba.size
+ pixels = rgba.load()
+ cell_w, cell_h = width / cols, height / rows
+
+ alpha = bytearray(width * height)
+ for y in range(height):
+ for x in range(width):
+ if pixels[x, y][3] > 0:
+ alpha[y * width + x] = 1
+
+ def cell_of(index: int) -> int:
+ return min(int((index // width) // cell_h), rows - 1) * cols + min(int((index % width) // cell_w), cols - 1)
+
+ buckets: dict[int, list[list[int]]] = {i: [] for i in range(cell_count)}
+ for comp in _components(alpha, width, height):
+ if len(comp) < noise_min:
+ continue
+ xs = [i % width for i in comp]
+ ys = [i // width for i in comp]
+ if (max(xs) - min(xs)) > cell_w * MERGED_SPAN_FACTOR or (max(ys) - min(ys)) > cell_h * MERGED_SPAN_FACTOR:
+ parts: dict[int, list[int]] = {}
+ for index in comp:
+ parts.setdefault(cell_of(index), []).append(index)
+ for cell, part in parts.items():
+ if len(part) < noise_min:
+ continue
+ for sub in _relabel_within_cell(part, width):
+ if len(sub) >= noise_min:
+ buckets[cell].append(sub)
+ continue
+ centroid = min(int((sum(ys) / len(ys)) // cell_h), rows - 1) * cols + min(
+ int((sum(xs) / len(xs)) // cell_w), cols - 1
+ )
+ buckets[centroid].append(comp)
+
+ # Neighbour-debris rule: fragments touching the cell border and much
+ # smaller than the cell's main figure are overhang from a neighbour.
+ for cell, comps_in in buckets.items():
+ if len(comps_in) < 2:
+ continue
+ main_size = max(len(c) for c in comps_in)
+ row, col = divmod(cell, cols)
+ bx0, bx1 = col * cell_w, (col + 1) * cell_w
+ by0, by1 = row * cell_h, (row + 1) * cell_h
+ kept = []
+ for comp in comps_in:
+ if len(comp) < main_size * debris_fraction:
+ touches = any(
+ abs(i % width - bx0) < 2
+ or abs(i % width - bx1) < 2
+ or abs(i // width - by0) < 2
+ or abs(i // width - by1) < 2
+ for i in comp
+ )
+ if touches:
+ continue
+ kept.append(comp)
+ buckets[cell] = kept
+
+ out_dir.mkdir(parents=True, exist_ok=True)
+ written: list[Path] = []
+ for cell in range(cell_count):
+ comps_in = buckets[cell]
+ if not comps_in:
+ raise SystemExit(f"{sheet}: cell {cell} has no subject after extraction")
+ main = max(comps_in, key=len)
+ main_ys = [i // width for i in main]
+ main_xs = [i % width for i in main]
+ main_top, main_bottom = min(main_ys), max(main_ys)
+ scale = target_height / (main_bottom - main_top + 1)
+
+ all_pixels = {i for comp in comps_in for i in comp}
+ xs = [i % width for i in all_pixels]
+ ys = [i // width for i in all_pixels]
+ x0, x1, y0, y1 = min(xs), max(xs), min(ys), max(ys)
+ piece = Image.new("RGBA", (x1 - x0 + 1, y1 - y0 + 1), (0, 0, 0, 0))
+ piece_px = piece.load()
+ for index in all_pixels:
+ x, y = index % width, index // width
+ piece_px[x - x0, y - y0] = pixels[x, y]
+ new_size = (max(1, round(piece.size[0] * scale)), max(1, round(piece.size[1] * scale)))
+ piece = piece.resize(new_size, Image.LANCZOS)
+
+ main_center_x = (min(main_xs) + max(main_xs)) / 2
+ out = Image.new("RGBA", canvas, (0, 0, 0, 0))
+ offset_x = round(canvas[0] / 2 - (main_center_x - x0) * scale)
+ offset_y = round(baseline_y - (main_bottom - y0 + 1) * scale)
+ out.alpha_composite(piece, (max(0, offset_x), max(0, offset_y)))
+
+ name = names[cell] if names else f"cell-{cell}"
+ path = out_dir / f"{prefix}{name}.png"
+ out.save(path)
+ written.append(path)
+ print(
+ f"{sheet.name} cell{cell} -> {path.name} "
+ f"main_h {main_bottom - main_top + 1} -> {round((main_bottom - main_top + 1) * scale)} "
+ f"comps {len(comps_in)}"
+ )
+ return written
+
+
+def run(
+ *,
+ sheet: Path,
+ out_dir: Path,
+ chroma_key: str,
+ grid: tuple[int, int] = (3, 2),
+ names: str | None = None,
+ prefix: str = "",
+ cell_width: int = 512,
+ cell_height: int = 768,
+ baseline_y: float = 725.0,
+ target_height: float = 645.0,
+ key_threshold: float = DEFAULT_KEY_THRESHOLD,
+ fringe_key_threshold: float = DEFAULT_FRINGE_KEY_THRESHOLD,
+ fringe_delta: float = DEFAULT_FRINGE_DELTA,
+ fringe_unmix_reach: int = 4,
+ spill_max_fraction: float = 0.005,
+ noise_min: int = DEFAULT_NOISE_MIN,
+ debris_fraction: float = DEFAULT_DEBRIS_FRACTION,
+) -> int:
+ name_list = [part.strip() for part in names.split(",") if part.strip()] if names else None
+ slice_sheet(
+ sheet,
+ out_dir,
+ parse_chroma_key(chroma_key),
+ grid=grid,
+ names=name_list,
+ prefix=prefix,
+ canvas=(cell_width, cell_height),
+ baseline_y=baseline_y,
+ target_height=target_height,
+ key_threshold=key_threshold,
+ fringe_key_threshold=fringe_key_threshold,
+ fringe_delta=fringe_delta,
+ unmix_reach=fringe_unmix_reach,
+ spill_max_fraction=spill_max_fraction,
+ noise_min=noise_min,
+ debris_fraction=debris_fraction,
+ )
+ return 0
+
+
+def _parse_grid(value: str) -> tuple[int, int]:
+ cols, rows = value.lower().split("x")
+ return int(cols), int(rows)
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
+ parser.add_argument("--sheet", required=True, type=Path)
+ parser.add_argument("--out-dir", required=True, type=Path)
+ parser.add_argument("--chroma-key", required=True, help="magenta, green, or #RRGGBB")
+ parser.add_argument("--grid", type=_parse_grid, default=(3, 2), help="COLSxROWS, default 3x2")
+ parser.add_argument("--names", help="comma-separated output names, one per cell in reading order")
+ parser.add_argument("--prefix", default="")
+ parser.add_argument("--cell-width", type=int, default=512)
+ parser.add_argument("--cell-height", type=int, default=768)
+ parser.add_argument("--baseline-y", type=float, default=725.0)
+ parser.add_argument("--target-height", type=float, default=645.0)
+ parser.add_argument("--key-threshold", type=float, default=DEFAULT_KEY_THRESHOLD)
+ parser.add_argument("--fringe-key-threshold", type=float, default=DEFAULT_FRINGE_KEY_THRESHOLD)
+ parser.add_argument("--fringe-delta", type=float, default=DEFAULT_FRINGE_DELTA)
+ parser.add_argument("--fringe-unmix-reach", type=int, default=4)
+ parser.add_argument("--spill-max-fraction", type=float, default=0.005)
+ parser.add_argument("--noise-min", type=int, default=DEFAULT_NOISE_MIN)
+ parser.add_argument("--debris-fraction", type=float, default=DEFAULT_DEBRIS_FRACTION)
+ args = parser.parse_args(argv)
+ return run(**vars(args))
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/sprite_gen/frames/unpack_atlas.py b/sprite_gen/frames/unpack_atlas.py
new file mode 100644
index 0000000..ac2ee68
--- /dev/null
+++ b/sprite_gen/frames/unpack_atlas.py
@@ -0,0 +1,630 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Unpack a composed sprite sheet back into a curator-ready run directory.
+
+This is the inverse of `compose_sprite_atlas.py`. When only the combined
+`sprite-sheet-alpha.png` (+ optional manifest) survives — for example a deployed
+asset whose original `frames/` source is gone — this rebuilds the per-frame
+editable representation so the curation webview can open it.
+
+Layout source priority (explicit wins, auto-detect is the no-instruction
+default — and the chosen path is always reported, never silent):
+
+ 1. --grid <cols>x<rows> a human said the grid; slice uniform cells (position-faithful).
+ 2. --manifest <json> read exact frame rectangles from the manifest.
+ 3. auto-detect (default) read the atlas alpha and cut on transparent gutters.
+
+Output (a normal sprite-gen run dir):
+
+ <out-dir>/
+ sprite-request.json synthesized recipe (fps/loop are defaults unless a manifest had them)
+ frames/<state>/frame-N.png
+ frames/frames-manifest.json
+ unpack-source.json provenance + original manifest format, for a future writeback
+
+Then: serve_curation.py --run-dir <out-dir>
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import shutil
+from pathlib import Path
+from typing import Any
+
+from PIL import Image
+
+from sprite_gen.curate.curation import imported_ref_role
+from sprite_gen.spec.runio import (
+ LOCK_FILENAME,
+ acquire_run_dir_lock,
+ atomic_save_image,
+ atomic_write_text,
+ publish_guard,
+ relative_posix,
+)
+from sprite_gen.frames.segment import mask_components
+
+ALPHA_THRESHOLD = 16 # a pixel counts as content above this alpha
+MIN_GUTTER = 1 # a fully-empty line of >= this many px separates frames
+
+
+# --- auto-detect (visual blob clustering) -----------------------------------
+
+def auto_detect(atlas: Image.Image) -> tuple[list[dict[str, Any]], tuple[int, int]]:
+ """Read the sheet visually: find content blobs, cluster them into a grid.
+
+ Connected components survive a character's internal transparency (a single
+ pose stays one blob), which is why this is far more robust on packed grids
+ than cutting on transparent gutters. Blobs are clustered into rows by their
+ vertical center, then into frames within a row by horizontal overlap.
+
+ Returns (states, cell_size). Each frame rect is the blob's content bbox;
+ write_run centers it in the cell.
+ """
+ scale = max(1, max(atlas.width, atlas.height) // 600) # downsample for speed
+ sw, sh = atlas.width // scale, atlas.height // scale
+ small = atlas.getchannel("A").resize((sw, sh), Image.BILINEAR)
+ mask = [b > ALPHA_THRESHOLD for b in small.tobytes()] # 'L' mode: 1 byte/px
+ boxes_small = mask_components(mask, sw, sh, min_area=max(6, (sw * sh) // 4000))
+ if not boxes_small:
+ raise SystemExit("auto-detect found no content blobs in the atlas")
+
+ # map blob bboxes back to full resolution
+ boxes = [(x0 * scale, y0 * scale, x1 * scale, y1 * scale) for (x0, y0, x1, y1) in boxes_small]
+ heights = sorted(y1 - y0 for _x0, y0, _x1, y1 in boxes)
+ widths = sorted(x1 - x0 for x0, _y0, x1, _y1 in boxes)
+ med_h = heights[len(heights) // 2]
+ med_w = widths[len(widths) // 2]
+
+ # cluster into rows by vertical center
+ boxes.sort(key=lambda b: (b[1] + b[3]) / 2)
+ rows: list[list[tuple[int, int, int, int]]] = []
+ row_tol = med_h * 0.6
+ for box in boxes:
+ cy = (box[1] + box[3]) / 2
+ if rows and abs(cy - sum((b[1] + b[3]) / 2 for b in rows[-1]) / len(rows[-1])) <= row_tol:
+ rows[-1].append(box)
+ else:
+ rows.append([box])
+
+ states: list[dict[str, Any]] = []
+ max_w = max_h = 0
+ for row_index, row_boxes in enumerate(rows):
+ row_boxes.sort(key=lambda b: b[0])
+ # merge horizontally overlapping / near blobs into one frame
+ frames: list[list[int]] = []
+ gap = med_w * 0.3
+ for box in row_boxes:
+ if frames and box[0] - frames[-1][2] <= gap:
+ f = frames[-1]
+ f[0], f[1] = min(f[0], box[0]), min(f[1], box[1])
+ f[2], f[3] = max(f[2], box[2]), max(f[3], box[3])
+ else:
+ frames.append(list(box))
+ rects = []
+ for f in frames:
+ rect = (f[0], f[1], f[2] - f[0], f[3] - f[1])
+ rects.append(rect)
+ max_w, max_h = max(max_w, rect[2]), max(max_h, rect[3])
+ if rects:
+ states.append({"name": f"row-{row_index}", "rects": rects})
+
+ if max_w == 0 or max_h == 0:
+ raise SystemExit("auto-detect could not size any frame")
+ cell = (max_w + 8, max_h + 8) # pad so centered content is not flush to the edge
+ return states, cell
+
+
+# --- explicit layout sources ------------------------------------------------
+
+def grid_layout(atlas: Image.Image, cols: int, rows: int) -> tuple[list[dict[str, Any]], tuple[int, int]]:
+ cell_w = atlas.width // cols
+ cell_h = atlas.height // rows
+ states = []
+ for r in range(rows):
+ rects = []
+ for c in range(cols):
+ rect = (c * cell_w, r * cell_h, cell_w, cell_h)
+ crop = atlas.crop((rect[0], rect[1], rect[0] + cell_w, rect[1] + cell_h))
+ if crop.getchannel("A").getbbox() is None:
+ continue # skip empty trailing cells
+ rects.append(rect)
+ if rects:
+ states.append({"name": f"row-{r}", "rects": rects})
+ return states, (cell_w, cell_h)
+
+
+def manifest_layout(
+ manifest: dict[str, Any],
+ direction: str | None,
+) -> tuple[list[dict[str, Any]], tuple[int, int], str, dict[str, Any]]:
+ """Resolve frame rectangles from a known manifest format.
+
+ Returns (states, cell, atlas_filename, per_state_meta).
+ """
+ cell = manifest.get("cell", {})
+ cell_w = int(cell.get("width", cell.get("size", 0)))
+ cell_h = int(cell.get("height", cell.get("size", 0)))
+
+ # compose-format: explicit frame_layout rectangles
+ if "frame_layout" in manifest and manifest["frame_layout"].get("rows"):
+ fl = manifest["frame_layout"]
+ cell_w = cell_w or fl.get("cellWidth", 0)
+ cell_h = cell_h or fl.get("cellHeight", 0)
+ states = []
+ meta = {}
+ anim = manifest.get("animation", {}).get("rows", {})
+ for state, rects in fl["rows"].items():
+ states.append({"name": state, "rects": [(r["x"], r["y"], r["w"], r["h"]) for r in rects]})
+ meta[state] = {"fps": anim.get(state, {}).get("fps", 6), "loop": anim.get(state, {}).get("loop", True)}
+ atlas_file = manifest.get("game_input") or manifest.get("sprite_sheet_alpha")
+ return states, (cell_w, cell_h), atlas_file, meta
+
+ # archive-2dir-mirror / grid-row format: rows carry {row, frames, fps, loop}
+ cols = int(cell.get("columns", 0)) or None
+ rows_src = None
+ atlas_file = None
+ if "directions" in manifest:
+ directions = manifest["directions"]
+ chosen = direction or next(iter(directions))
+ if chosen not in directions:
+ raise SystemExit(f"direction '{chosen}' not in manifest; have {list(directions)}")
+ rows_src = directions[chosen]["rows"]
+ atlas_file = directions[chosen]["sprite_sheet"]
+ elif manifest.get("animation", {}).get("rows"):
+ rows_src = {k: v for k, v in manifest["animation"]["rows"].items()}
+ atlas_file = manifest.get("game_input") or manifest.get("sprite_sheet_alpha")
+
+ if not rows_src:
+ raise SystemExit("manifest has no frame_layout, directions, or animation rows to read")
+ if not (cell_w and cell_h):
+ raise SystemExit("manifest cell width/height missing; pass --cell WxH")
+
+ states = []
+ meta = {}
+ for state, info in rows_src.items():
+ row = int(info["row"])
+ frames = int(info["frames"])
+ rects = [(c * cell_w, row * cell_h, cell_w, cell_h) for c in range(frames)]
+ states.append({"name": state, "rects": rects})
+ meta[state] = {"fps": int(info.get("fps", 6)), "loop": bool(info.get("loop", True))}
+ return states, (cell_w, cell_h), atlas_file, meta
+
+
+# --- writing ----------------------------------------------------------------
+
+def write_run(
+ out_dir: Path,
+ atlas: Image.Image,
+ states: list[dict[str, Any]],
+ cell: tuple[int, int],
+ meta: dict[str, Any],
+ layout_source: str,
+ provenance: dict[str, Any],
+) -> dict[str, Any]:
+ cell_w, cell_h = cell
+ frames_root = out_dir / "frames"
+ frames_root.mkdir(parents=True, exist_ok=True)
+
+ request_states = {}
+ manifest_rows = []
+ for state in states:
+ name = state["name"]
+ state_dir = frames_root / name
+ state_dir.mkdir(parents=True, exist_ok=True)
+ files = []
+ for index, (x, y, w, h) in enumerate(state["rects"]):
+ crop = atlas.crop((x, y, x + w, y + h)).convert("RGBA")
+ # place into a clean cell; center when the crop is smaller (auto-detect)
+ if crop.size == (cell_w, cell_h):
+ framed = crop
+ else:
+ framed = Image.new("RGBA", (cell_w, cell_h), (0, 0, 0, 0))
+ framed.alpha_composite(crop, ((cell_w - w) // 2, (cell_h - h) // 2))
+ out = state_dir / f"frame-{index}.png"
+ atomic_save_image(framed, out)
+ files.append(relative_posix(out, out_dir))
+ m = meta.get(name, {})
+ request_states[name] = {
+ "frames": len(state["rects"]),
+ "fps": int(m.get("fps", 6)),
+ "loop": bool(m.get("loop", True)),
+ "action": "",
+ }
+ manifest_rows.append({"state": name, "frames": len(state["rects"]), "method": "unpacked", "files": files, "ok": True})
+
+ request = {
+ "version": 1,
+ "kind": "sprite-gen-request",
+ "engine": "component-row",
+ "character": {"id": out_dir.name, "description": f"unpacked from atlas ({layout_source})"},
+ "cell": {"shape": "rect" if cell_w != cell_h else "square", "width": cell_w, "height": cell_h, "size": cell_w, "safe_margin": 0},
+ "chroma_key": provenance.get("chroma_key", {"name": "magenta", "hex": "#FF00FF", "rgb": [255, 0, 255]}),
+ "states": request_states,
+ }
+ atomic_write_text(out_dir / "sprite-request.json", json.dumps(request, ensure_ascii=False, indent=2) + "\n")
+ atomic_write_text(
+ frames_root / "frames-manifest.json",
+ json.dumps({"ok": True, "engine": "component-row", "run_dir": str(out_dir), "cell": request["cell"], "rows": manifest_rows, "errors": [], "warnings": []}, ensure_ascii=False, indent=2) + "\n",
+ )
+ source_doc = {
+ "version": 1,
+ "kind": "sprite-gen-unpack-source",
+ "layout_source": layout_source,
+ "cell": {"width": cell_w, "height": cell_h},
+ **provenance,
+ }
+ atomic_write_text(out_dir / "unpack-source.json", json.dumps(source_doc, ensure_ascii=False, indent=2) + "\n")
+ return {"layout_source": layout_source, "states": [s["name"] for s in states], "cell": [cell_w, cell_h]}
+
+
+def import_pngs(out_dir: Path, png_paths: list[Path], state_name: str, labels: list[str], iso: dict[str, Any] | None = None) -> dict[str, Any]:
+ """단일 그룹 임포트 (하위호환 래퍼) — 그룹 지원 본체는 import_png_groups."""
+ return import_png_groups(out_dir, [{"name": state_name, "paths": png_paths, "labels": labels}], iso)
+
+
+def import_png_groups(out_dir: Path, groups: list[dict[str, Any]], iso: dict[str, Any] | None = None,
+ base_src: Path | None = None) -> dict[str, Any]:
+ """Import separate PNGs as one or more curator rows (states).
+
+ groups: [{"name": str, "paths": [Path], "labels": [str], "refs": [Path]}] —
+ 하위폴더 하나가 큐레이터 줄 하나가 된다 (예: reference/ 와 portraits/ 를 분리).
+ 셀 크기는 전 그룹 공유 최대치라 카드 배율이 그룹 간에도 일관된다. 원본은 복사만 한다.
+
+ 소스 1급 수용 (run-contract.md §4): `base_src` 는 아이덴티티 truth →
+ `base-source.<ext>` (큐레이션뷰 베이스 참조 줄). group 의 `refs` 는 그 줄의
+ 생성 재료 `<role>-<name>.png` → `references/imported/<state>/` (상태별 생성 재료
+ 칩). 역할(anchor/basis/guide) 해석은 serve_curation `_state_refs` 가 파일명에서
+ 단독 수행한다 (여긴 파일명 보존 복사만 — 역할 파싱 SSoT 이원화 금지).
+ """
+ loaded: list[tuple[dict[str, Any], list[Image.Image]]] = []
+ cell_w = 0
+ cell_h = 0
+ for group in groups:
+ imgs = [Image.open(p).convert("RGBA") for p in group["paths"]]
+ cell_w = max(cell_w, max(i.width for i in imgs))
+ cell_h = max(cell_h, max(i.height for i in imgs))
+ loaded.append((group, imgs))
+
+ request_states: dict[str, Any] = {}
+ manifest_rows = []
+ source_files: list[str] = []
+ source_labels: list[str] = []
+ imported_refs_manifest: dict[str, list[str]] = {}
+ for group, imgs in loaded:
+ state_name = str(group["name"])
+ labels = list(group.get("labels", []))
+ state_dir = out_dir / "frames" / state_name
+ state_dir.mkdir(parents=True, exist_ok=True)
+ files = []
+ for index, im in enumerate(imgs):
+ if im.size == (cell_w, cell_h):
+ framed = im
+ else:
+ framed = Image.new("RGBA", (cell_w, cell_h), (0, 0, 0, 0))
+ framed.alpha_composite(im, ((cell_w - im.width) // 2, (cell_h - im.height) // 2))
+ out = state_dir / f"frame-{index}.png"
+ atomic_save_image(framed, out)
+ files.append(relative_posix(out, out_dir))
+ request_states[state_name] = {"frames": len(imgs), "fps": 2, "loop": False, "action": "imported still set"}
+ manifest_rows.append({"state": state_name, "frames": len(imgs), "method": "imported-pngs", "files": files, "labels": labels, "ok": True})
+ source_files.extend(p.name for p in group["paths"])
+ source_labels.extend(labels)
+ # generation-material refs → references/imported/<state>/ (큐레이터 생성 재료 칩).
+ # 파일명을 보존해 복사한다 — role 파싱은 serve_curation 이 단독으로.
+ ref_paths = [Path(r) for r in group.get("refs", [])]
+ if ref_paths:
+ ref_dir = out_dir / "references" / "imported" / state_name
+ ref_dir.mkdir(parents=True, exist_ok=True)
+ for rp in ref_paths:
+ shutil.copy2(rp, ref_dir / rp.name)
+ imported_refs_manifest[state_name] = [rp.name for rp in ref_paths]
+
+ # base 아이덴티티 truth → base-source.<ext> (큐레이션뷰 베이스 참조 줄). prepare.py 와
+ # 동일하게 원본 확장자 보존 복사 (identity 는 재인코딩 없이 pristine 유지).
+ base_out_name = None
+ if base_src is not None:
+ base_src = Path(base_src)
+ base_out = out_dir / f"base-source{base_src.suffix.lower() or '.png'}"
+ shutil.copy2(base_src, base_out)
+ base_out_name = base_out.name
+
+ first_dir = groups[0]["paths"][0].parent
+ request = {
+ "version": 1,
+ "kind": "sprite-gen-request",
+ "engine": "component-row",
+ "character": {"id": out_dir.name, "description": f"imported PNG set from {first_dir}"},
+ "cell": {"shape": "square" if cell_w == cell_h else "rect", "width": cell_w, "height": cell_h, "size": cell_w, "safe_margin": 0},
+ "chroma_key": {"name": "magenta", "hex": "#FF00FF", "rgb": [255, 0, 255]},
+ "states": request_states,
+ }
+ if iso:
+ request["iso"] = iso # ground-grid geometry for the curator overlay
+ atomic_write_text(out_dir / "sprite-request.json", json.dumps(request, ensure_ascii=False, indent=2) + "\n")
+ atomic_write_text(
+ out_dir / "frames" / "frames-manifest.json",
+ json.dumps({"ok": True, "engine": "component-row", "run_dir": str(out_dir), "cell": request["cell"],
+ "rows": manifest_rows, "errors": [], "warnings": []}, ensure_ascii=False, indent=2) + "\n",
+ )
+ atomic_write_text(
+ out_dir / "unpack-source.json",
+ json.dumps({"version": 1, "kind": "sprite-gen-unpack-source", "layout_source": "imported-pngs",
+ "cell": {"width": cell_w, "height": cell_h}, "source_dir": str(first_dir),
+ "files": source_files, "labels": source_labels,
+ "groups": [str(g["name"]) for g in groups],
+ "base_source": base_out_name, "imported_refs": imported_refs_manifest}, ensure_ascii=False, indent=2) + "\n",
+ )
+ return {"layout_source": "imported-pngs", "states": [str(g["name"]) for g in groups], "cell": [cell_w, cell_h],
+ "frames": sum(len(imgs) for _, imgs in loaded),
+ "base_source": base_out_name, "imported_refs": imported_refs_manifest}
+
+
+def _new_staging(out_dir: Path) -> Path:
+ """A fresh empty staging dir beside out_dir. The run is built here first, then
+ published atomically, so a failed/partial build never touches the prior run."""
+ staging = out_dir.parent / f".{out_dir.name}.sg-staging"
+ if staging.exists():
+ shutil.rmtree(staging)
+ staging.mkdir(parents=True)
+ return staging
+
+
+_PUBLISH_BACKUP = ".sg-backup"
+
+
+def _publish_run(staging: Path, out_dir: Path) -> None:
+ """Publish the fully-built staging run into out_dir.
+
+ Named isolation strategy: **out_dir (and the `.sprite-gen.lock` inside it) never
+ disappears** during the publish. Prior content is relocated into an in-place
+ `.sg-backup` subdir and staging content moved in — out_dir is never renamed away, so a
+ concurrent writer's `acquire_run_dir_lock(out_dir)` always finds the held lock and
+ blocks (runio single-writer contract holds across the whole publish). On an I/O failure
+ the swap rolls back to the prior run byte-intact (Atomicity: succeed or roll back).
+ Called only after a successful build."""
+ reserved = {LOCK_FILENAME, _PUBLISH_BACKUP}
+ backup = out_dir / _PUBLISH_BACKUP
+ # publish_guard (exclusive) blocks concurrent readers (serve_curation read_guard) for
+ # the whole swap, so a serving /api/run never observes the half-published state
+ # (reader isolation — a reader sees the complete prior run or the complete new run).
+ with publish_guard(out_dir):
+ if backup.exists():
+ shutil.rmtree(backup)
+ backup.mkdir()
+ moved: list[str] = []
+ phase1_done = False
+ try:
+ for child in [c for c in out_dir.iterdir() if c.name not in reserved]:
+ child.rename(backup / child.name) # prior content -> in-place backup
+ moved.append(child.name)
+ phase1_done = True
+ for child in [c for c in staging.iterdir() if c.name != LOCK_FILENAME]:
+ child.rename(out_dir / child.name) # new content -> out_dir
+ except OSError:
+ # roll back to the prior run byte-intact.
+ if phase1_done:
+ # all prior content is safe in backup; drop any partial new content we placed.
+ for child in [c for c in out_dir.iterdir() if c.name not in reserved]:
+ shutil.rmtree(child) if child.is_dir() else child.unlink()
+ # restore relocated prior content (a phase-1-partial failure left the rest in place)
+ for name in moved:
+ (backup / name).rename(out_dir / name)
+ raise
+ finally:
+ shutil.rmtree(backup, ignore_errors=True)
+
+
+def parse_grid(value: str) -> tuple[int, int]:
+ cols, rows = value.lower().split("x")
+ return int(cols), int(rows)
+
+
+def _build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--atlas", type=Path, help="sprite sheet PNG (or use --manifest)")
+ parser.add_argument("--manifest", type=Path, help="manifest JSON with frame layout")
+ parser.add_argument("--pngs-dir", type=Path, help="folder of separate PNGs to import as one state's frames")
+ parser.add_argument("--state-name", default="items", help="state name for --pngs-dir import")
+ parser.add_argument("--out-dir", type=Path, help="run dir for output; defaults to a '<source>-curator' folder next to the input so it is easy to find")
+ parser.add_argument("--grid", type=parse_grid, help="explicit COLSxROWS, for example 8x9")
+ parser.add_argument("--cell", type=parse_grid, help="explicit cell WxH (for manifests missing cell size)")
+ parser.add_argument("--direction", help="which direction to unpack from a multi-direction manifest")
+ parser.add_argument("--states", help="comma-separated state names to override detected/row names")
+ parser.add_argument("--auto", action="store_true", help="force alpha auto-detect even if a manifest is given")
+ parser.add_argument("--force", action="store_true", help="overwrite an existing out-dir")
+ return parser
+
+
+def _namespace_from_kwargs(**kwargs: object) -> argparse.Namespace:
+ parser = _build_parser()
+ values: dict[str, object] = {}
+ remaining = dict(kwargs)
+ for action in parser._actions:
+ if action.dest == "help":
+ continue
+ default = [] if action.nargs == "*" else action.default
+ if default is argparse.SUPPRESS:
+ default = None
+ value = remaining.pop(action.dest, default)
+ if getattr(action, "required", False) and value is None:
+ raise TypeError(f"missing required argument: {action.dest}")
+ values[action.dest] = value
+ if remaining:
+ names = ", ".join(sorted(remaining))
+ raise TypeError(f"unexpected keyword argument(s): {names}")
+ return argparse.Namespace(**values)
+def _run(args: argparse.Namespace):
+
+ # default the run dir to a clearly-findable sibling next to the input.
+ if args.out_dir:
+ out_dir = args.out_dir.expanduser().resolve()
+ else:
+ if args.pngs_dir:
+ base = args.pngs_dir.expanduser().resolve()
+ out_dir = base.parent / f"{base.name}-curator"
+ elif args.atlas:
+ base = args.atlas.expanduser().resolve()
+ out_dir = base.parent / f"{base.stem}-curator"
+ elif args.manifest:
+ base = args.manifest.expanduser().resolve()
+ out_dir = base.parent / f"{base.stem}-curator"
+ else:
+ raise SystemExit("need one of --pngs-dir / --atlas / --manifest (or pass --out-dir)")
+
+ if out_dir.exists() and any(out_dir.iterdir()) and not args.force:
+ raise SystemExit(f"out-dir not empty: {out_dir} (use --force)")
+ try:
+ out_dir.mkdir(parents=True, exist_ok=True)
+ except OSError as exc:
+ raise SystemExit(f"cannot create run dir next to the input: {out_dir}\n {exc}\n pass --out-dir <writable path> to choose another location")
+ acquire_run_dir_lock(out_dir, "unpack_atlas_run")
+
+ # --pngs-dir: import a folder of separate PNGs (e.g. a furniture set).
+ # 하위폴더가 있으면 각 하위폴더가 큐레이터 줄(state) 하나가 된다 —
+ # 예: reference/ (베이스 이미지 칸) + portraits/ (표정 세트 줄).
+ if args.pngs_dir:
+ src = args.pngs_dir.expanduser().resolve()
+ top_pngs = sorted(p for p in src.glob("*.png"))
+ # reserved underscore dirs carry sources, not curator rows (run-contract.md §4):
+ # _base/ = whole-set identity image, <group>/_refs/ = that row's generation material.
+ reserved = {"_base", "_refs"}
+ subdirs = sorted(d for d in src.iterdir() if d.is_dir() and d.name not in reserved)
+ # _base/<img> → base-source (base reference row). Accept the same formats serve_curation shows.
+ base_src = None
+ base_dir = src / "_base"
+ if base_dir.is_dir():
+ base_candidates = sorted(p for p in base_dir.iterdir()
+ if p.suffix.lower() in (".png", ".jpg", ".jpeg", ".webp"))
+ if len(base_candidates) > 1:
+ # _base is the run's single identity image; picking one of several silently would
+ # make identity SSoT ambiguous (No Silent Fallback).
+ raise SystemExit(
+ f"_base/ has {len(base_candidates)} images ({', '.join(p.name for p in base_candidates)}); "
+ f"provide exactly one identity image."
+ )
+ if base_candidates:
+ base_src = base_candidates[0]
+
+ def _group_refs(group_dir: Path) -> list[Path]:
+ rd = group_dir / "_refs"
+ return sorted(rd.glob("*.png")) if rd.is_dir() else []
+
+ # prefer human names from a sibling meta.json (file -> item name), else filename stem
+ file_to_name: dict[str, str] = {}
+ iso = None
+ meta_path = src / "meta.json"
+ if meta_path.is_file():
+ meta = json.loads(meta_path.read_text(encoding="utf-8"))
+ file_to_name = {info.get("file"): name for name, info in meta.get("items", {}).items() if isinstance(info, dict)}
+ tile = meta.get("tile")
+ anchor = meta.get("anchor")
+ if tile and anchor:
+ iso = {
+ "tile": {"width": int(tile["width"]), "height": int(tile["height"])},
+ "projection": tile.get("projection", "2:1 dimetric diamond"),
+ "anchor_pixel": anchor.get("pixel", [128, 222]),
+ "canvas": meta.get("style", {}).get("canvas", [256, 256]),
+ }
+ groups: list[dict[str, Any]] = []
+ if top_pngs:
+ groups.append({"name": args.state_name, "paths": top_pngs,
+ "labels": [file_to_name.get(p.name, p.stem) for p in top_pngs],
+ "refs": _group_refs(src)})
+ for sub in subdirs:
+ sub_pngs = sorted(p for p in sub.glob("*.png"))
+ if sub_pngs:
+ groups.append({"name": sub.name, "paths": sub_pngs,
+ "labels": [file_to_name.get(p.name, p.stem) for p in sub_pngs],
+ "refs": _group_refs(sub)})
+ if not groups:
+ raise SystemExit(f"no PNGs in {src}")
+ # imported ref roles are validated fail-loud (run-contract §4). A _refs file whose
+ # prefix isn't a known role (anchor/basis/guide) is malformed input — reject it
+ # loudly instead of silently relabeling it as guide (No Silent Fallback).
+ bad_refs = [f"{g['name']}/_refs/{Path(r).name}"
+ for g in groups for r in g.get("refs", [])
+ if imported_ref_role(Path(r).name) is None]
+ if bad_refs:
+ raise SystemExit("invalid _refs role prefix — expected anchor-/basis-/guide-<name>.png, got: "
+ + ", ".join(bad_refs))
+ # atomic rebuild: all validation above ran before any mutation; build into a
+ # staging dir, then publish over out_dir. A --force re-import that fails (or is
+ # invalid) leaves the prior run intact — never clear-then-fail.
+ staging = _new_staging(out_dir)
+ try:
+ result = import_png_groups(staging, groups, iso, base_src=base_src)
+ _publish_run(staging, out_dir)
+ finally:
+ shutil.rmtree(staging, ignore_errors=True)
+ result["ok"] = True
+ result["out_dir"] = str(out_dir)
+ print(json.dumps(result, ensure_ascii=False, indent=2))
+ return 0
+
+ manifest = json.loads(args.manifest.read_text(encoding="utf-8")) if args.manifest else None
+ provenance: dict[str, Any] = {
+ "atlas": str(args.atlas) if args.atlas else None,
+ "manifest": str(args.manifest) if args.manifest else None,
+ "direction": args.direction,
+ }
+
+ # resolve layout + atlas image
+ atlas_path = args.atlas
+ meta: dict[str, Any] = {}
+ if args.grid:
+ layout_source = "grid-explicit"
+ if not atlas_path:
+ raise SystemExit("--grid needs --atlas")
+ atlas = Image.open(atlas_path).convert("RGBA")
+ states, cell = grid_layout(atlas, *args.grid)
+ elif manifest and not args.auto:
+ layout_source = "manifest"
+ states, cell, atlas_name, meta = manifest_layout(manifest, args.direction)
+ provenance["chroma_key"] = manifest.get("chroma_key") if isinstance(manifest.get("chroma_key"), dict) else None
+ if not atlas_path:
+ atlas_path = (args.manifest.parent / atlas_name) if atlas_name else None
+ if not atlas_path or not Path(atlas_path).is_file():
+ raise SystemExit(f"could not locate atlas image (manifest pointed to {atlas_name}); pass --atlas")
+ atlas = Image.open(atlas_path).convert("RGBA")
+ else:
+ layout_source = "auto-detect"
+ if not atlas_path:
+ raise SystemExit("auto-detect needs --atlas")
+ atlas = Image.open(atlas_path).convert("RGBA")
+ states, cell = auto_detect(atlas)
+
+ if args.states:
+ names = [n.strip() for n in args.states.split(",")]
+ for i, name in enumerate(names):
+ if i < len(states):
+ states[i]["name"] = name
+
+ provenance["atlas"] = str(atlas_path)
+ # atomic rebuild (see --pngs-dir): atlas/layout resolution above is read-only; build
+ # into staging, then publish over out_dir so a failed rebuild leaves the prior run intact.
+ staging = _new_staging(out_dir)
+ try:
+ result = write_run(staging, atlas, states, cell, meta, layout_source, provenance)
+ _publish_run(staging, out_dir)
+ finally:
+ shutil.rmtree(staging, ignore_errors=True)
+ result["ok"] = True
+ result["out_dir"] = str(out_dir)
+ print(json.dumps(result, ensure_ascii=False, indent=2))
+ return 0
+
+
+
+def run(**kwargs: object):
+ return _run(_namespace_from_kwargs(**kwargs))
+
+def main() -> int:
+ parser = _build_parser()
+ args = parser.parse_args()
+ return _run(args)
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/sprite_gen/gen/__init__.py b/sprite_gen/gen/__init__.py
new file mode 100644
index 0000000..a48e999
--- /dev/null
+++ b/sprite_gen/gen/__init__.py
@@ -0,0 +1,306 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Unified image generation layer for sprite-gen.
+
+Single source of truth for provider-backed image generation: codex (`image_gen`,
+ChatGPT OAuth) and grok (Imagine, xAI OAuth). One call = prompt (+ optional refs)
+-> one verified raw PNG, with an optional deterministic transparent chroma
+post-process. The general `image-gen` skill is a thin shuttle over `sprite-gen gen`.
+
+CLI:
+ sprite-gen gen --provider codex|grok --prompt "..." --out DEST.png
+ [--ref REF.png ...] [--transparent [--chroma-key magenta|green]]
+ [--white-check CHECK.png] [--model ID] [--aspect-ratio 1:1]
+ [--report REPORT.json] [--keep-session]
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import shutil
+import subprocess
+import sys
+import tempfile
+from pathlib import Path
+from typing import Any
+
+from sprite_gen.spec.runio import atomic_write_text
+
+from . import chroma as chroma_mod
+from .base import GenRequest, GenResult, verify_png, GenTimeoutError, provider_binary, provider_subprocess_env
+from .codex_provider import CodexProvider
+from .grok_provider import GrokProvider
+
+PROVIDERS = ("codex", "grok")
+
+# Default-provider policy (maintainer 확정 2026-07-17): the default backend is codex
+# (GPT `image_gen`). If codex is unavailable in the environment (CLI missing or
+# not logged in) the default resolution falls back to grok — but OBSERVABLY, never
+# silently (No Silent Fallback): the chosen provider and the fallback reason are
+# reported. A user can change the default with SPRITE_GEN_DEFAULT_PROVIDER. An
+# EXPLICIT `--provider` is always honored exactly (no availability fallback) — an
+# explicitly named provider that is down fails loud at generation time.
+DEFAULT_PROVIDER_ENV = "SPRITE_GEN_DEFAULT_PROVIDER"
+HARD_DEFAULT_PROVIDER = "codex"
+_CODEX_PROBE_TIMEOUT_SECONDS = 15
+
+
+def _make_provider(name: str, *, keep_session: bool):
+ if name == "codex":
+ return CodexProvider(keep_session=keep_session)
+ if name == "grok":
+ return GrokProvider()
+ raise SystemExit(f"gen: unknown provider {name!r}; expected one of {', '.join(PROVIDERS)}")
+
+
+def _codex_available() -> tuple[bool, str]:
+ """Is codex usable here? Returns (ok, reason_if_not).
+
+ Two checks, cheapest first: the `codex` CLI on PATH, then `codex login status`
+ (exit 0 = logged in). Any probe error/timeout counts as unavailable with a
+ stated reason — never a silent pass. Monkeypatchable in tests.
+ """
+ if shutil.which("codex") is None:
+ return False, "codex CLI not found on PATH"
+ try:
+ completed = subprocess.run(
+ [provider_binary("codex"), "login", "status"],
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ env=provider_subprocess_env(),
+ timeout=_CODEX_PROBE_TIMEOUT_SECONDS,
+ )
+ except (OSError, subprocess.SubprocessError) as exc:
+ return False, f"codex login-status probe failed: {exc}"
+ if completed.returncode != 0:
+ tail = (completed.stdout or completed.stderr or "").strip().splitlines()[-3:]
+ detail = f": {' '.join(tail)}" if tail else ""
+ return False, f"codex not logged in (codex login status exit {completed.returncode}{detail})"
+ return True, ""
+
+
+def resolve_default_provider() -> tuple[str, dict[str, str] | None]:
+ """Resolve the provider to use when `--provider` is not given.
+
+ Precedence: SPRITE_GEN_DEFAULT_PROVIDER env > hard default (codex). When the
+ resolved default is codex but codex is unavailable, fall back to grok and return
+ fallback metadata (from/to/reason/default_source) so the switch is observable.
+ Returns (provider, fallback_or_None).
+ """
+ configured = os.environ.get(DEFAULT_PROVIDER_ENV, "").strip()
+ if configured:
+ if configured not in PROVIDERS:
+ raise SystemExit(
+ f"gen: {DEFAULT_PROVIDER_ENV}={configured!r} is not a known provider; "
+ f"expected one of {', '.join(PROVIDERS)}"
+ )
+ default, source = configured, DEFAULT_PROVIDER_ENV
+ else:
+ default, source = HARD_DEFAULT_PROVIDER, "hard-default"
+
+ # The availability-driven fallback is codex -> grok only (the mandated default).
+ # A grok default that is down fails loud at generation time rather than silently
+ # reverse-falling-back to codex.
+ if default == "codex":
+ ok, reason = _codex_available()
+ if not ok:
+ return "grok", {
+ "from": "codex",
+ "to": "grok",
+ "reason": reason,
+ "default_source": source,
+ }
+ return default, None
+
+
+def generate_image(
+ provider: str,
+ prompt: str,
+ out: Path,
+ *,
+ refs: list[Path] | None = None,
+ model: str | None = None,
+ aspect_ratio: str | None = None,
+ transparent: bool = False,
+ chroma_key: str = "magenta",
+ white_check: Path | None = None,
+ keep_session: bool = False,
+ workdir: Path | None = None,
+) -> GenResult:
+ """Generate one image and return a GenResult. Raises SystemExit on any failure."""
+ prompt = (prompt or "").strip()
+ if not prompt:
+ raise SystemExit("gen: empty prompt; pass --prompt or --prompt-file")
+ out = out.expanduser().resolve()
+ refs = [Path(r).expanduser().resolve() for r in (refs or [])]
+ for ref in refs:
+ if not ref.is_file():
+ raise SystemExit(f"gen: reference image not found: {ref}")
+
+ backend = _make_provider(provider, keep_session=keep_session)
+ owns_workdir = workdir is None
+ workdir = Path(workdir).expanduser().resolve() if workdir else Path(tempfile.mkdtemp(prefix="sprite-gen-gen-"))
+ workdir.mkdir(parents=True, exist_ok=True)
+ raw = workdir / "raw.png"
+
+ try:
+ request = GenRequest(prompt=prompt, raw=raw, refs=refs, model=model, aspect_ratio=aspect_ratio)
+ # 타임아웃 1회 관측 가능 재시도 — 산발 provider 스톨은 같은 호출 재시도로
+ # 대부분 통과한다 (회귀 2026-07-19). 두 번째도 스톨이면 fail loud.
+ try:
+ run = backend.generate(request, workdir)
+ except GenTimeoutError as exc:
+ print(f"[gen] {exc} — retrying once", file=sys.stderr)
+ run = backend.generate(request, workdir)
+ raw_bytes = verify_png(raw)
+
+ chroma_stats: dict[str, Any] | None = None
+ out.parent.mkdir(parents=True, exist_ok=True)
+ if transparent:
+ chroma_stats = chroma_mod.key_transparent(raw, out, key=chroma_key, white_check=white_check)
+ else:
+ shutil.copyfile(raw, out)
+ verify_png(out)
+
+ # Preserve the pre-chroma raw next to the destination for auditability.
+ raw_keep = out.with_suffix(out.suffix + ".raw.png")
+ shutil.copyfile(raw, raw_keep)
+
+ return GenResult(
+ provider=run.provider,
+ prompt=prompt,
+ out=out,
+ raw=raw_keep,
+ raw_bytes=raw_bytes,
+ elapsed_seconds=run.elapsed_seconds,
+ model=run.model,
+ session_id=run.session_id,
+ refs=refs,
+ transparent=transparent,
+ chroma=chroma_stats,
+ extra=run.extra,
+ )
+ finally:
+ if owns_workdir:
+ shutil.rmtree(workdir, ignore_errors=True)
+
+
+def _run(args: argparse.Namespace) -> int:
+ prompt = args.prompt
+ if args.prompt_file:
+ prompt = Path(args.prompt_file).expanduser().read_text(encoding="utf-8")
+ # Explicit --provider is honored verbatim; only the unspecified case resolves the
+ # default (env > codex) with an observable codex->grok availability fallback.
+ provider = args.provider
+ fallback: dict[str, str] | None = None
+ if provider is not None:
+ resolved_from = "explicit"
+ else:
+ provider, fallback = resolve_default_provider()
+ if fallback:
+ resolved_from = f"fallback-from-{fallback['from']}"
+ print(
+ f"sprite-gen gen: default provider '{fallback['from']}' unavailable "
+ f"({fallback['reason']}) — falling back to '{fallback['to']}'. "
+ f"Set {DEFAULT_PROVIDER_ENV} or pass --provider to control this.",
+ file=sys.stderr,
+ )
+ elif os.environ.get(DEFAULT_PROVIDER_ENV, "").strip():
+ resolved_from = DEFAULT_PROVIDER_ENV
+ else:
+ resolved_from = "hard-default"
+ result = generate_image(
+ provider,
+ prompt or "",
+ args.out,
+ refs=args.ref,
+ model=args.model,
+ aspect_ratio=args.aspect_ratio,
+ transparent=args.transparent,
+ chroma_key=args.chroma_key,
+ white_check=args.white_check,
+ keep_session=args.keep_session,
+ workdir=args.workdir,
+ )
+ payload = result.to_dict()
+ # `provider` in the payload is always the backend that actually generated the
+ # image; `provider_resolved_from` records HOW it was chosen and
+ # `provider_fallback` records a default->fallback switch when one happened
+ # (No Silent Fallback — the report names which provider was used and why).
+ payload["provider_resolved_from"] = resolved_from
+ if fallback:
+ payload["provider_fallback"] = fallback
+ if args.report:
+ report_path = Path(args.report).expanduser().resolve()
+ atomic_write_text(report_path, json.dumps(payload, ensure_ascii=False, indent=2) + "\n")
+ payload["report"] = str(report_path)
+ _print_json(payload)
+ return 0
+
+
+def _print_json(payload: dict) -> None:
+ """Emit the machine-readable report as UTF-8 on every host locale.
+
+ A generated prompt may contain Korean or an em dash. On a Windows cp949
+ redirected stream, writing that through ``TextIOWrapper`` can fail after
+ the image already exists. The binary buffer is the CLI byte contract and
+ avoids mutating process-global stdout configuration. Captured/in-memory
+ streams without a buffer already accept Unicode and use the text path.
+ """
+ text = json.dumps(payload, ensure_ascii=False, indent=2) + "\n"
+ buffer = getattr(sys.stdout, "buffer", None)
+ if buffer is not None:
+ buffer.write(text.encode("utf-8"))
+ buffer.flush()
+ else:
+ sys.stdout.write(text)
+
+
+def _build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(prog="sprite-gen gen", description=__doc__)
+ add_arguments(parser)
+ return parser
+
+
+def add_arguments(parser: argparse.ArgumentParser) -> None:
+ parser.add_argument(
+ "--provider",
+ choices=PROVIDERS,
+ default=None,
+ help=(
+ f"generation backend; default resolves via {DEFAULT_PROVIDER_ENV} env "
+ "then codex, with an observable grok fallback if codex is unavailable"
+ ),
+ )
+ parser.add_argument("--prompt")
+ parser.add_argument("--prompt-file", type=Path)
+ parser.add_argument("--out", required=True, type=Path)
+ parser.add_argument("--ref", action="append", type=Path, default=[], help="reference image (repeatable)")
+ parser.add_argument("--model")
+ parser.add_argument("--aspect-ratio", help="grok only, e.g. 1:1 16:9 9:16")
+ parser.add_argument("--transparent", action="store_true", help="chroma-key the raw PNG to transparent RGBA")
+ parser.add_argument("--chroma-key", choices=sorted(chroma_mod.KEYS), default="magenta")
+ parser.add_argument("--white-check", type=Path, help="write a white-composite check image")
+ parser.add_argument("--keep-session", action="store_true", help="codex: do not delete the rollout jsonl")
+ parser.add_argument("--report", type=Path, help="write the generation report JSON here")
+ parser.add_argument("--workdir", type=Path, help="reuse this working dir instead of a temp dir")
+
+
+def run(**kwargs: object) -> int:
+ parser = _build_parser()
+ known = {action.dest for action in parser._actions if action.dest != "help"}
+ unexpected = set(kwargs) - known
+ if unexpected:
+ raise TypeError(f"unexpected keyword argument(s): {', '.join(sorted(unexpected))}")
+ namespace = argparse.Namespace(**{dest: kwargs.get(dest, parser.get_default(dest)) for dest in known})
+ return _run(namespace)
+
+
+def main(argv: list[str] | None = None) -> int:
+ return _run(_build_parser().parse_args(argv))
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/sprite_gen/gen/base.py b/sprite_gen/gen/base.py
new file mode 100644
index 0000000..edefe1f
--- /dev/null
+++ b/sprite_gen/gen/base.py
@@ -0,0 +1,145 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Shared contract for sprite-gen image generation providers.
+
+One generation call = prompt (+ optional reference images) -> one verified raw
+PNG on disk. Providers own the model call and its timing; the orchestrator in
+`sprite_gen.gen` owns the optional transparent chroma post-process and the
+report. Truth is always the decoded PNG bytes on disk, never a model-reported
+path or a "done" string (No Silent Fallback).
+"""
+
+from __future__ import annotations
+
+import os
+import shutil
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any, Protocol
+
+PNG_MAGIC = b"\x89PNG\r\n\x1a\n"
+
+# Child provider processes are independent execution contexts. They must not
+# inherit parent orchestration identity or lifecycle controls, while ordinary
+# variables such as PATH remain available. Suffix matching keeps the contract
+# provider-neutral and covers any orchestration namespace.
+_ORCHESTRATOR_SESSION_ENV_SUFFIXES = (
+ "_RUNTIME_ENDPOINT_ID",
+ "_MEMBER_ID",
+ "_PROJECT_ID",
+ "_PLAN_EXIT_GATE",
+ "_STUDIO_PORT",
+)
+
+
+# 생성 서브프로세스 하드 타임아웃 — provider 스트림이 드물게 무출력으로 매달린다
+# (회귀 2026-07-19: 15행 배치 중 1행의 codex exec 이 1시간 38분 무출력 — 같은 env
+# 로 14행이 성공했으니 세션/훅 충돌이 아니라 provider 측 산발 스톨. 킬 외엔 답이
+# 없으므로 바운드가 유일한 방어). 기본 180초 (maintainer 확정 2026-07-19; 실측 정상 최장 129초).
+GEN_TIMEOUT_SECONDS = int(os.environ.get("SPRITE_GEN_GEN_TIMEOUT_SECONDS", "180"))
+
+
+class GenTimeoutError(SystemExit):
+ """생성 서브프로세스가 GEN_TIMEOUT_SECONDS 안에 끝나지 않아 킬됨 (관측 가능)."""
+
+
+def provider_subprocess_env() -> dict[str, str]:
+ """Environment for a headless generation subprocess.
+
+ The parent environment minus known orchestrator session env families, so a
+ spawned engine (`codex exec`, `grok`) is a clean standalone process — it
+ neither impersonates the spawning agent nor gets strangled by the
+ orchestrator's hooks. SSoT for every provider's `subprocess.run` env —
+ providers must not spawn with the inherited env directly.
+ """
+ env = {
+ key: value
+ for key, value in os.environ.items()
+ if not key.endswith(_ORCHESTRATOR_SESSION_ENV_SUFFIXES)
+ }
+ return env
+
+
+def provider_binary(name: str) -> str:
+ """Resolve a provider CLI through PATH, including Windows PATHEXT shims.
+
+ npm installs provider CLIs as ``.cmd`` shims on Windows. ``CreateProcess``
+ does not resolve those from a bare name, while ``shutil.which`` does. A
+ missing command stays bare so the provider spawn still owns the observable
+ failure instead of introducing a second availability answer here.
+ """
+ return shutil.which(name) or name
+
+
+def verify_png(path: Path) -> int:
+ """Return the PNG byte count, or raise SystemExit if it is missing/not a PNG."""
+ if not path.is_file():
+ raise SystemExit(f"gen: expected a generated PNG at {path}, but no file was written")
+ data = path.read_bytes()
+ if data[:8] != PNG_MAGIC:
+ raise SystemExit(f"gen: file at {path} is not a PNG (magic mismatch) — refusing to claim success")
+ return len(data)
+
+
+@dataclass
+class GenRequest:
+ """A single image generation request."""
+
+ prompt: str
+ raw: Path # provider writes the generated PNG (chroma background included) here
+ refs: list[Path] = field(default_factory=list)
+ model: str | None = None
+ aspect_ratio: str | None = None # grok honours this; codex ignores it
+
+
+@dataclass
+class ProviderRun:
+ """What a provider reports after writing `request.raw`."""
+
+ provider: str
+ elapsed_seconds: float
+ model: str | None = None
+ session_id: str | None = None # codex rollout session id, when applicable
+ extra: dict[str, Any] = field(default_factory=dict)
+
+
+class Provider(Protocol):
+ """A generation backend. `generate` must write a verified PNG to `request.raw`."""
+
+ name: str
+
+ def generate(self, request: GenRequest, workdir: Path) -> ProviderRun: ...
+
+
+@dataclass
+class GenResult:
+ """Full outcome of one `sprite-gen gen` invocation."""
+
+ provider: str
+ prompt: str
+ out: Path
+ raw: Path
+ raw_bytes: int
+ elapsed_seconds: float
+ model: str | None = None
+ session_id: str | None = None
+ refs: list[Path] = field(default_factory=list)
+ transparent: bool = False
+ chroma: dict[str, Any] | None = None
+ extra: dict[str, Any] = field(default_factory=dict)
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "kind": "sprite-gen-image-report",
+ "provider": self.provider,
+ "prompt": self.prompt,
+ "out": str(self.out),
+ "raw": str(self.raw),
+ "raw_bytes": self.raw_bytes,
+ "elapsed_seconds": round(self.elapsed_seconds, 3),
+ "model": self.model,
+ "session_id": self.session_id,
+ "refs": [str(ref) for ref in self.refs],
+ "transparent": self.transparent,
+ "chroma": self.chroma,
+ **({"extra": self.extra} if self.extra else {}),
+ }
diff --git a/sprite_gen/gen/chroma.py b/sprite_gen/gen/chroma.py
new file mode 100644
index 0000000..12ccc17
--- /dev/null
+++ b/sprite_gen/gen/chroma.py
@@ -0,0 +1,128 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Deterministic chroma-key -> transparent PNG contract for generated images.
+
+Ported verbatim in behaviour from the standalone `image-gen` skill helper
+(`scripts/chroma_key_transparent.py`, MIT, aldegad/image-gen). `image_gen` /
+Grok Imagine alpha output is not reliable, so the canonical transparent contract
+is: generate on a solid `#FF00FF` magenta or `#00FF00` green background, then key
+it out here. Removes the key colour, clears RGB for fully-transparent pixels, and
+neutralises semi-transparent chroma fringe. No silent success — transparent
+pixels that still carry non-zero RGB raise loudly.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+from typing import Any
+
+from PIL import Image
+
+KEYS: dict[str, dict[str, int | tuple[int, int, int]]] = {
+ "magenta": {"target": (255, 0, 255), "min_primary": 170, "max_opposite": 115, "min_delta": 70},
+ "green": {"target": (0, 255, 0), "min_primary": 170, "max_opposite": 115, "min_delta": 70},
+}
+
+
+def is_key_pixel(r: int, g: int, b: int, key: str, min_primary: int, max_opposite: int, min_delta: int) -> bool:
+ if key == "magenta":
+ return r >= min_primary and b >= min_primary and g <= max_opposite and (r - g) >= min_delta and (b - g) >= min_delta
+ return g >= min_primary and r <= max_opposite and b <= max_opposite and (g - r) >= min_delta and (g - b) >= min_delta
+
+
+def is_fringe_pixel(r: int, g: int, b: int, key: str, threshold: int) -> bool:
+ if key == "magenta":
+ return (r - g) > threshold and (b - g) > threshold
+ return (g - r) > threshold and (g - b) > threshold
+
+
+def neutralize_fringe(r: int, g: int, b: int, a: int, key: str) -> tuple[int, int, int, int]:
+ neutral = g if key == "magenta" else max(r, b)
+ return (neutral, neutral, neutral, max(0, a // 3))
+
+
+def write_white_check(image: Image.Image, path: Path) -> None:
+ bg = Image.new("RGBA", image.size, (255, 255, 255, 255))
+ bg.alpha_composite(image)
+ bg.convert("RGB").save(path)
+
+
+def key_transparent(
+ input_path: Path,
+ out_path: Path,
+ *,
+ key: str = "magenta",
+ min_primary: int | None = None,
+ max_opposite: int | None = None,
+ min_delta: int | None = None,
+ fringe_threshold: int = 4,
+ fringe_alpha_max: int = 239,
+ fringe_cleanup: bool = True,
+ white_check: Path | None = None,
+) -> dict[str, Any]:
+ """Key a solid-chroma-background PNG to a clean transparent RGBA PNG.
+
+ Returns a stats dict (keyed/fringe/cleaned pixel counts, alpha_zero_pct).
+ Raises SystemExit if any transparent pixel keeps non-zero RGB (No Silent
+ Fallback: a "transparent" result that still leaks the key colour is a defect).
+ """
+ if key not in KEYS:
+ raise SystemExit(f"chroma: unknown key {key!r}; expected one of {sorted(KEYS)}")
+ defaults = KEYS[key]
+ min_primary = int(defaults["min_primary"]) if min_primary is None else min_primary
+ max_opposite = int(defaults["max_opposite"]) if max_opposite is None else max_opposite
+ min_delta = int(defaults["min_delta"]) if min_delta is None else min_delta
+
+ image = Image.open(input_path).convert("RGBA")
+ pixels = image.load()
+ width, height = image.size
+ keyed = fringe = cleaned_rgb = 0
+
+ for y in range(height):
+ for x in range(width):
+ r, g, b, a = pixels[x, y]
+ if a and is_key_pixel(r, g, b, key, min_primary, max_opposite, min_delta):
+ pixels[x, y] = (0, 0, 0, 0)
+ keyed += 1
+ continue
+ if a == 0:
+ if r or g or b:
+ pixels[x, y] = (0, 0, 0, 0)
+ cleaned_rgb += 1
+ continue
+ if fringe_cleanup and 0 < a <= fringe_alpha_max and is_fringe_pixel(r, g, b, key, fringe_threshold):
+ pixels[x, y] = neutralize_fringe(r, g, b, a, key)
+ fringe += 1
+
+ out_path.parent.mkdir(parents=True, exist_ok=True)
+ image.save(out_path)
+
+ if white_check is not None:
+ white_check.parent.mkdir(parents=True, exist_ok=True)
+ write_white_check(image, white_check)
+
+ total = width * height
+ alpha_zero = stale_rgb = 0
+ for y in range(height):
+ for x in range(width):
+ r, g, b, a = pixels[x, y]
+ if a == 0:
+ alpha_zero += 1
+ if r or g or b:
+ stale_rgb += 1
+
+ stats: dict[str, Any] = {
+ "out": str(out_path),
+ "mode": "RGBA",
+ "size": f"{width}x{height}",
+ "key": key,
+ "keyed_pixels": keyed,
+ "fringe_pixels": fringe,
+ "cleaned_transparent_rgb_pixels": cleaned_rgb,
+ "alpha_zero_pct": round(alpha_zero / total * 100, 2) if total else 0.0,
+ "stale_transparent_rgb_pixels": stale_rgb,
+ }
+ if white_check is not None:
+ stats["white_check"] = str(white_check)
+ if stale_rgb:
+ raise SystemExit(f"chroma: transparent pixels still contain non-zero RGB ({stale_rgb} px) in {out_path}")
+ return stats
diff --git a/sprite_gen/gen/codex_provider.py b/sprite_gen/gen/codex_provider.py
new file mode 100644
index 0000000..9639ae9
--- /dev/null
+++ b/sprite_gen/gen/codex_provider.py
@@ -0,0 +1,323 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Codex `image_gen` provider (ChatGPT OAuth, no API key).
+
+Ported from the standalone `image-gen` skill (MIT, aldegad/image-gen). codex
+does not persist a discrete file; `image_gen` returns the PNG **inline as base64**
+inside the session rollout jsonl. We spawn a fresh `codex exec` in an empty
+sandbox (fresh session breaks OpenAI's prompt cache so repeat prompts don't drag
+in a previous image), parse the session id from stdout, then decode the inline
+base64 deterministically. The model-reported path is never trusted.
+
+Decisive flags (each verified in the image-gen skill):
+- `--sandbox workspace-write` image_gen needs write access, else the tool never registers.
+- `--add-dir <Codex state root>/generated_images` not in the default writable set; the root is `CODEX_HOME` when set and `~/.codex` otherwise.
+- `--skip-git-repo-check` the sandbox dir is not a git repo.
+- NO `--ephemeral` the session jsonl must survive on disk so we can extract from it.
+"""
+
+from __future__ import annotations
+
+import base64
+import json
+import os
+import re
+import subprocess
+import time
+from pathlib import Path
+
+from .base import GEN_TIMEOUT_SECONDS, GenRequest, GenTimeoutError, ProviderRun, provider_binary, provider_subprocess_env, verify_png
+
+# codex carries the inline base64 on a version-specific record. Both are
+# first-class canonical records (not a fallback) — read whichever the running
+# codex emits. v0.140.0: response_item `image_generation_call`. v0.144.1:
+# event_msg `image_generation_end` (+status, saved_path — saved_path untrusted).
+_RESULT_TYPES = ("image_generation_call", "image_generation_end")
+# The session id that names the rollout jsonl. v0.144.1 `codex exec --json` emits
+# it as `{"type":"thread.started","thread_id":"<uuid>"}` on stdout; older codex
+# printed a `session id: <uuid>` text line. Both are canonical per version.
+_SID_RE = re.compile(r"session id: ([0-9a-f-]+)")
+# The official way to invoke a codex skill explicitly is the `$<skill>` prompt
+# mention, and image generation lives in the bundled `imagegen` system skill
+# (`<Codex state root>/skills/.system/imagegen/agents/openai.yaml` ships
+# `default_prompt: "Use $imagegen to make or edit an image for this project."`).
+# We state the trigger rather than describing the tool in prose so the invocation
+# contract is explicit and single-owned here.
+#
+# Scope of the trigger: naming the skill does not create the tool. Whether the
+# built-in `image_gen` tool is offered to the session at all is a capability of
+# the account behind the active Codex state root (see `_no_image_records_message`),
+# so this trigger is an alignment with the official invocation contract, not a fix
+# for a session that is never offered the tool.
+_SKILL_TRIGGER = "$imagegen"
+
+
+def _parse_session_id(stdout: str) -> str | None:
+ for line in stdout.splitlines():
+ line = line.strip()
+ if not line:
+ continue
+ try:
+ event = json.loads(line)
+ except json.JSONDecodeError:
+ continue
+ if isinstance(event, dict) and event.get("thread_id"):
+ return str(event["thread_id"])
+ hits = _SID_RE.findall(stdout)
+ return hits[-1] if hits else None
+
+
+def _extract_stream_errors(stdout: str) -> list[str]:
+ """Pull the human-readable failure cause out of the `codex exec --json` stream.
+
+ codex reports a fatal error (e.g. an unsupported model) as a `turn.failed` or
+ top-level `error` event on **stdout**, not stderr — so surfacing only the exit
+ code and stderr leaves the real reason invisible. Unwraps the API error JSON
+ that codex nests inside `message`."""
+ msgs: list[str] = []
+ for line in stdout.splitlines():
+ line = line.strip()
+ if not line:
+ continue
+ try:
+ event = json.loads(line)
+ except json.JSONDecodeError:
+ continue
+ if not isinstance(event, dict):
+ continue
+ if event.get("type") == "turn.failed":
+ raw = (event.get("error") or {}).get("message")
+ elif event.get("type") == "error":
+ raw = event.get("message")
+ else:
+ continue
+ if not raw:
+ continue
+ text = raw
+ try:
+ inner = json.loads(raw)
+ if isinstance(inner, dict):
+ text = (inner.get("error") or {}).get("message") or inner.get("message") or raw
+ except (json.JSONDecodeError, TypeError):
+ pass
+ text = str(text).strip()
+ if text and text not in msgs:
+ msgs.append(text)
+ return msgs
+
+
+def _resolve_codex_home() -> Path:
+ """Return the one state root used by both the Codex child and this adapter."""
+ configured = os.environ.get("CODEX_HOME")
+ if configured is None:
+ return Path.home() / ".codex"
+ if not configured.strip():
+ raise SystemExit("codex-gen: CODEX_HOME is set but empty; refusing to use the default root")
+ return Path(configured).expanduser().resolve()
+
+
+def _rollout_files(sessions_root: Path) -> tuple[Path, ...]:
+ """List rollout files deterministically without following a second state root."""
+ if not sessions_root.exists():
+ return ()
+ if not sessions_root.is_dir():
+ raise SystemExit(f"codex-gen: Codex sessions root is not a directory: {sessions_root}")
+ try:
+ return tuple(
+ sorted(
+ (path.resolve() for path in sessions_root.rglob("rollout-*.jsonl") if path.is_file()),
+ key=lambda path: str(path),
+ )
+ )
+ except OSError as exc:
+ raise SystemExit(f"codex-gen: cannot scan Codex sessions root {sessions_root}: {exc}") from exc
+
+
+def _resolve_rollout(
+ session_id: str,
+ sessions_root: Path,
+ *,
+ preexisting: set[Path] | frozenset[Path] | None = None,
+) -> Path:
+ """Resolve exactly one newly-created rollout for one Codex session."""
+ suffix = f"-{session_id}.jsonl"
+ hits = [path for path in _rollout_files(sessions_root) if path.name.endswith(suffix)]
+ if not hits:
+ raise SystemExit(
+ f"codex-gen: no rollout jsonl for session {session_id!r} under {sessions_root}"
+ )
+ if len(hits) > 1:
+ rendered = "\n".join(f" - {path}" for path in hits)
+ raise SystemExit(
+ f"codex-gen: multiple rollout jsonl files for session {session_id!r} under "
+ f"{sessions_root}; refusing to choose by mtime:\n{rendered}"
+ )
+ rollout = hits[0]
+ stale = {path.resolve() for path in (preexisting or ())}
+ if rollout in stale:
+ raise SystemExit(
+ f"codex-gen: pre-existing stale rollout for session {session_id!r}: {rollout}"
+ )
+ return rollout
+
+
+def _collect_inline_results(rollout: Path) -> list[str]:
+ results: list[str] = []
+ with rollout.open(encoding="utf-8") as handle:
+ for line in handle:
+ line = line.strip()
+ if not line:
+ continue
+ try:
+ record = json.loads(line)
+ except json.JSONDecodeError:
+ continue
+ payload = record.get("payload", {}) or {}
+ if payload.get("type") not in _RESULT_TYPES or not payload.get("result"):
+ continue
+ status = payload.get("status")
+ if status is not None and status != "completed":
+ raise SystemExit(f"codex-gen: image_gen call ended with status={status!r} in {rollout}")
+ results.append(payload["result"])
+ return results
+
+
+def _decode_png(b64: str, dest: Path) -> None:
+ raw = base64.b64decode(b64)
+ dest.parent.mkdir(parents=True, exist_ok=True)
+ dest.write_bytes(raw)
+ verify_png(dest)
+
+
+def _build_prompt(user_prompt: str) -> str:
+ """Wrap the caller's prompt in the transport-level skill trigger.
+
+ The sprite-request prompt is the caller's SSoT and is passed through verbatim;
+ this adapter is the one place that owns the codex invocation contract.
+ """
+ return (
+ f"{_SKILL_TRIGGER} 스킬로 built-in image_gen 도구를 정확히 1번 호출해서 "
+ "다음 프롬프트의 이미지 1장만 생성해줘.\n"
+ "미리보기 전용이라 생성된 파일은 기본 경로에 그대로 두면 된다.\n"
+ "파일 저장·이동·복사·셸 명령·코드 작성·경로 보고 전부 금지. 생성만 하고 끝.\n\n"
+ "프롬프트:\n"
+ f"{user_prompt}\n"
+ )
+
+
+def _no_image_records_message(rollout: Path, codex_home: Path) -> str:
+ """State an empty rollout as a capability failure, not a list of guesses.
+
+ Built-in image generation is a capability of the account behind the active
+ Codex state root. When the session is not offered the tool, it cannot be
+ talked into it: not by the prompt, not by the model, and not by a config
+ toggle. The only remedy is to run against a state root whose account provides
+ it, so that is what this message says.
+ """
+ return (
+ "codex-gen: the built-in image_gen tool never ran in this codex session — "
+ f"zero {' / '.join(_RESULT_TYPES)} records in {rollout}\n"
+ f" the prompt carries the official {_SKILL_TRIGGER} skill trigger, so the tool was "
+ "not offered to the session rather than merely not chosen.\n"
+ f" the account behind this Codex state root ({codex_home}) does not provide the "
+ "built-in image_gen capability.\n"
+ " select a Codex state root whose account provides it (`codex login status`), or "
+ "generate with another provider. A config feature toggle does not grant it."
+ )
+
+
+class CodexProvider:
+ """Generate one image through codex `image_gen`."""
+
+ name = "codex"
+
+ def __init__(self, *, keep_session: bool = False) -> None:
+ self.keep_session = keep_session
+
+ def generate(self, request: GenRequest, workdir: Path) -> ProviderRun:
+ codex_home = _resolve_codex_home()
+ if not codex_home.is_dir():
+ raise SystemExit(
+ f"codex-gen: Codex state root does not exist or is not a directory: {codex_home}"
+ )
+ sessions_root = codex_home / "sessions"
+ preexisting_rollouts = set(_rollout_files(sessions_root))
+ gen_dir = codex_home / "generated_images"
+ try:
+ gen_dir.mkdir(parents=True, exist_ok=True)
+ except OSError as exc:
+ raise SystemExit(f"codex-gen: cannot create Codex generated-images dir {gen_dir}: {exc}") from exc
+ cmd = [
+ provider_binary("codex"),
+ "exec",
+ "--json",
+ "--sandbox",
+ "workspace-write",
+ "--skip-git-repo-check",
+ "--color",
+ "never",
+ "--add-dir",
+ str(gen_dir),
+ "-C",
+ str(workdir),
+ ]
+ if request.model:
+ cmd += ["--model", request.model]
+ for ref in request.refs:
+ cmd += ["-i", str(Path(ref).expanduser().resolve())]
+ cmd += ["-", ]
+
+ prompt = _build_prompt(request.prompt)
+ started = time.monotonic()
+ child_env = provider_subprocess_env()
+ if "CODEX_HOME" in os.environ:
+ child_env["CODEX_HOME"] = str(codex_home)
+ # A headless provider must not inherit parent orchestration identity or
+ # lifecycle controls (see base.provider_subprocess_env).
+ try:
+ completed = subprocess.run(
+ cmd, input=prompt, capture_output=True, text=True, encoding="utf-8", env=child_env,
+ timeout=GEN_TIMEOUT_SECONDS,
+ )
+ except subprocess.TimeoutExpired:
+ raise GenTimeoutError(
+ f"codex-gen: no completion within {GEN_TIMEOUT_SECONDS}s — "
+ "provider stream stalled; child killed (gen-timeout)")
+ elapsed = time.monotonic() - started
+ stdout = completed.stdout or ""
+ if completed.returncode != 0:
+ stream_errors = _extract_stream_errors(stdout)
+ tail = (completed.stderr or "").strip().splitlines()[-20:]
+ detail = "\n".join(stream_errors + tail).strip() or "(no error detail on stdout/stderr)"
+ raise SystemExit(
+ f"codex-gen: codex exec exited {completed.returncode}\n{detail}"
+ )
+
+ session_id = _parse_session_id(stdout)
+ if not session_id:
+ raise SystemExit(
+ "codex-gen: no thread/session id in codex stdout — image_gen was not reached.\n"
+ " check `codex login status` and `--sandbox workspace-write`."
+ )
+ rollout = _resolve_rollout(
+ session_id,
+ sessions_root,
+ preexisting=preexisting_rollouts,
+ )
+ results = _collect_inline_results(rollout)
+ if not results:
+ raise SystemExit(_no_image_records_message(rollout, codex_home))
+ _decode_png(results[-1], request.raw)
+
+ if not self.keep_session:
+ try:
+ rollout.unlink()
+ except OSError as exc:
+ raise SystemExit(f"codex-gen: failed to remove consumed rollout {rollout}: {exc}") from exc
+
+ return ProviderRun(
+ provider=self.name,
+ elapsed_seconds=elapsed,
+ model=request.model,
+ session_id=session_id,
+ extra={"inline_results": len(results), "rollout_cleaned": not self.keep_session},
+ )
diff --git a/sprite_gen/gen/generate_image.py b/sprite_gen/gen/generate_image.py
new file mode 100644
index 0000000..e6f7e63
--- /dev/null
+++ b/sprite_gen/gen/generate_image.py
@@ -0,0 +1,18 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Deprecated shim — image generation now lives in `sprite_gen.gen`.
+
+This module previously stood in as a desktop-only placeholder during the package
+split. Provider-backed generation (codex `image_gen`, grok Imagine) is now a
+first-class engine module: `sprite_gen.gen` / CLI `sprite-gen gen`. Keeping two
+generation surfaces would violate SSoT, so this shim redirects and fails loudly
+if called directly.
+"""
+
+from __future__ import annotations
+
+
+def run(**_kwargs: object) -> int:
+ raise SystemExit(
+ "sprite_gen.gen.generate_image is retired — use `sprite_gen.gen` "
+ "(CLI: `sprite-gen gen --provider codex|grok --prompt ... --out ...`)"
+ )
diff --git a/sprite_gen/gen/grok_provider.py b/sprite_gen/gen/grok_provider.py
new file mode 100644
index 0000000..4e68f35
--- /dev/null
+++ b/sprite_gen/gen/grok_provider.py
@@ -0,0 +1,104 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Grok Imagine provider (xAI OAuth, no API key).
+
+grok build ships an Imagine skill with `image_gen` (text -> new image) and
+`image_edit` (edit an existing image). Unlike codex, grok's tool result is not
+inline base64 — grok (the agent) holds the produced file and can move it. We run
+grok headless with `--always-approve` (media/shell must be auto-approved; plain
+`--write`/acceptEdits blocks tool execution and returns an empty answer) and
+instruct it to write the final PNG to an exact absolute path. Truth is the PNG on
+disk at that path, never grok's text (No Silent Fallback).
+
+Model note: image tools route to the grok-build model, which 400s on
+`reasoningEffort` — so this provider never passes `--effort`.
+"""
+
+from __future__ import annotations
+
+import subprocess
+import time
+from pathlib import Path
+
+from .base import GEN_TIMEOUT_SECONDS, GenRequest, GenTimeoutError, ProviderRun, provider_binary, provider_subprocess_env, verify_png
+
+
+def _build_prompt(request: GenRequest) -> str:
+ raw = str(request.raw)
+ aspect = request.aspect_ratio or "auto"
+ lines = [
+ "You are generating exactly one image, then saving it. Do only this:",
+ "",
+ ]
+ if request.refs:
+ ref_list = ", ".join(str(Path(r).expanduser().resolve()) for r in request.refs)
+ lines += [
+ f"1. Call `image_edit` once using these source image(s) as reference: {ref_list}",
+ " Apply this instruction while keeping the referenced subject/style consistent:",
+ f" {request.prompt}",
+ ]
+ else:
+ lines += [
+ f"1. Call `image_gen` once with aspect_ratio `{aspect}` and this prompt:",
+ f" {request.prompt}",
+ ]
+ lines += [
+ f"2. Save the produced image to EXACTLY this absolute path as a PNG file: {raw}",
+ " Overwrite it if it already exists. Use the shell to copy/convert the produced",
+ " file to that path if the tool wrote it elsewhere. Do not resize or restyle it.",
+ f"3. Print only the final absolute path ({raw}). Do not do anything else — no extra",
+ " images, no edits, no commentary, no other files.",
+ ]
+ return "\n".join(lines)
+
+
+class GrokProvider:
+ """Generate one image through grok Imagine `image_gen` / `image_edit`."""
+
+ name = "grok"
+
+ def generate(self, request: GenRequest, workdir: Path) -> ProviderRun:
+ request.raw.parent.mkdir(parents=True, exist_ok=True)
+ cmd = [
+ provider_binary("grok"),
+ "-p",
+ _build_prompt(request),
+ "--output-format",
+ "plain",
+ "--sandbox",
+ "workspace",
+ "--always-approve",
+ "--cwd",
+ str(workdir),
+ ]
+ if request.model:
+ cmd += ["-m", request.model]
+
+ started = time.monotonic()
+ # env: parent minus orchestrator session env — same reason as codex
+ # (base.provider_subprocess_env). grok hooks are off today, but a headless
+ # generation subprocess must never carry the parent worker's endpoint
+ # identity regardless of the engine's current hook config.
+ try:
+ completed = subprocess.run(cmd, capture_output=True, text=True, encoding="utf-8",
+ env=provider_subprocess_env(), timeout=GEN_TIMEOUT_SECONDS)
+ except subprocess.TimeoutExpired:
+ raise GenTimeoutError(
+ f"grok-gen: no completion within {GEN_TIMEOUT_SECONDS}s — "
+ "provider stream stalled; child killed (gen-timeout)")
+ elapsed = time.monotonic() - started
+ if completed.returncode != 0:
+ tail = (completed.stderr or "").strip().splitlines()[-20:]
+ raise SystemExit(
+ f"grok-gen: grok exited {completed.returncode} (empty answer + non-zero = blocked exec or login).\n"
+ + "\n".join(tail)
+ )
+ # Verify the real file grok wrote, not its text. Missing/not-a-PNG fails loudly.
+ verify_png(request.raw)
+
+ return ProviderRun(
+ provider=self.name,
+ elapsed_seconds=elapsed,
+ model=request.model,
+ session_id=None,
+ extra={"stdout_tail": "\n".join((completed.stdout or "").strip().splitlines()[-5:])},
+ )
diff --git a/sprite_gen/gen/prepare.py b/sprite_gen/gen/prepare.py
new file mode 100644
index 0000000..a1abd6c
--- /dev/null
+++ b/sprite_gen/gen/prepare.py
@@ -0,0 +1,1222 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Prepare a sprite-gen component-row run.
+
+This script owns the numeric sprite recipe. It writes one request JSON, one
+layout guide per state, and one prompt per state. Image generation should read
+these files instead of hand-copying frame counts into ad hoc prompts.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import re
+import shutil
+import sys
+from collections import deque
+from pathlib import Path
+from typing import Any
+
+from PIL import Image, ImageDraw
+
+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
+
+
+# Default safe margin is proportional to the cell dimension (floored), not a fixed
+# pixel count — 9.4% keeps the same relative reserve at every cell size
+# (256 -> 24px, 128 -> 12px). An explicit request/CLI value stays absolute.
+DEFAULT_SAFE_MARGIN_RATIO = 0.094
+
+DEFAULT_STATES: dict[str, dict[str, Any]] = {
+ "idle": {"frames": 4, "fps": 4, "loop": True, "action": "subtle breathing and blinking"},
+ "attack": {
+ "frames": 4,
+ "fps": 8,
+ "loop": False,
+ "action": "simple windup, strike, recovery attack pose sequence with no detached effects",
+ },
+ "jump": {"frames": 4, "fps": 8, "loop": False, "action": "jump arc through body position only"},
+ "wave": {
+ "frames": 4,
+ "fps": 6,
+ "loop": False,
+ "action": "friendly hand wave gesture; arm changes clearly while feet stay planted",
+ },
+}
+
+# 스타일의 SSoT 는 첨부된 베이스/앵커 이미지다. 텍스트로 체형·등신·아웃라인
+# 굵기·디테일 밀도를 재기술하면 레퍼런스와 경쟁해 identity 가 흘러간다
+# (2026-07-05 사고: 기본값의 "compact chibi/chunky/thick outline" 조항이
+# 슬림 베이스를 계속 뭉툭하게 되돌렸다). 기본값은 레퍼런스 추종 + 금지선만.
+STYLE_DEFAULT = (
+ "match the attached base/anchor reference image EXACTLY: same pixel density "
+ "(logical pixel block size), same body proportions, same outline weight, same "
+ "palette, same shading style, same level of detail. Do not restyle, do not "
+ "change proportions, do not add or remove detail density. Avoid polished "
+ "illustration, painterly rendering, anime key art, 3D render, vector app-icon "
+ "polish, glossy lighting, soft gradients, and anti-aliased high-detail edges."
+)
+
+TRANSPARENCY_ARTIFACT_RULES = [
+ "Prefer pose, expression, and silhouette changes over decorative effects.",
+ "Effects are allowed only when state-relevant, opaque, hard-edged, sprite-like, fully inside the same frame slot, and physically touching or overlapping the character silhouette.",
+ "Do not draw detached effects: floating stars, loose sparkles, floating punctuation, floating icons, separated smoke clouds, loose dust, disconnected outline bits, or stray pixels.",
+ "Do not draw wave marks, motion arcs, speed lines, action streaks, afterimages, blur, smears, halos, glows, auras, floor patches, cast shadows, contact shadows, drop shadows, oval floor shadows, landing marks, or impact bursts.",
+ "Do not include text, labels, frame numbers, visible grids, guide marks, speech bubbles, thought bubbles, UI panels, code snippets, scenery, checkerboard transparency, white backgrounds, or black backgrounds.",
+ "Reject any pose that is cropped, overlaps another pose, crosses into a neighboring frame slot, or creates a separate disconnected component that is not attached to the character.",
+]
+
+STATE_REQUIREMENTS = {
+ "running-right": [
+ "Show rightward locomotion through body, arm, leg, hair, and prop movement only.",
+ "Use distinct gait poses that create a readable cycle instead of repeated standing or static bobbing.",
+ "Do not draw speed lines, dust clouds, floor shadows, motion trails, or detached motion effects.",
+ ],
+ "running-left": [
+ "Show leftward locomotion through body, arm, leg, hair, and prop movement only.",
+ "Use distinct gait poses that create a readable cycle instead of repeated standing or static bobbing.",
+ "If an additional rightward gait row is attached, use it only as a motion-rhythm reference for limb phase and body bounce; do not copy its facing direction or redraw the character from that row.",
+ "Do not draw speed lines, dust clouds, floor shadows, motion trails, or detached motion effects.",
+ ],
+ "running-front-right": [
+ "Show 45-degree diagonal locomotion toward camera-right and slightly toward the viewer.",
+ "Keep the body three-quarter-front, not pure side view and not straight front view.",
+ "Use alternating foot-contact phases so the left and right legs clearly trade forward reach.",
+ "Do not draw speed lines, dust clouds, floor shadows, motion trails, or detached motion effects.",
+ ],
+ "running-front-left": [
+ "Show 45-degree diagonal locomotion toward camera-left and slightly toward the viewer.",
+ "Keep the body three-quarter-front, not pure side view and not straight front view.",
+ "Use alternating foot-contact phases so the left and right legs clearly trade forward reach.",
+ "Do not draw speed lines, dust clouds, floor shadows, motion trails, or detached motion effects.",
+ ],
+ "running-back-right": [
+ "Show 45-degree diagonal locomotion away from the viewer toward camera-right.",
+ "Keep the body three-quarter-back, with the face partly hidden but the character still identifiable.",
+ "Use alternating foot-contact phases so the left and right legs clearly trade backward/forward reach.",
+ "Do not draw speed lines, dust clouds, floor shadows, motion trails, or detached motion effects.",
+ ],
+ "running-back-left": [
+ "Show 45-degree diagonal locomotion away from the viewer toward camera-left.",
+ "Keep the body three-quarter-back, with the face partly hidden but the character still identifiable.",
+ "Use alternating foot-contact phases so the left and right legs clearly trade backward/forward reach.",
+ "Do not draw speed lines, dust clouds, floor shadows, motion trails, or detached motion effects.",
+ ],
+ "run": [
+ "Show locomotion through body, arm, leg, hair, and prop movement only.",
+ "Use distinct gait poses that create a readable cycle instead of repeated standing or static bobbing.",
+ "Do not draw speed lines, dust clouds, floor shadows, motion trails, or detached motion effects.",
+ ],
+ "walk": [
+ "Show locomotion through body, arm, leg, hair, and prop movement only.",
+ "Use distinct gait poses that create a readable cycle instead of repeated standing or static bobbing.",
+ "Do not draw speed lines, dust clouds, floor shadows, motion trails, or detached motion effects.",
+ ],
+ "frontwalk": [
+ "Show front-view walking through alternating leg, arm, shoulder, and body-height changes.",
+ "This is difficult: make the foot-contact and passing poses visibly different without changing identity.",
+ "Do not draw speed lines, dust clouds, floor shadows, motion trails, or detached motion effects.",
+ ],
+ "45_frontwalk": [
+ "Show three-quarter-front walking through alternating leg, arm, shoulder, and body-height changes.",
+ "This is difficult: make the foot-contact and passing poses visibly different without changing identity.",
+ "Do not draw speed lines, dust clouds, floor shadows, motion trails, or detached motion effects.",
+ ],
+ "wave": [
+ "Show the gesture through arm pose only: arm down, arm raised, hand tilted, arm returning.",
+ "Keep the feet planted unless the action explicitly requests stepping.",
+ "Do not draw wave marks, motion arcs, lines, sparkles, symbols, or floating effects around the hand.",
+ ],
+ "jump": [
+ "Show the jump through pose and vertical body position only: anticipation, lift, airborne peak, descent, settle.",
+ "Do not draw ground shadows, contact shadows, oval shadows, landing marks, dust, smears, or motion marks under the character.",
+ ],
+}
+
+RUN_PHASE_CYCLE = [
+ {
+ "name": "contact",
+ "body_y": 0,
+ "front_leg": "forward_straight",
+ "back_leg": "back_extended",
+ "note": "front foot contacts ground, back foot pushes off",
+ },
+ {
+ "name": "down",
+ "body_y": 6,
+ "front_leg": "under_bent",
+ "back_leg": "back_bent",
+ "note": "weight drops over planted foot",
+ },
+ {
+ "name": "passing",
+ "body_y": 2,
+ "front_leg": "under_vertical",
+ "back_leg": "passing_forward",
+ "note": "swing leg passes under body",
+ },
+ {
+ "name": "up",
+ "body_y": -6,
+ "front_leg": "back_lifted",
+ "back_leg": "forward_lifted",
+ "note": "body lifts before the opposite contact",
+ },
+ {
+ "name": "opposite_contact",
+ "body_y": 0,
+ "front_leg": "back_extended",
+ "back_leg": "forward_straight",
+ "note": "opposite foot contacts ground",
+ },
+ {
+ "name": "opposite_down",
+ "body_y": 6,
+ "front_leg": "back_bent",
+ "back_leg": "under_bent",
+ "note": "weight drops over the opposite planted foot",
+ },
+ {
+ "name": "opposite_passing",
+ "body_y": 2,
+ "front_leg": "passing_forward",
+ "back_leg": "under_vertical",
+ "note": "first leg passes under body",
+ },
+ {
+ "name": "opposite_up",
+ "body_y": -6,
+ "front_leg": "forward_lifted",
+ "back_leg": "back_lifted",
+ "note": "body lifts back toward frame 1",
+ },
+]
+
+CHROMA_CANDIDATES = [
+ ("magenta", "#FF00FF"),
+ ("green", "#00FF00"),
+ ("cyan", "#00FFFF"),
+ ("blue", "#004DFF"),
+]
+
+
+def parse_hex_color(value: str) -> tuple[int, int, int]:
+ if not re.fullmatch(r"#[0-9a-fA-F]{6}", value):
+ raise SystemExit(f"invalid chroma key color: {value}; expected #RRGGBB")
+ return tuple(int(value[index : index + 2], 16) for index in (1, 3, 5))
+
+
+def rgb_to_hex(rgb: tuple[int, int, int]) -> str:
+ return f"#{rgb[0]:02X}{rgb[1]:02X}{rgb[2]:02X}"
+
+
+# The reference is sampled with NEAREST, not LANCZOS: a resampling filter that
+# averages neighbours invents colors the base never contained, and every one of
+# those invented colors sits on the line between the chroma background and the
+# subject — exactly the region the candidate scoring must not see. 256px keeps
+# small features (eyes, gems) that a 128px sample would average away.
+REFERENCE_SAMPLE_SIZE = 256
+
+# A base for this pipeline is a subject on a flat chroma background, so the
+# background is recognisable from the border ring alone.
+BACKGROUND_TOLERANCE = 48.0
+BACKGROUND_MIN_OPAQUE_BORDER = 0.25
+BACKGROUND_BORDER_COVERAGE = 0.75
+
+# The subject is anti-aliased against the background over ~1-2px. Those blend
+# pixels are background contamination, not subject material; grow the background
+# mask to swallow the band.
+BACKGROUND_EDGE_DILATION = 2
+
+# A key-colored region enclosed by the subject is ambiguous: either a hole that
+# shows the background through the silhouette, or material the artist drew in the
+# key hue. A hole is a flat fill, so nearly all of it sits on the exact background
+# color; drawn material carries shading and spreads away from it. Holes are
+# background; drawn material stays subject so the erase-radius gate can reject the
+# key that would delete it (the v1.10.1 key-tint protection).
+BACKGROUND_FLAT_TOLERANCE = 16.0
+ENCLOSED_FLAT_FRACTION = 0.60
+
+# Generated art carries isolated spill/compression specks inside the silhouette
+# (a lone `(233, 7, 202)` in a hair gap). A single pixel is not a feature, and
+# the nearest-pixel safety gate is otherwise dominated by them. Keep only pixels
+# that belong to a region of their own color.
+SPECKLE_NEIGHBOR_TOLERANCE = 40.0
+SPECKLE_MIN_SIMILAR_NEIGHBORS = 3
+
+# Mirrors the default --key-threshold in extract_sprite_row_frames.py: any subject
+# pixel within this color distance of the chroma key is removed at extraction, so a
+# key whose nearest subject pixel falls inside this radius will erase that feature.
+MIN_SUBJECT_KEY_DISTANCE = 96.0
+
+_NEIGHBORS_4 = ((1, 0), (-1, 0), (0, 1), (0, -1))
+_NEIGHBORS_8 = ((-1, -1), (0, -1), (1, -1), (-1, 0), (1, 0), (-1, 1), (0, 1), (1, 1))
+
+
+def _border_coordinates(width: int, height: int) -> list[tuple[int, int]]:
+ if width < 2 or height < 2:
+ return [(x, y) for y in range(height) for x in range(width)]
+ ring = [(x, 0) for x in range(width)] + [(x, height - 1) for x in range(width)]
+ ring += [(0, y) for y in range(1, height - 1)] + [(width - 1, y) for y in range(1, height - 1)]
+ return ring
+
+
+def detect_reference_background(image: Image.Image) -> dict[str, Any]:
+ """Classify the base's background from its border ring.
+
+ Returns one of three observable modes. ``flat`` carries the background color;
+ ``transparent`` and ``heterogeneous`` carry none, and the caller excludes
+ nothing beyond the alpha and near-white rules.
+ """
+ width, height = image.size
+ pixels = image.load()
+ ring = _border_coordinates(width, height)
+ opaque = [(x, y) for x, y in ring if pixels[x, y][3] > 16]
+ opaque_fraction = len(opaque) / len(ring) if ring else 0.0
+ if opaque_fraction < BACKGROUND_MIN_OPAQUE_BORDER:
+ return {"mode": "transparent", "opaque_border_fraction": round(opaque_fraction, 3)}
+
+ # Quantize to 16-level buckets so a flat fill survives PNG/codec jitter, then
+ # recover the true color as the mean of the winning bucket.
+ buckets: dict[tuple[int, int, int], list[tuple[int, int, int]]] = {}
+ for x, y in opaque:
+ color = pixels[x, y][:3]
+ buckets.setdefault(tuple(channel // 16 for channel in color), []).append(color)
+ members = max(buckets.values(), key=len)
+ background = tuple(round(sum(m[index] for m in members) / len(members)) for index in range(3))
+
+ within = sum(1 for x, y in opaque if color_distance(pixels[x, y][:3], background) <= BACKGROUND_TOLERANCE)
+ coverage = within / len(opaque)
+ if coverage < BACKGROUND_BORDER_COVERAGE:
+ return {
+ "mode": "heterogeneous",
+ "opaque_border_fraction": round(opaque_fraction, 3),
+ "border_coverage": round(coverage, 3),
+ "note": (
+ f"border ring is not a flat fill (largest color covers {coverage:.0%} "
+ f"of it, needs {BACKGROUND_BORDER_COVERAGE:.0%}); no background pixels "
+ f"were excluded, so candidate distances may be skewed by the background"
+ ),
+ }
+ return {
+ "mode": "flat",
+ "hex": rgb_to_hex(background),
+ "rgb": list(background),
+ "opaque_border_fraction": round(opaque_fraction, 3),
+ "border_coverage": round(coverage, 3),
+ }
+
+
+def _background_mask(image: Image.Image, background: dict[str, Any]) -> list[list[bool]]:
+ """Mark every pixel that belongs to the base's background rather than its subject."""
+ width, height = image.size
+ pixels = image.load()
+ transparent = [[pixels[x, y][3] <= 16 for x in range(width)] for y in range(height)]
+ mask = [row[:] for row in transparent]
+
+ if background["mode"] == "flat":
+ key = tuple(background["rgb"])
+ near = [
+ [transparent[y][x] or color_distance(pixels[x, y][:3], key) <= BACKGROUND_TOLERANCE for x in range(width)]
+ for y in range(height)
+ ]
+ visited = [[False] * width for _ in range(height)]
+ enclosed_background = enclosed_material = 0
+ for start_y in range(height):
+ for start_x in range(width):
+ if not near[start_y][start_x] or visited[start_y][start_x]:
+ continue
+ visited[start_y][start_x] = True
+ queue = deque([(start_x, start_y)])
+ component: list[tuple[int, int]] = []
+ grounded = False
+ while queue:
+ x, y = queue.popleft()
+ component.append((x, y))
+ if x in (0, width - 1) or y in (0, height - 1) or transparent[y][x]:
+ grounded = True
+ for dx, dy in _NEIGHBORS_8:
+ nx, ny = x + dx, y + dy
+ if 0 <= nx < width and 0 <= ny < height and near[ny][nx] and not visited[ny][nx]:
+ visited[ny][nx] = True
+ queue.append((nx, ny))
+ if not grounded:
+ flat = sum(
+ 1 for x, y in component if color_distance(pixels[x, y][:3], key) <= BACKGROUND_FLAT_TOLERANCE
+ )
+ if flat / len(component) < ENCLOSED_FLAT_FRACTION:
+ enclosed_material += len(component)
+ continue # drawn key-hued material: keep it as subject
+ enclosed_background += len(component)
+ for x, y in component:
+ mask[y][x] = True
+ background["enclosed_background_pixels"] = enclosed_background
+ background["enclosed_material_pixels"] = enclosed_material
+
+ for _ in range(BACKGROUND_EDGE_DILATION):
+ grown = [
+ (x, y)
+ for y in range(height)
+ for x in range(width)
+ if not mask[y][x]
+ and any(0 <= x + dx < width and 0 <= y + dy < height and mask[y + dy][x + dx] for dx, dy in _NEIGHBORS_4)
+ ]
+ for x, y in grown:
+ mask[y][x] = True
+ return mask
+
+
+def _subject_pixels(image: Image.Image, background: dict[str, Any]) -> list[tuple[int, int, int]]:
+ width, height = image.size
+ pixels = image.load()
+ mask = _background_mask(image, background)
+ candidate = [
+ [not mask[y][x] and not all(channel > 244 for channel in pixels[x, y][:3]) for x in range(width)]
+ for y in range(height)
+ ]
+ subject: list[tuple[int, int, int]] = []
+ for y in range(height):
+ for x in range(width):
+ if not candidate[y][x]:
+ continue
+ color = pixels[x, y][:3]
+ similar = 0
+ for dx, dy in _NEIGHBORS_8:
+ nx, ny = x + dx, y + dy
+ if 0 <= nx < width and 0 <= ny < height and candidate[ny][nx]:
+ if color_distance(pixels[nx, ny][:3], color) <= SPECKLE_NEIGHBOR_TOLERANCE:
+ similar += 1
+ if similar >= SPECKLE_MIN_SIMILAR_NEIGHBORS:
+ subject.append(color)
+ return subject
+
+
+def analyze_reference(path: Path | None) -> tuple[list[tuple[int, int, int]], dict[str, Any]]:
+ """Sample the base into (subject pixels, background classification)."""
+ if path is None or not path.is_file():
+ return [], {"mode": "absent"}
+ with Image.open(path) as opened:
+ image = opened.convert("RGBA")
+ image.thumbnail((REFERENCE_SAMPLE_SIZE, REFERENCE_SAMPLE_SIZE), Image.Resampling.NEAREST)
+ background = detect_reference_background(image)
+ pixels = _subject_pixels(image, background)
+ background["subject_pixels"] = len(pixels)
+ return pixels, background
+
+
+def sampled_reference_pixels(path: Path | None) -> list[tuple[int, int, int]]:
+ """Subject pixels of the base, with its chroma background excluded.
+
+ A base in this pipeline always carries a chroma background. Counting those
+ pixels as subject pins every candidate that matches the current background to
+ ``min_subject_distance ~= 0``, so ``auto`` could never re-select the key the
+ base was drawn against.
+ """
+ return analyze_reference(path)[0]
+
+
+def choose_chroma_key(reference: Path | None, requested: str) -> dict[str, Any]:
+ if requested.lower() != "auto":
+ rgb = parse_hex_color(requested)
+ hex_value = rgb_to_hex(rgb)
+ name = next((candidate_name for candidate_name, candidate_hex in CHROMA_CANDIDATES if candidate_hex == hex_value), "manual")
+ return {"name": name, "hex": hex_value, "rgb": list(rgb), "selection": "manual"}
+
+ pixels, background = analyze_reference(reference)
+ if background["mode"] == "heterogeneous":
+ print(f"WARNING: chroma_key auto: {background['note']}", file=sys.stderr)
+ if not pixels:
+ rgb = parse_hex_color("#FF00FF")
+ reason = (
+ "no base reference to sample"
+ if background["mode"] == "absent"
+ else "the base reference yielded no subject pixels once its background was excluded"
+ )
+ if background["mode"] != "absent":
+ print(f"WARNING: chroma_key auto: {reason}; defaulting to magenta", file=sys.stderr)
+ return {
+ "name": "magenta",
+ "hex": "#FF00FF",
+ "rgb": list(rgb),
+ "selection": "fallback",
+ "background": background,
+ "selection_reason": reason,
+ }
+
+ scored: list[tuple[float, float, int, str, tuple[int, int, int]]] = []
+ for preference_index, (name, hex_color) in enumerate(CHROMA_CANDIDATES):
+ rgb = parse_hex_color(hex_color)
+ distances = sorted(color_distance(rgb, pixel) for pixel in pixels)
+ percentile_index = max(0, min(len(distances) - 1, int(len(distances) * 0.01)))
+ scored.append((distances[percentile_index], distances[0], -preference_index, name, rgb))
+
+ # Rank by the 1st-percentile distance, but that metric ignores sub-1% features
+ # (eyes, gems, ear lamps): a key can look "safe" while its nearest subject pixel
+ # is still inside the erase radius. Prefer candidates that clear every subject
+ # pixel; only fall back to the raw ranking (with a warning) when none do.
+ safe = [entry for entry in scored if entry[1] > MIN_SUBJECT_KEY_DISTANCE]
+ score, min_distance, _preference, name, rgb = max(safe) if safe else max(scored)
+ result = {
+ "name": name,
+ "hex": rgb_to_hex(rgb),
+ "rgb": list(rgb),
+ "selection": "auto",
+ "score": round(score, 2),
+ "min_subject_distance": round(min_distance, 2),
+ "background": background,
+ "candidates": [
+ {
+ "name": entry[3],
+ "hex": rgb_to_hex(entry[4]),
+ "score": round(entry[0], 2),
+ "min_subject_distance": round(entry[1], 2),
+ "clears_erase_radius": entry[1] > MIN_SUBJECT_KEY_DISTANCE,
+ }
+ for entry in scored
+ ],
+ "selection_reason": (
+ f"highest 1st-percentile subject distance among the {len(safe)} candidate(s) "
+ f"clearing the {MIN_SUBJECT_KEY_DISTANCE:.0f} erase radius"
+ if safe
+ else f"no candidate clears the {MIN_SUBJECT_KEY_DISTANCE:.0f} erase radius; "
+ f"ranked by 1st-percentile subject distance alone"
+ ),
+ }
+ if min_distance <= MIN_SUBJECT_KEY_DISTANCE:
+ result["warning"] = (
+ f"nearest subject pixel is {min_distance:.1f} from {name} "
+ f"(<= {MIN_SUBJECT_KEY_DISTANCE:.0f}); that feature will be erased at extraction — "
+ f"recolor it or force a different --chroma-key"
+ )
+ print(f"WARNING: chroma_key auto: {result['warning']}", file=sys.stderr)
+ return result
+
+
+def normalize_states(raw: dict[str, Any] | None) -> dict[str, dict[str, Any]]:
+ source = raw or DEFAULT_STATES
+ normalized: dict[str, dict[str, Any]] = {}
+ for state, entry in source.items():
+ if not isinstance(entry, dict):
+ raise SystemExit(f"state {state!r} must be an object")
+ frames = int(entry.get("frames", 0))
+ if frames <= 0:
+ raise SystemExit(f"state {state!r} must have positive frames")
+ normalized[state] = {
+ "frames": frames,
+ "fps": int(entry.get("fps", DEFAULT_STATES.get(state, {}).get("fps", 6))),
+ "loop": bool(entry.get("loop", True)),
+ "action": str(entry.get("action", 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
+
+
+# What `prepare` does with an incoming `--request` / `--request-json`. It re-emits
+# `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.
+REQUEST_KEYS_CARRIED = ("cell", "states", "style", "motion_phase_guides",
+ "directions", "fit", "rig", "layers")
+# 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")
+
+
+def dropped_key_notes(raw_request: dict[str, Any]) -> list[str]:
+ """Every key of an incoming request whose value does not reach the run.
+
+ Deterministic order, one note per class. Silence here means the request was
+ carried whole — that is the point: a dropped key that says nothing looks
+ exactly like a key that was honoured.
+ """
+ notes: list[str] = []
+ dropped = sorted(set(raw_request) - set(REQUEST_KEYS_CARRIED) - set(REQUEST_KEYS_REGENERATED))
+ if dropped:
+ notes.append(
+ f"dropped top-level request key(s) {dropped}: prepare re-emits "
+ f"sprite-request.json from {list(REQUEST_KEYS_CARRIED)} and does not carry "
+ f"anything else — write them into sprite-request.json after this run if the "
+ f"pipeline is documented to read them")
+ restated = sorted(set(raw_request) & set(REQUEST_KEYS_REGENERATED))
+ if restated:
+ notes.append(
+ f"ignored incoming {restated}: prepare writes these itself (identity from "
+ f"--character-id/--description/--base-image, chroma from --chroma-key)")
+ for state in sorted(raw_request.get("states") or {}):
+ entry = (raw_request["states"] or {})[state]
+ if not isinstance(entry, dict):
+ continue
+ extra = sorted(set(entry) - set(STATE_KEYS_CARRIED))
+ if extra:
+ notes.append(
+ f"dropped states.{state} key(s) {extra}: a state entry is rebuilt as "
+ f"{list(STATE_KEYS_CARRIED)}")
+ return notes
+
+
+def normalize_cell(raw_cell: dict[str, Any], size: int, safe_margin: int | None) -> dict[str, Any]:
+ width = int(raw_cell.get("width", raw_cell.get("cell_width", raw_cell.get("size", size))))
+ height = int(raw_cell.get("height", raw_cell.get("cell_height", raw_cell.get("size", size))))
+ raw_margin_x = raw_cell.get("safe_margin_x", raw_cell.get("safe_margin", safe_margin))
+ raw_margin_y = raw_cell.get("safe_margin_y", raw_cell.get("safe_margin", safe_margin))
+ margin_x = int(width * DEFAULT_SAFE_MARGIN_RATIO) if raw_margin_x is None else int(raw_margin_x)
+ margin_y = int(height * DEFAULT_SAFE_MARGIN_RATIO) if raw_margin_y is None else int(raw_margin_y)
+ if width <= 0 or height <= 0:
+ raise SystemExit("cell width and height must be positive")
+ if margin_x < 0 or margin_y < 0 or margin_x * 2 >= width or margin_y * 2 >= height:
+ raise SystemExit("cell safe margins must fit inside cell width/height")
+ cell: dict[str, Any] = {
+ "shape": "rect" if width != height else "square",
+ "width": width,
+ "height": height,
+ "safe_margin_x": margin_x,
+ "safe_margin_y": margin_y,
+ }
+ if width == height and margin_x == margin_y:
+ cell["size"] = width
+ cell["safe_margin"] = margin_x
+ return cell
+
+
+def load_request(path: Path | None, inline_json: str | None) -> dict[str, Any]:
+ if path and inline_json:
+ raise SystemExit("use only one of --request or --request-json")
+ if path:
+ return json.loads(path.read_text(encoding="utf-8"))
+ if inline_json:
+ return json.loads(inline_json)
+ return {}
+
+
+def state_motion_phases(state: str, frames: int) -> list[dict[str, Any]]:
+ if frames != 8:
+ return []
+ if (
+ state in {"running-right", "running-left", "run", "walk"}
+ or state.startswith("running-front-")
+ or state.startswith("running-back-")
+ or state.startswith("walking-front-")
+ or state.startswith("walking-back-")
+ ):
+ return RUN_PHASE_CYCLE
+ return []
+
+
+# --- 방향 계약 (directions block) -------------------------------------------
+# base = down(정면) 기본자세 하나. 방향 앵커(<dir>_<anchor_suffix>)를 base 에서 먼저
+# 뽑고, 각 행은 자기 방향 앵커를 identity 로 생성한다 (directional-anchor-workflow.md).
+# mirror 에 오른 방향은 생성을 생략하고 런타임 미러로 커버한다 (maintainer 확정 2026-07-14).
+DIRECTION_FACING = {
+ "down": "facing the viewer (front view)",
+ "up": "facing away from the viewer (back view, no visible face)",
+ "side": "pure side profile view facing camera-right",
+ "right": "pure side profile view facing camera-right",
+ "left": "pure side profile view facing camera-left",
+ "down45": "45-degree three-quarter-front view",
+ "up45": "45-degree three-quarter-back view",
+}
+
+
+def normalize_directions(raw: dict[str, Any] | None, states: dict[str, Any]) -> dict[str, Any] | None:
+ """Validate/normalize the request `directions` block. None = 방향 계약 없음(기존 flat)."""
+ if not raw:
+ return None
+ dir_set = [str(d) for d in raw.get("set", [])]
+ if not dir_set:
+ raise SystemExit("directions.set must list at least one direction")
+ mirror = {str(k): str(v) for k, v in (raw.get("mirror") or {}).items()}
+ for target, source in mirror.items():
+ if source not in dir_set:
+ raise SystemExit(f"directions.mirror source '{source}' is not in directions.set")
+ if target in dir_set:
+ raise SystemExit(f"directions.mirror target '{target}' must not also be a generated direction")
+ anchor_suffix = str(raw.get("anchor_suffix", "idle"))
+ for state in states:
+ if not any(state.startswith(d + "_") for d in dir_set):
+ raise SystemExit(
+ f"state '{state}' does not start with a declared direction prefix "
+ f"({', '.join(dir_set)}) — direction-contract runs name states <direction>_<state>")
+ return {"set": dir_set, "mirror": mirror, "anchor_suffix": anchor_suffix}
+
+
+def direction_anchor_states(directions: dict[str, Any]) -> dict[str, str]:
+ """direction -> anchor state name (<dir>_<anchor_suffix>)."""
+ return {d: f"{d}_{directions['anchor_suffix']}" for d in directions["set"]}
+
+
+def ensure_direction_anchors(directions: dict[str, Any], states: dict[str, Any]) -> dict[str, Any]:
+ """방향 앵커 상태가 요청에 없으면 합성해 앞에 끼운다 — 앵커 없는 방향 행 생성 금지."""
+ synthesized: dict[str, Any] = {}
+ for direction, anchor in direction_anchor_states(directions).items():
+ if anchor not in states:
+ facing = DIRECTION_FACING.get(direction, f"facing the {direction} direction")
+ synthesized[anchor] = {
+ "frames": 4,
+ "fps": 4,
+ "loop": True,
+ "action": f"standing idle, {facing}; subtle breathing; canonical direction anchor derived from the base",
+ }
+ return {**synthesized, **states}
+
+
+def state_direction(state: str, directions: dict[str, Any] | None) -> str | None:
+ if not directions:
+ return None
+ return next((d for d in directions["set"] if state.startswith(d + "_")), None)
+
+
+def build_generation_plan(request: dict[str, Any]) -> dict[str, Any] | None:
+ """생성 체인 SSoT: 1단계 방향 앵커(base 기반) -> 2단계 행(방향 앵커 기반).
+
+ 미러 방향은 생성 생략을 명시적으로 기록한다 — 조용한 누락이 아니라 계약이다."""
+ directions = request.get("directions")
+ if not directions:
+ return None
+ anchors = direction_anchor_states(directions)
+ anchor_names = set(anchors.values())
+ stage_anchors = [
+ {
+ "state": anchors[d],
+ "role": "direction-anchor",
+ "direction": d,
+ "refs": ["base-source.*", guide_rel(request, anchors[d])],
+ "note": "base 는 방향 앵커 생성까지만 identity 소스다 — 앵커 수락 후 행 생성에 base 를 재부착하지 않는다",
+ }
+ for d in directions["set"]
+ ]
+ # 앵커 ref 진실 = 사람이 승인한 최종 모습(픽셀 편집·변형·삭제·재정렬 반영)이고,
+ # 그 한 장을 고르는 규칙은 `sprite_gen/curate/anchor.py` 가 소유한다 (지정 > 앵커 행 시퀀스
+ # 헤드). 그래서 플랜은 "curated export 를 알아서 찾아 붙여라" 라는 산문 대신
+ # **결정론 커맨드 + 그 커맨드가 쓰는 실제 경로**를 준다 (maintainer 확정 2026-07-19 편집
+ # 반영 요구 + 2026-07-25 앵커 프레임 직접 지정): 워커가 크롭 위치를 판단할 여지가
+ # 없어야 승인 전 모습이 identity 로 번지지 않는다.
+ stage_rows = [
+ {
+ "state": state,
+ "role": "action-row",
+ "direction": state_direction(state, directions),
+ "refs": [
+ anchor_ref_rel(state_direction(state, directions)),
+ guide_rel(request, state),
+ ],
+ # 기계 소비 필드라 **어디서나 도는 형태**로 굽는다: `sprite-gen` 콘솔 스크립트는
+ # 설치된 환경에만 있고(레포 체크아웃엔 없다), 문서의 `sprite-gen anchor` 산문은
+ # 레포 관례를 따른다 (같은 커맨드의 두 호출 형태 — 두 진실이 아니다).
+ "materialize": (
+ f"python3 -m sprite_gen.cli anchor --run-dir . "
+ f"--direction {state_direction(state, directions)}"
+ ),
+ "note": ("앵커 ref 는 파생 캐시다 — 생성 직전 위 커맨드로 큐레이션 진실에서 다시 굽는다"
+ " (`--for-state <state>` 는 붙일 경로를 그대로 출력한다)"),
+ }
+ for state in request["states"]
+ if state not in anchor_names and state_direction(state, directions)
+ ]
+ mirrored = [
+ {
+ "direction": target,
+ "mirror_of": source,
+ "note": ("생성 생략 — 런타임 미러가 기본. 미러로 부족해 재생성할 때는 반대편 행"
+ f"(raw/{source}/*.png)을 timing/scale 참조로만 부착하고, 대상 방향 앵커를"
+ " 새로 뽑아 identity 로 쓴다 (directional-anchor-workflow.md 좌우 게이트)"),
+ }
+ for target, source in directions["mirror"].items()
+ ]
+ return {
+ "version": 1,
+ "kind": "sprite-gen-generation-plan",
+ "order": [
+ {"stage": 1, "name": "direction-anchors", "items": stage_anchors},
+ {"stage": 2, "name": "action-rows", "items": stage_rows},
+ ],
+ "mirrored_directions": mirrored,
+ }
+
+
+def direction_prefix_requirements(request: dict[str, Any], state: str) -> list[str]:
+ """방향 계약 런의 프롬프트 방향 잠금 — 앵커 행은 base 기반, 일반 행은 앵커 기반."""
+ directions = request.get("directions")
+ direction = state_direction(state, directions)
+ if direction is None:
+ return []
+ facing = DIRECTION_FACING.get(direction, f"facing the {direction} direction")
+ requirements = [
+ f"Lock the whole row to {facing}. Do not average it into a different facing.",
+ ]
+ if state == direction_anchor_states(directions).get(direction):
+ requirements.append(
+ "This row is the CANONICAL DIRECTION ANCHOR for this facing: derive identity from the "
+ "attached base image, change only the facing/orientation, and keep poses minimal "
+ "(subtle breathing) so a single frame can be cropped as the anchor.")
+ else:
+ requirements.append(
+ "Derive identity from the attached accepted direction anchor for this facing, "
+ "not from any base character image.")
+ return requirements
+
+
+def directional_parts(state: str) -> tuple[str, str] | None:
+ match = re.search(r"-(front|back)-(left|right)$", state)
+ if not match:
+ return None
+ return match.group(1), match.group(2)
+
+
+def directional_requirements(state: str) -> list[str]:
+ parts = directional_parts(state)
+ if not parts:
+ return []
+ depth, side = parts
+ toward = "toward the viewer" if depth == "front" else "away from the viewer"
+ body_view = "three-quarter-front" if depth == "front" else "three-quarter-back"
+ camera_side = f"camera-{side}"
+ opposite_side = "left" if side == "right" else "right"
+ requirements = [
+ f"Lock the whole row to a 45-degree {body_view} view facing {camera_side} and slightly {toward}.",
+ f"Do not average this into a straight front, straight back, or pure side-view sprite.",
+ f"Make {camera_side} readable through face/body orientation, hair silhouette, shoulder overlap, hand/foot placement, and prop angle.",
+ "If a 4-direction reference sheet is attached, use it as the direction SSoT for facing only; do not copy its pose or state.",
+ "If a single target-direction anchor is attached, its facing direction is authoritative and overrides any paired-row reference.",
+ ]
+ if side == "left":
+ requirements.append(
+ f"If a generated {depth}-{opposite_side} basis row is attached, use it only for timing, scale, and pose-family consistency; change the facing to camera-left."
+ )
+ return requirements
+
+
+def mirrored_x(center_x: int, x: int, facing: str) -> int:
+ if facing == "left":
+ return center_x - (x - center_x)
+ return x
+
+
+def leg_points(root: tuple[int, int], pose: str, facing: str, scale: float) -> tuple[tuple[int, int], tuple[int, int]]:
+ root_x, root_y = root
+ forward = round(34 * scale)
+ back = round(32 * scale)
+ down = round(54 * scale)
+ bend = round(24 * scale)
+ lift = round(22 * scale)
+ if pose == "forward_straight":
+ knee = (root_x + round(forward * 0.45), root_y + round(down * 0.48))
+ foot = (root_x + forward, root_y + down)
+ elif pose == "back_extended":
+ knee = (root_x - round(back * 0.45), root_y + round(down * 0.48))
+ foot = (root_x - back, root_y + down)
+ elif pose == "under_bent":
+ knee = (root_x + round(bend * 0.2), root_y + round(down * 0.45))
+ foot = (root_x + round(bend * 0.55), root_y + round(down * 0.82))
+ elif pose == "back_bent":
+ knee = (root_x - round(bend * 0.65), root_y + round(down * 0.42))
+ foot = (root_x - round(bend * 0.2), root_y + round(down * 0.78))
+ elif pose == "passing_forward":
+ knee = (root_x + round(bend * 0.45), root_y + round(down * 0.35))
+ foot = (root_x + round(bend * 0.1), root_y + round(down * 0.63))
+ elif pose == "under_vertical":
+ knee = (root_x, root_y + round(down * 0.42))
+ foot = (root_x, root_y + round(down * 0.88))
+ elif pose == "forward_lifted":
+ knee = (root_x + round(forward * 0.45), root_y + round(down * 0.18))
+ foot = (root_x + round(forward * 0.7), root_y + round(down * 0.35))
+ elif pose == "back_lifted":
+ knee = (root_x - round(back * 0.45), root_y + round(down * 0.18))
+ foot = (root_x - round(back * 0.7), root_y + round(down * 0.35))
+ else:
+ knee = (root_x, root_y + round(down * 0.45))
+ foot = (root_x, root_y + down)
+ if facing == "left":
+ knee = (root_x - (knee[0] - root_x), knee[1])
+ foot = (root_x - (foot[0] - root_x), foot[1])
+ return knee, foot
+
+
+def draw_motion_phase(draw: ImageDraw.ImageDraw, slot_left: int, cell_width: int, cell_height: int, phase: dict[str, Any], facing: str) -> None:
+ scale = min(cell_width / 192, cell_height / 208)
+ center_x = slot_left + cell_width // 2
+ hip_y = round(cell_height * 0.52 + int(phase["body_y"]) * scale)
+ shoulder_y = hip_y - round(42 * scale)
+ head_y = shoulder_y - round(26 * scale)
+ hip = (center_x, hip_y)
+ shoulder = (center_x, shoulder_y)
+ head_bbox = (
+ center_x - round(11 * scale),
+ head_y - round(11 * scale),
+ center_x + round(11 * scale),
+ head_y + round(11 * scale),
+ )
+ draw.ellipse(head_bbox, outline="#6b7280", width=max(1, round(2 * scale)))
+ draw.line((shoulder, hip), fill="#6b7280", width=max(2, round(3 * scale)))
+ front_arm = (mirrored_x(center_x, center_x - round(26 * scale), facing), shoulder_y + round(30 * scale))
+ back_arm = (mirrored_x(center_x, center_x + round(26 * scale), facing), shoulder_y + round(18 * scale))
+ draw.line((shoulder, front_arm), fill="#94a3b8", width=max(1, round(2 * scale)))
+ draw.line((shoulder, back_arm), fill="#cbd5e1", width=max(1, round(2 * scale)))
+ front_knee, front_foot = leg_points(hip, str(phase["front_leg"]), facing, scale)
+ back_knee, back_foot = leg_points(hip, str(phase["back_leg"]), facing, scale)
+ draw.line((hip, front_knee, front_foot), fill="#ef4444", width=max(2, round(4 * scale)))
+ draw.line((hip, back_knee, back_foot), fill="#2563eb", width=max(2, round(4 * scale)))
+ ground_y = round(cell_height * 0.52 + 54 * scale + int(phase["body_y"]) * scale)
+ draw.line((slot_left + round(34 * scale), ground_y, slot_left + cell_width - round(34 * scale), ground_y), fill="#cbd5e1", width=1)
+
+
+def draw_guide(path: Path, state: str, frames: int, cell: dict[str, Any], motion_phase_guides: bool = False) -> None:
+ cell_width = int(cell["width"])
+ cell_height = int(cell["height"])
+ safe_margin_x = int(cell["safe_margin_x"])
+ safe_margin_y = int(cell["safe_margin_y"])
+ width = frames * cell_width
+ height = cell_height
+ image = Image.new("RGB", (width, height), "#f6f6f6")
+ draw = ImageDraw.Draw(image)
+ for index in range(frames):
+ left = index * cell_width
+ right = left + cell_width - 1
+ draw.rectangle((left, 0, right, height - 1), outline="#333333", width=3)
+ safe = (
+ left + safe_margin_x,
+ safe_margin_y,
+ right - safe_margin_x,
+ height - 1 - safe_margin_y,
+ )
+ draw.rectangle(safe, outline="#2f80ed", width=2)
+ draw.line((left + cell_width // 2, safe_margin_y, left + cell_width // 2, height - safe_margin_y), fill="#b8c8e8", width=1)
+ if motion_phase_guides:
+ phases = state_motion_phases(state, frames)
+ facing = "left" if state.endswith("left") else "right"
+ for index, phase in enumerate(phases):
+ draw_motion_phase(draw, index * cell_width, cell_width, cell_height, phase, facing)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ image.save(path)
+
+
+def row_prompt(request: dict[str, Any], state: str, entry: dict[str, Any]) -> str:
+ cell = request["cell"]
+ chroma = request["chroma_key"]
+ character = request["character"]
+ frames = int(entry["frames"])
+ cell_width = int(cell["width"])
+ cell_height = int(cell["height"])
+ safe_margin_x = int(cell["safe_margin_x"])
+ safe_margin_y = int(cell["safe_margin_y"])
+ state_requirements = [
+ *direction_prefix_requirements(request, state),
+ *directional_requirements(state),
+ *STATE_REQUIREMENTS.get(state, []),
+ ]
+ state_requirement_text = ""
+ if state_requirements:
+ state_requirement_text = "\n\nState-specific requirements:\n" + "\n".join(
+ f"- {requirement}" for requirement in state_requirements
+ )
+ phase_prompt_text = ""
+ phases = state_motion_phases(state, frames) if request.get("motion_phase_guides") else []
+ if phases:
+ phase_lines = [
+ f"- frame {index + 1}: {phase['name']} — {phase['note']}"
+ for index, phase in enumerate(phases)
+ ]
+ phase_prompt_text = (
+ "\n\nMotion phase requirements:\n"
+ "- The layout guide includes simple stick-pose motion hints inside each slot. Use those hints only for body height, foot contact, and leg phase. Do not copy guide colors or guide lines into the artwork.\n"
+ "- Make the sequence loop as one continuous locomotion cycle, not eight unrelated poses.\n"
+ "- The motion phase guide and any multi-pose contact sheet override a single running/walking pose anchor for leg phase. Do not repeat one anchor's forward leg across every frame.\n"
+ "- Opposite contact frames must visibly trade which leg reaches forward; passing frames must not look like duplicate contact frames.\n"
+ + "\n".join(phase_lines)
+ )
+ transparency_artifact_text = "\n".join(f"- {rule}" for rule in TRANSPARENCY_ARTIFACT_RULES)
+ runtime_size = f"{cell_width}x{cell_height}"
+ reference_contract = (
+ "Use the attached accepted idle/direction anchor as the canonical character design for this row. "
+ "If a state anchor is attached for a non-locomotion state, treat it as approved state vocabulary only. "
+ "Use the attached layout guide image only for frame count, slot spacing, centering, and safe padding. "
+ "If an additional generated row strip is attached, use it only as a motion reference, never as a replacement identity source. "
+ "Do not simply copy the still reference pose. Generate distinct animation poses that create a readable cycle or action."
+ )
+ if character.get("base_image"):
+ reference_contract = (
+ "If this is a pre-idle/simple run, the attached base image may be used as the canonical character design. "
+ "In direction-anchor mode, do not use base images for final action rows; accepted idle/direction anchors own row identity. "
+ + reference_contract
+ )
+ return f"""Create a single horizontal sprite strip for the game character `{character["id"]}` in the state `{state}`.
+
+{reference_contract}
+
+Character: {character.get("description") or character["id"]}.
+Style contract: {request["style"]}.
+
+Use this prompt as an authoritative sprite-production spec. Do not expand it into a polished illustration, painterly character image, anime key art, 3D render, vector mascot, glossy app icon, realistic portrait, or marketing artwork.
+
+Animation action: {entry["action"]}.
+
+Anchor lock:
+- Accepted idle/direction anchors own character identity, outfit details, colors, face design, asymmetric markings, and side-specific accessories for final action rows.
+- Base character images and original character sheets are pre-idle sources only. Do not reinterpret or reintroduce base-character details inside a direction-anchor action row.
+- This row owns motion only. Spend the variation budget on limb contacts, arm counter-swing, body height, torso lean, head bob, hair bounce, and loop continuity.
+- Do not redesign or reinterpret identity details while animating. Keep face, hair shape, markings, palette, outline weight, body proportions, outfit, props, and silhouette copied from the approved anchors.
+- Preserve side-specific features exactly as the approved anchors show them. Do not solve hairpin side, earring side, logos, handed props, scars, one-sided markings, asymmetric clothing, or lighting cues from scratch inside the row.
+- When generating a paired left/right row, use the paired row reference only for timing, scale, and animation intensity. Rotate the body, feet, shoulders, face angle, and gaze to the target facing, but keep identity details attached according to the accepted target-direction anchor.
+- For cyclic locomotion, do not let a single running/walking pose anchor determine every frame's leg phase. Use multi-pose motion references and the layout phase guide for foot contacts.
+- Prefer a subtler animation over any change that mutates the character identity.
+{state_requirement_text}
+{phase_prompt_text}
+
+Transparency and artifact rules:
+{transparency_artifact_text}
+
+Layout requirements:
+- Exactly {frames} full-body frames, left to right, in one horizontal row.
+- The attached layout guide shows the {frames} frame boxes, inner safe area, and optional motion phase hints for this row. Follow its slot count, spacing, centering, padding, and phase timing.
+- Do not reproduce the layout guide itself: no visible boxes, guide lines, center marks, labels, stick figures, guide colors, or guide background may appear in the output.
+- Treat the image as {frames} equal-width invisible {runtime_size} frame slots. Fill every slot: each requested slot must contain exactly one complete full-body pose.
+- Spread the {frames} poses evenly across the whole image width. Do not leave any requested slot blank or create large empty gaps between poses.
+- Center one complete pose in each slot. No pose may cross into the neighboring slot.
+- Use a perfectly flat pure {chroma["name"]} {chroma["hex"]} chroma-key background across the whole image.
+- Do not use {chroma["hex"]}, pure {chroma["name"]}, or chroma-adjacent colors in the character, highlights, props, shadows, or effects.
+- Keep the rendering faithful to the attached reference sprite: same outline weight, same palette, same detail level — do not restyle it.
+- Keep every frame self-contained with at least {safe_margin_x} px horizontal and {safe_margin_y} px vertical safe padding. No character body part should be clipped by the frame slot.
+- Avoid motion blur. Use clear pose changes readable at {runtime_size}.
+- Preserve the same silhouette, face, proportions, palette, material, and props across every frame.
+
+Output only the sprite strip image."""
+
+
+def _outline_config(value: str):
+ """Parse --fit-outline: on -> True, off -> False, otherwise a 0..1 strength."""
+ lowered = value.strip().lower()
+ if lowered in {"on", "true"}:
+ return True
+ if lowered in {"off", "false"}:
+ return False
+ try:
+ strength = float(lowered)
+ except ValueError:
+ raise argparse.ArgumentTypeError(f"expected on, off, or a strength float: {value!r}")
+ if not 0.0 <= strength <= 1.0:
+ raise argparse.ArgumentTypeError(f"outline strength must be within 0..1: {value!r}")
+ return strength
+
+
+def _build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--out-dir", required=True, type=Path)
+ parser.add_argument("--character-id", required=True)
+ parser.add_argument("--base-image", type=Path)
+ parser.add_argument("--description", default="")
+ parser.add_argument("--style", default=STYLE_DEFAULT)
+ parser.add_argument("--subject", choices=SUBJECTS, default=None,
+ help="what the run draws: character (default) or effect — "
+ "sets validation defaults like the sparse-frame floor")
+ parser.add_argument("--cell-size", type=int, default=256)
+ parser.add_argument("--cell-width", type=int)
+ parser.add_argument("--cell-height", type=int)
+ parser.add_argument("--safe-margin", type=int, default=None, help="absolute px override; default is 9.4%% of the cell dimension, floored")
+ parser.add_argument("--chroma-key", default="auto", help="auto or #RRGGBB")
+ parser.add_argument("--fit-resample", choices=["lanczos", "nearest", "kcentroid"], default=None, help="frame downscale filter; nearest keeps pixel-art edges crisp, kcentroid keeps 1px outlines readable")
+ parser.add_argument("--fit-align-x", choices=["bbox-center", "centroid", "foot-centroid", "alpha-centroid"], default=None, help="horizontal frame anchor; centroid stabilizes body position across variable-width poses, foot-centroid anchors on the bottom-20%% alpha (legs), alpha-centroid is the perfectpixel-studio per-frame alpha-weighted centroid (fringe-insensitive, per-frame in the pixel unfake row path)")
+ parser.add_argument("--fit-align-y", choices=["center", "bottom"], default=None, help="vertical frame anchor; bottom pins feet to a shared baseline")
+ parser.add_argument("--fit-pixel-unfake", action=argparse.BooleanOptionalAction, default=None, help="unfake the AI dots: pitch detection -> grid snap -> kCentroid -> shared palette -> integer NEAREST (see docs/pixel-unfake.md)")
+ # 은퇴한 이름 (조용한 별칭 금지 — 두 이름이 공존하면 문서·스크립트가 갈라진다)
+ parser.add_argument("--fit-pixel-perfect", "--no-fit-pixel-perfect", dest="_retired_pp",
+ action="store_true", help=argparse.SUPPRESS)
+ parser.add_argument("--fit-logical-height", type=int, default=None, help="pixel unfake logical grid height; omit for 1:1 with the cell height")
+ parser.add_argument("--fit-palette-size", type=int, default=None, help="pixel unfake run-wide shared palette size (default 48)")
+ parser.add_argument("--fit-detail-bias", action=argparse.BooleanOptionalAction, default=None, help="pixel unfake dominant-color voting bias toward near-black detail clusters (default on)")
+ parser.add_argument("--fit-outline", type=_outline_config, default=None, metavar="{on,off,STRENGTH}", help="pixel unfake outline enforcement: on (strength 0.62), off, or an explicit 0..1 strength")
+ parser.add_argument("--fit-pitch-hint", type=int, default=None, help="pixel unfake fallback pixel pitch when per-frame detection is inconclusive")
+ parser.add_argument("--motion-phase-guides", action="store_true", help="draw simple per-frame motion phase hints into locomotion layout guides")
+ parser.add_argument("--directions", help="comma list of generated directions (e.g. down,side,up); states must be named <direction>_<state>; missing <direction>_idle anchors are synthesized and a generation plan is written")
+ parser.add_argument("--mirror", help="comma list of target=source pairs covered by runtime mirroring instead of generation (e.g. left=side)")
+ parser.add_argument("--request", type=Path)
+ parser.add_argument("--request-json")
+ parser.add_argument("--force", action="store_true")
+ return parser
+
+
+def _namespace_from_kwargs(**kwargs: object) -> argparse.Namespace:
+ parser = _build_parser()
+ values: dict[str, object] = {}
+ remaining = dict(kwargs)
+ for action in parser._actions:
+ if action.dest == "help":
+ continue
+ default = [] if action.nargs == "*" else action.default
+ if default is argparse.SUPPRESS:
+ default = None
+ value = remaining.pop(action.dest, default)
+ if getattr(action, "required", False) and value is None:
+ raise TypeError(f"missing required argument: {action.dest}")
+ values[action.dest] = value
+ if remaining:
+ names = ", ".join(sorted(remaining))
+ raise TypeError(f"unexpected keyword argument(s): {names}")
+ return argparse.Namespace(**values)
+def _run(args: argparse.Namespace):
+
+ out_dir = args.out_dir.expanduser().resolve()
+ if out_dir.exists() and any(out_dir.iterdir()) and not args.force:
+ raise SystemExit(f"output dir exists and is not empty: {out_dir}; pass --force")
+
+ raw_request = load_request(args.request, args.request_json)
+ states = normalize_states(raw_request.get("states"))
+ # 방향 계약: CLI 가 request JSON 을 override 한다 (fit 과 동일 규칙)
+ raw_directions = dict(raw_request.get("directions") or {})
+ if args.directions:
+ raw_directions["set"] = [d.strip() for d in args.directions.split(",") if d.strip()]
+ if args.mirror:
+ mirror = dict(raw_directions.get("mirror") or {})
+ for pair in args.mirror.split(","):
+ if "=" not in pair:
+ raise SystemExit(f"--mirror expects target=source pairs, got: {pair!r}")
+ target, source = pair.split("=", 1)
+ mirror[target.strip()] = source.strip()
+ raw_directions["mirror"] = mirror
+ directions = normalize_directions(raw_directions or None, states)
+ if directions:
+ states = ensure_direction_anchors(directions, states)
+ raw_cell = dict(raw_request.get("cell", {}))
+ if args.cell_width is not None:
+ raw_cell["width"] = args.cell_width
+ if args.cell_height is not None:
+ raw_cell["height"] = args.cell_height
+ cell = normalize_cell(raw_cell, args.cell_size, args.safe_margin)
+
+ # 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(raw_request):
+ print(f"[prepare] {note}", file=sys.stderr)
+
+ out_dir.mkdir(parents=True, exist_ok=True)
+ base_dest = None
+ if args.base_image:
+ base_source = args.base_image.expanduser().resolve()
+ if not base_source.is_file():
+ raise SystemExit(f"missing base image: {base_source}")
+ base_dest = out_dir / f"base-source{base_source.suffix.lower() or '.png'}"
+ shutil.copy2(base_source, base_dest)
+
+ chroma_key = choose_chroma_key(base_dest, args.chroma_key)
+ request = {
+ "version": 1,
+ "kind": "sprite-gen-request",
+ "engine": "component-row",
+ "character": {
+ "id": args.character_id,
+ "description": args.description,
+ "base_image": base_dest.name if base_dest else None,
+ },
+ "cell": cell,
+ "chroma_key": chroma_key,
+ "states": states,
+ "style": raw_request.get("style", args.style),
+ "motion_phase_guides": bool(raw_request.get("motion_phase_guides", args.motion_phase_guides)),
+ }
+ # Subject profile: CLI wins over --request-json; absent = character. The
+ # field stays omitted for the default so the request has one canonical
+ # representation. Downstream validation derives its floor from this plus
+ # cell geometry via sprite_gen.spec.subject.
+ subject = args.subject or raw_request.get("subject")
+ if subject is not None:
+ if subject not in SUBJECTS:
+ raise SystemExit(f"unknown subject kind: {subject!r} (expected one of {', '.join(SUBJECTS)})")
+ request["subject"] = subject
+ if directions:
+ request["directions"] = directions
+ # 파일 택소노미 계약: 신규 런 기본. 방향 계약과 결합 시 raw/frames/guides/prompts
+ # 가 <direction>/<pose> 로 나뉜다 (layout.py SSoT). legacy 런은 필드 없음 = flat.
+ request["layout"] = TAXONOMY
+ fit = dict(raw_request.get("fit", {}))
+ fit_overrides = {
+ "resample": args.fit_resample,
+ "align_x": args.fit_align_x,
+ "align_y": args.fit_align_y,
+ "pixel_unfake": args.fit_pixel_unfake,
+ "logical_height": args.fit_logical_height,
+ "palette_size": args.fit_palette_size,
+ "detail_bias": args.fit_detail_bias,
+ "outline": args.fit_outline,
+ "pitch_hint": args.fit_pitch_hint,
+ }
+ for key, value in fit_overrides.items():
+ if value is not None:
+ fit[key] = value
+ 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"):
+ directory.mkdir(parents=True, exist_ok=True)
+
+ for state, entry in states.items():
+ guide_path = out_dir / guide_rel(request, state)
+ prompt_path = out_dir / prompt_rel(request, state)
+ for parent in (guide_path.parent, prompt_path.parent, (out_dir / raw_rel(request, state)).parent):
+ parent.mkdir(parents=True, exist_ok=True)
+ draw_guide(
+ guide_path,
+ state,
+ int(entry["frames"]),
+ cell,
+ motion_phase_guides=bool(request["motion_phase_guides"]),
+ )
+ prompt_path.write_text(row_prompt(request, state, entry).rstrip() + "\n", encoding="utf-8")
+
+ # 방향 계약 런: 생성 체인 SSoT(1단계 앵커 -> 2단계 행, 미러 방향 명시)를 기록
+ plan = build_generation_plan(request)
+ if plan:
+ (out_dir / "references" / "generation-plan.json").write_text(
+ json.dumps(plan, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
+
+ (out_dir / "sprite-request.json").write_text(
+ json.dumps(request, ensure_ascii=False, indent=2) + "\n",
+ encoding="utf-8",
+ )
+
+ print(json.dumps({"ok": True, "run_dir": str(out_dir), "states": list(states),
+ "generation_plan": bool(plan)}, ensure_ascii=False, indent=2))
+ return 0
+
+
+
+def run(**kwargs: object):
+ return _run(_namespace_from_kwargs(**kwargs))
+
+RETIRED_PP_MESSAGE = (
+ "--fit-pixel-perfect is retired: the accurate name for this pipeline is **pixel unfake** "
+ "(grid snapping / re-quantization — community name from unfake.js), while 'pixel perfect' is "
+ "a broad UI-alignment term. Use --fit-pixel-unfake / --no-fit-pixel-unfake.")
+
+
+def main() -> int:
+ parser = _build_parser()
+ args = parser.parse_args()
+ if getattr(args, "_retired_pp", False):
+ raise SystemExit(RETIRED_PP_MESSAGE)
+ return _run(args)
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/sprite_gen/qa/__init__.py b/sprite_gen/qa/__init__.py
new file mode 100644
index 0000000..9881313
--- /dev/null
+++ b/sprite_gen/qa/__init__.py
@@ -0,0 +1 @@
+# SPDX-License-Identifier: Apache-2.0
diff --git a/sprite_gen/qa/correction_loop.py b/sprite_gen/qa/correction_loop.py
new file mode 100644
index 0000000..4dff371
--- /dev/null
+++ b/sprite_gen/qa/correction_loop.py
@@ -0,0 +1,187 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Run a bounded inspect -> score -> correction-hint loop."""
+
+from __future__ import annotations
+
+import argparse
+import json
+import shlex
+import shutil
+import subprocess
+from pathlib import Path
+from typing import Any
+
+from sprite_gen.qa import inspect as inspect_mod
+from sprite_gen.qa import score as score_mod
+from sprite_gen.spec.runio import atomic_write_text
+
+
+def _build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--run-dir", required=True, type=Path)
+ parser.add_argument("--states", default="all")
+ parser.add_argument("--out-dir", type=Path)
+ parser.add_argument("--max-passes", type=int, default=3)
+ parser.add_argument("--min-attempts", type=int, default=1)
+ parser.add_argument("--pass-score", type=float, default=90.0)
+ parser.add_argument("--provider-command", help="optional command template; {prompt_file}, {next_run_dir}, {attempt}")
+ parser.add_argument("--dry-run", action="store_true")
+ parser.add_argument("--no-preserve-best", action="store_true")
+ return parser
+
+
+def _namespace_from_kwargs(**kwargs: object) -> argparse.Namespace:
+ parser = _build_parser()
+ values: dict[str, object] = {}
+ remaining = dict(kwargs)
+ for action in parser._actions:
+ if action.dest == "help":
+ continue
+ default = [] if action.nargs == "*" else action.default
+ if default is argparse.SUPPRESS:
+ default = None
+ value = remaining.pop(action.dest, default)
+ if getattr(action, "required", False) and value is None:
+ raise TypeError(f"missing required argument: {action.dest}")
+ values[action.dest] = value
+ if remaining:
+ names = ", ".join(sorted(remaining))
+ raise TypeError(f"unexpected keyword argument(s): {names}")
+ return argparse.Namespace(**values)
+
+
+def _copy_run_dir(source: Path, target: Path) -> None:
+ if target.exists():
+ shutil.rmtree(target)
+
+ def ignore(_dir: str, names: list[str]) -> set[str]:
+ return {name for name in names if name == ".sprite-gen.lock" or name == "__pycache__"}
+
+ shutil.copytree(source, target, ignore=ignore)
+
+
+def _write_hints(path: Path, hints: list[str]) -> None:
+ body = "\n".join(f"- {hint}" for hint in hints) if hints else "- No correction hint; candidate passed."
+ atomic_write_text(path, body + "\n")
+
+
+def run_loop(
+ run_dir: Path,
+ *,
+ states: str = "all",
+ out_dir: Path | None = None,
+ max_passes: int = 3,
+ min_attempts: int = 1,
+ pass_score: float = 90.0,
+ provider_command: str | None = None,
+ dry_run: bool = False,
+ preserve_best: bool = True,
+) -> dict[str, Any]:
+ if max_passes < 1:
+ raise SystemExit("--max-passes must be at least 1")
+ if min_attempts < 1 or min_attempts > max_passes:
+ raise SystemExit("--min-attempts must be between 1 and --max-passes")
+ run_dir = run_dir.expanduser().resolve()
+ out_dir = (out_dir or (run_dir / "correction-loop")).expanduser().resolve()
+ out_dir.mkdir(parents=True, exist_ok=True)
+ attempts: list[dict[str, Any]] = []
+ best: dict[str, Any] | None = None
+ current = run_dir
+
+ for attempt in range(1, max_passes + 1):
+ attempt_dir = out_dir / f"attempt-{attempt}"
+ attempt_dir.mkdir(parents=True, exist_ok=True)
+ inspect_report = inspect_mod.inspect_run(current, states=states)
+ scored = score_mod.score_inspection(inspect_report)
+ atomic_write_text(attempt_dir / "inspect.json", json.dumps(inspect_report, ensure_ascii=False, indent=2) + "\n")
+ atomic_write_text(attempt_dir / "score.json", json.dumps(scored, ensure_ascii=False, indent=2) + "\n")
+ _write_hints(attempt_dir / "correction-hints.txt", scored["hints"])
+ record = {
+ "attempt": attempt,
+ "run_dir": str(current),
+ "inspect_report": str(attempt_dir / "inspect.json"),
+ "score_report": str(attempt_dir / "score.json"),
+ "hint_file": str(attempt_dir / "correction-hints.txt"),
+ "ok": scored["ok"],
+ "overall_score": scored["overall_score"],
+ "candidate_rank": scored["candidate_rank"],
+ }
+ attempts.append(record)
+ if best is None or (scored["candidate_rank"], scored["overall_score"]) > (
+ best["candidate_rank"],
+ best["overall_score"],
+ ):
+ best = record
+ if attempt >= min_attempts and scored["ok"] and float(scored["overall_score"]) >= pass_score:
+ break
+ if attempt == max_passes:
+ break
+ if dry_run:
+ break
+ if not provider_command:
+ raise SystemExit("correction loop needs --provider-command, or use --dry-run for an inspect/score/hint demo")
+ next_run_dir = out_dir / f"candidate-{attempt + 1}"
+ prompt_file = attempt_dir / "correction-hints.txt"
+ command = provider_command.format(
+ prompt_file=str(prompt_file),
+ next_run_dir=str(next_run_dir),
+ attempt=attempt + 1,
+ )
+ completed = subprocess.run(shlex.split(command), capture_output=True, text=True)
+ atomic_write_text(
+ attempt_dir / "provider.log",
+ completed.stdout + ("\n--- stderr ---\n" + completed.stderr if completed.stderr else ""),
+ )
+ if completed.returncode != 0:
+ raise SystemExit(f"provider command failed with exit {completed.returncode}: {command}")
+ if not (next_run_dir / "sprite-request.json").is_file():
+ raise SystemExit(f"provider command did not create a sprite-gen run dir: {next_run_dir}")
+ current = next_run_dir
+
+ assert best is not None
+ preserved_best = None
+ if preserve_best:
+ preserved = out_dir / "best-candidate"
+ _copy_run_dir(Path(best["run_dir"]), preserved)
+ preserved_best = str(preserved)
+ result = {
+ "ok": bool(attempts and attempts[-1]["ok"] and float(attempts[-1]["overall_score"]) >= pass_score),
+ "kind": "sprite-gen-correction-loop-report",
+ "dry_run": dry_run,
+ "min_attempts": min_attempts,
+ "max_passes": max_passes,
+ "attempts": attempts,
+ "best_candidate": best,
+ "preserved_best": preserved_best,
+ }
+ atomic_write_text(out_dir / "correction-loop.report.json", json.dumps(result, ensure_ascii=False, indent=2) + "\n")
+ return result
+
+
+def _run(args: argparse.Namespace) -> int:
+ result = run_loop(
+ args.run_dir,
+ states=args.states,
+ out_dir=args.out_dir,
+ max_passes=args.max_passes,
+ min_attempts=args.min_attempts,
+ pass_score=args.pass_score,
+ provider_command=args.provider_command,
+ dry_run=args.dry_run,
+ preserve_best=not args.no_preserve_best,
+ )
+ print(json.dumps({k: v for k, v in result.items() if k != "attempts"}, ensure_ascii=False, indent=2))
+ return 0 if result["ok"] else 1
+
+
+def run(**kwargs: object) -> int:
+ args = _namespace_from_kwargs(**kwargs)
+ return _run(args)
+
+
+def main() -> int:
+ return _run(_build_parser().parse_args())
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/sprite_gen/qa/inspect.py b/sprite_gen/qa/inspect.py
new file mode 100644
index 0000000..54af949
--- /dev/null
+++ b/sprite_gen/qa/inspect.py
@@ -0,0 +1,436 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Inspect generated sprite rows for closed-loop correction signals."""
+
+from __future__ import annotations
+
+import argparse
+import json
+import math
+from pathlib import Path
+from statistics import mean, pstdev
+from typing import Any
+
+from PIL import Image, ImageChops
+
+from sprite_gen.frames import extract
+from sprite_gen.spec.layout import frames_dir_rel, raw_rel, state_frame_total
+from sprite_gen.spec.runio import (acquire_run_dir_lock, atomic_write_text, load_request,
+ read_guard, relative_posix)
+from sprite_gen.frames.segment import segment_strip
+
+
+HISTOGRAM_BINS = 64
+D_HASH_BITS = 64
+DEFAULT_HISTOGRAM_MIN = 0.0
+DEFAULT_DHASH_MIN = 0.55
+DEFAULT_MOTION_MIN = 0.01
+
+
+def _build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--run-dir", required=True, type=Path)
+ parser.add_argument("--states", default="all")
+ parser.add_argument("--report", default="sprite-inspect.report.json")
+ parser.add_argument("--histogram-min", type=float, default=DEFAULT_HISTOGRAM_MIN)
+ parser.add_argument("--dhash-min", type=float, default=DEFAULT_DHASH_MIN)
+ parser.add_argument("--motion-min", type=float, default=DEFAULT_MOTION_MIN)
+ parser.add_argument("--key-threshold", type=float, default=96.0)
+ parser.add_argument("--fringe-key-threshold", type=float, default=180.0)
+ parser.add_argument("--fringe-delta", type=float, default=18.0)
+ parser.add_argument("--fringe-unmix-reach", type=int, default=None)
+ parser.add_argument("--spill-max-fraction", type=float, default=None)
+ parser.add_argument("--chroma-mode", choices=("rgb", "ycbcr"), default=None)
+ parser.add_argument("--no-write", action="store_true")
+ return parser
+
+
+def _namespace_from_kwargs(**kwargs: object) -> argparse.Namespace:
+ parser = _build_parser()
+ values: dict[str, object] = {}
+ remaining = dict(kwargs)
+ for action in parser._actions:
+ if action.dest == "help":
+ continue
+ default = [] if action.nargs == "*" else action.default
+ if default is argparse.SUPPRESS:
+ default = None
+ value = remaining.pop(action.dest, default)
+ if getattr(action, "required", False) and value is None:
+ raise TypeError(f"missing required argument: {action.dest}")
+ values[action.dest] = value
+ if remaining:
+ names = ", ".join(sorted(remaining))
+ raise TypeError(f"unexpected keyword argument(s): {names}")
+ return argparse.Namespace(**values)
+
+
+def _state_list(request: dict[str, Any], states: str) -> list[str]:
+ if states == "all":
+ return list(request["states"])
+ selected = [state.strip() for state in states.split(",") if state.strip()]
+ unknown = [state for state in selected if state not in request["states"]]
+ if unknown:
+ raise SystemExit(f"unknown state(s) in request: {', '.join(unknown)}")
+ return selected
+
+
+def _rgba(path: Path) -> Image.Image:
+ with Image.open(path) as opened:
+ return opened.convert("RGBA")
+
+
+def _frame_sort_key(path: Path) -> int:
+ stem = path.stem
+ if stem.endswith(".plain"):
+ stem = stem.removesuffix(".plain")
+ try:
+ return int(stem.split("-")[1])
+ except (IndexError, ValueError):
+ return 10**9
+
+
+def _load_extracted_frames(run_dir: Path, state: str, request: dict[str, Any]) -> tuple[list[Image.Image], list[str]]:
+ state_dir = run_dir / frames_dir_rel(request, state)
+ if not state_dir.is_dir():
+ return [], []
+ paths = sorted(
+ (path for path in state_dir.glob("frame-*.png") if not path.name.endswith(".plain.png")),
+ key=_frame_sort_key,
+ )
+ return [_rgba(path) for path in paths], [relative_posix(path, run_dir) for path in paths]
+
+
+def _strip_for_state(run_dir: Path, request: dict[str, Any], state: str, args: argparse.Namespace) -> Image.Image | None:
+ raw_path = run_dir / raw_rel(request, state)
+ if not raw_path.is_file():
+ return None
+ chroma_config = dict(request.get("chroma") or {})
+ chroma_mode = args.chroma_mode if args.chroma_mode is not None else str(chroma_config.get("mode", "rgb"))
+ chroma_key = tuple(int(value) for value in request["chroma_key"]["rgb"])
+ unmix_reach = (
+ args.fringe_unmix_reach
+ if args.fringe_unmix_reach is not None
+ else int(chroma_config.get("unmix_reach", 4))
+ )
+ spill_max_fraction = (
+ args.spill_max_fraction
+ if args.spill_max_fraction is not None
+ else float(chroma_config.get("spill_max_fraction", 0.005))
+ )
+ with Image.open(raw_path) as opened:
+ if chroma_mode == "ycbcr":
+ notes: list[str] = []
+ return extract.remove_chroma_background_ycbcr(opened, chroma_key, notes)
+ return extract.remove_chroma_background(
+ opened,
+ chroma_key,
+ args.key_threshold,
+ args.fringe_key_threshold,
+ args.fringe_delta,
+ unmix_reach=unmix_reach,
+ spill_max_fraction=spill_max_fraction,
+ )
+
+
+def _frames_from_raw(strip: Image.Image, expected: int, request: dict[str, Any]) -> tuple[list[Image.Image], int]:
+ cell_width, cell_height, safe_margin_x, safe_margin_y = extract.cell_geometry(request["cell"])
+ segments, natural = segment_strip(strip, expected)
+ frames: list[Image.Image] = []
+ for left, right in segments:
+ frames.append(
+ extract.fit_to_cell(
+ strip.crop((left, 0, right, strip.height)),
+ cell_width,
+ cell_height,
+ safe_margin_x,
+ safe_margin_y,
+ request.get("fit") or {},
+ )
+ )
+ return frames, natural
+
+
+def _rgb_histogram(image: Image.Image) -> list[float]:
+ bins = [0] * HISTOGRAM_BINS
+ total = 0
+ for red, green, blue, alpha in image.convert("RGBA").getdata():
+ if alpha <= 16:
+ continue
+ index = (red // 64) * 16 + (green // 64) * 4 + (blue // 64)
+ bins[index] += 1
+ total += 1
+ if total == 0:
+ return [0.0] * HISTOGRAM_BINS
+ return [value / total for value in bins]
+
+
+def histogram_intersection(left: list[float], right: list[float]) -> float:
+ return sum(min(a, b) for a, b in zip(left, right))
+
+
+def _dhash(image: Image.Image) -> int:
+ flattened = Image.new("RGBA", image.size, (255, 255, 255, 255))
+ flattened.alpha_composite(image.convert("RGBA"))
+ small = flattened.convert("L").resize((9, 8), Image.Resampling.BILINEAR)
+ pixels = list(small.getdata())
+ value = 0
+ bit = 0
+ for y in range(8):
+ row = y * 9
+ for x in range(8):
+ if pixels[row + x] > pixels[row + x + 1]:
+ value |= 1 << bit
+ bit += 1
+ return value
+
+
+def dhash_similarity(left: int, right: int) -> float:
+ return 1.0 - ((left ^ right).bit_count() / D_HASH_BITS)
+
+
+def _alpha_centroid(image: Image.Image) -> tuple[float, float] | None:
+ alpha = image.getchannel("A")
+ total = 0
+ weighted_x = 0
+ weighted_y = 0
+ for y in range(image.height):
+ for x in range(image.width):
+ value = alpha.getpixel((x, y))
+ if value <= 10:
+ continue
+ total += value
+ weighted_x += x * value
+ weighted_y += y * value
+ if total == 0:
+ return None
+ return weighted_x / total, weighted_y / total
+
+
+def _motion_presence(frames: list[Image.Image]) -> float:
+ if len(frames) < 2:
+ return 0.0
+ values: list[float] = []
+ for left, right in zip(frames, frames[1:]):
+ a = left.convert("RGBA").resize((64, 64), Image.Resampling.BILINEAR)
+ b = right.convert("RGBA").resize((64, 64), Image.Resampling.BILINEAR)
+ diff = ImageChops.difference(a, b)
+ total = 0
+ for pixel in diff.getdata():
+ total += pixel[0] + pixel[1] + pixel[2] + pixel[3]
+ values.append(total / (64 * 64 * 4 * 255))
+ return mean(values) if values else 0.0
+
+
+def _similarity_summary(frames: list[Image.Image]) -> dict[str, Any]:
+ histograms = [_rgb_histogram(frame) for frame in frames]
+ hashes = [_dhash(frame) for frame in frames]
+ hist_pairs = [
+ histogram_intersection(histograms[i], histograms[j])
+ for i in range(len(histograms))
+ for j in range(i + 1, len(histograms))
+ ]
+ dhash_pairs = [
+ dhash_similarity(hashes[i], hashes[j])
+ for i in range(len(hashes))
+ for j in range(i + 1, len(hashes))
+ ]
+ centroids = [_alpha_centroid(frame) for frame in frames]
+ xs = [point[0] for point in centroids if point is not None]
+ ys = [point[1] for point in centroids if point is not None]
+ return {
+ "histogram_intersection": {
+ "min": min(hist_pairs) if hist_pairs else 1.0,
+ "mean": mean(hist_pairs) if hist_pairs else 1.0,
+ },
+ "dhash_similarity": {
+ "min": min(dhash_pairs) if dhash_pairs else 1.0,
+ "mean": mean(dhash_pairs) if dhash_pairs else 1.0,
+ },
+ "motion_presence": _motion_presence(frames),
+ "centroid_sigma": {
+ "x": pstdev(xs) if len(xs) > 1 else 0.0,
+ "y": pstdev(ys) if len(ys) > 1 else 0.0,
+ },
+ }
+
+
+def _manifest_state_notes(run_dir: Path, state: str) -> tuple[dict[str, Any] | None, list[str], list[str]]:
+ """Per-state manifest row + failure notes for `state`, gathered from two sources:
+
+ - `frames/frames-manifest.json` — the current COMPLETE generation (only ever published
+ on a successful extract, so it carries the row for a good state, no failure errors).
+ - `extract-failure.json` — the last failed extract's per-state diagnostics, written
+ OUTSIDE canonical frames/ because a failed extract publishes no partial generation
+ (whole-generation atomicity). This is the signal the automatic correction loop needs to
+ know *which state failed and why* and drive error-driven regeneration; a successful
+ extract removes it, so it never re-flags a now-good state.
+
+ The row comes only from the published manifest (real frames); errors/warnings merge both."""
+ manifest_row: dict[str, Any] | None = None
+ state_errors: list[str] = []
+ state_warnings: list[str] = []
+
+ def _collect(manifest: dict, take_row: bool) -> None:
+ nonlocal manifest_row
+ if not manifest:
+ return
+ prefix = f"{state}:"
+ for message in manifest.get("errors", []):
+ text = str(message)
+ if text.startswith(prefix) and text not in state_errors:
+ state_errors.append(text)
+ for message in manifest.get("warnings", []):
+ text = str(message)
+ if text.startswith(prefix) and text not in state_warnings:
+ state_warnings.append(text)
+ if take_row and manifest_row is None:
+ for row in manifest.get("rows", []):
+ if row.get("state") == state:
+ manifest_row = row
+ break
+
+ # fail-loud on a corrupt/broken canonical record (No Silent Fallback), {} only if absent
+ _collect(extract.load_frames_manifest(run_dir / "frames" / "frames-manifest.json"), take_row=True)
+ _collect(extract.load_failure_evidence(run_dir / "extract-failure.json"), take_row=False)
+ return manifest_row, state_errors, state_warnings
+
+
+def inspect_run(run_dir: Path, states: str = "all", **kwargs: object) -> dict[str, Any]:
+ """Inspect the run holding a shared read_guard, so the combined read of frames/,
+ frames-manifest.json, and extract-failure.json sees ONE consistent snapshot — never a
+ mid-publish mix of a newly-swapped frames generation with a stale failure record. The
+ correction loop reads through here, so its diagnostics stay isolated from a concurrent
+ extract commit (which advances both surfaces under the matching publish_guard)."""
+ with read_guard(Path(run_dir).expanduser().resolve()):
+ return _inspect_run_impl(run_dir, states=states, **kwargs)
+
+
+def _inspect_run_impl(run_dir: Path, states: str = "all", **kwargs: object) -> dict[str, Any]:
+ args = _namespace_from_kwargs(run_dir=run_dir, states=states, no_write=True, **kwargs)
+ run_dir = args.run_dir.expanduser().resolve()
+ # Fail loud on a corrupt/inconsistent generation or orphan frames (frames with no manifest) —
+ # otherwise the correction loop would read stale frames as ok:true (No Silent Fallback). A run
+ # with no generation at all ({}) is fine: inspect falls back to raw-projection below.
+ extract.load_consistent_frames_manifest(run_dir)
+ request = load_request(run_dir)
+ selected = _state_list(request, args.states)
+ rows: list[dict[str, Any]] = []
+ errors: list[str] = []
+ warnings: list[str] = []
+
+ for state in selected:
+ expected = state_frame_total(request, state)
+ frames, files = _load_extracted_frames(run_dir, state, request)
+ source = "frames"
+ natural_found: int | None = None
+ if not frames:
+ strip = _strip_for_state(run_dir, request, state, args)
+ if strip is None:
+ row = {
+ "state": state,
+ "source": "missing",
+ "expected_frames": expected,
+ "found_frames": 0,
+ "natural_pose_count": 0,
+ "ok": False,
+ "errors": [f"{state}: missing extracted frames and raw strip"],
+ "warnings": [],
+ }
+ rows.append(row)
+ errors.extend(row["errors"])
+ continue
+ frames, natural_found = _frames_from_raw(strip, expected, request)
+ source = "raw-projection"
+
+ found = len(frames) if source == "frames" else int(natural_found or len(frames))
+ row_errors: list[str] = []
+ row_warnings: list[str] = []
+ if found != expected:
+ row_errors.append(f"{state}: expected {expected} frame(s), inspect found {found}")
+ manifest_row, manifest_errors, manifest_warnings = _manifest_state_notes(run_dir, state)
+ row_errors.extend(manifest_errors)
+ row_warnings.extend(manifest_warnings)
+ if manifest_row is not None:
+ row_errors.extend(str(error) for error in manifest_row.get("errors", []))
+ row_warnings.extend(str(warning) for warning in manifest_row.get("warnings", []))
+ metrics = _similarity_summary(frames)
+ if args.histogram_min > 0 and metrics["histogram_intersection"]["min"] < args.histogram_min:
+ row_warnings.append(
+ f"{state}: RGB histogram identity similarity is low "
+ f"({metrics['histogram_intersection']['min']:.3f} < {args.histogram_min:.3f})"
+ )
+ if metrics["dhash_similarity"]["min"] < args.dhash_min:
+ row_warnings.append(
+ f"{state}: dHash silhouette similarity is low "
+ f"({metrics['dhash_similarity']['min']:.3f} < {args.dhash_min:.3f})"
+ )
+ if metrics["motion_presence"] < args.motion_min:
+ row_warnings.append(
+ f"{state}: motion presence is too low "
+ f"({metrics['motion_presence']:.4f} < {args.motion_min:.4f})"
+ )
+ row = {
+ "state": state,
+ "source": source,
+ "expected_frames": expected,
+ "found_frames": found,
+ "natural_pose_count": natural_found if natural_found is not None else found,
+ "frame_files": files,
+ "metrics": metrics,
+ "ok": not row_errors,
+ "errors": row_errors,
+ "warnings": row_warnings,
+ }
+ rows.append(row)
+ errors.extend(row_errors)
+ warnings.extend(row_warnings)
+
+ return {
+ "ok": not errors,
+ "engine": "component-row",
+ "kind": "sprite-gen-inspect-report",
+ "run_dir": str(run_dir),
+ "states": selected,
+ "thresholds": {
+ "histogram_min": args.histogram_min,
+ "dhash_min": args.dhash_min,
+ "motion_min": args.motion_min,
+ },
+ "rows": rows,
+ "errors": errors,
+ "warnings": warnings,
+ }
+
+
+def _run(args: argparse.Namespace) -> int:
+ run_dir = args.run_dir.expanduser().resolve()
+ report = inspect_run(
+ run_dir,
+ states=args.states,
+ histogram_min=args.histogram_min,
+ dhash_min=args.dhash_min,
+ motion_min=args.motion_min,
+ key_threshold=args.key_threshold,
+ fringe_key_threshold=args.fringe_key_threshold,
+ fringe_delta=args.fringe_delta,
+ fringe_unmix_reach=args.fringe_unmix_reach,
+ spill_max_fraction=args.spill_max_fraction,
+ chroma_mode=args.chroma_mode,
+ )
+ if not args.no_write:
+ acquire_run_dir_lock(run_dir, "inspect_sprite_run")
+ atomic_write_text(run_dir / args.report, json.dumps(report, ensure_ascii=False, indent=2) + "\n")
+ print(json.dumps({k: v for k, v in report.items() if k != "rows"}, ensure_ascii=False, indent=2))
+ return 0 if report["ok"] else 1
+
+
+def run(**kwargs: object) -> int:
+ return _run(_namespace_from_kwargs(**kwargs))
+
+
+def main() -> int:
+ return _run(_build_parser().parse_args())
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/sprite_gen/qa/preview.py b/sprite_gen/qa/preview.py
new file mode 100644
index 0000000..be1062b
--- /dev/null
+++ b/sprite_gen/qa/preview.py
@@ -0,0 +1,179 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Build motion-QA previews for a sprite-gen run.
+
+For each state in frames/frames-manifest.json this writes:
+ qa/<state>-contact.png - frames left-to-right on a checker so motion is readable
+ qa/<state>.gif - frames played at the state fps (loops)
+ qa/all-contact.png - every state stacked, one row per state
+
+These are QA instruments, not runtime assets. The runtime SSoT stays
+manifest.json.frame_layout over sprite-sheet-alpha.png.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+from pathlib import Path
+
+from PIL import Image
+
+from sprite_gen.frames.extract import require_frames_manifest
+from sprite_gen.spec.runio import REQUEST_FILENAME, load_request, read_guard
+from sprite_gen.util.gif_utils import delay_ticks_to_duration_ms, save_clean_gif
+
+
+def checker(size: tuple[int, int], square: int = 16) -> Image.Image:
+ """Neutral checker so transparent pixels and stray fringe are both visible."""
+ w, h = size
+ bg = Image.new("RGBA", size, (210, 210, 210, 255))
+ px = bg.load()
+ for y in range(h):
+ for x in range(w):
+ if ((x // square) + (y // square)) % 2 == 0:
+ px[x, y] = (235, 235, 235, 255)
+ return bg
+
+
+def flatten(frame: Image.Image) -> Image.Image:
+ base = checker(frame.size)
+ base.alpha_composite(frame)
+ return base.convert("RGB")
+
+
+def load_frames(run_dir: Path, files: list[str]) -> list[Image.Image]:
+ return [Image.open(run_dir / rel).convert("RGBA") for rel in files]
+
+
+def contact_sheet(frames: list[Image.Image], gap: int = 4) -> Image.Image:
+ cw = max(f.width for f in frames)
+ ch = max(f.height for f in frames)
+ n = len(frames)
+ sheet = Image.new("RGB", (n * cw + (n + 1) * gap, ch + 2 * gap), (255, 255, 255))
+ x = gap
+ for f in frames:
+ sheet.paste(flatten(f), (x, gap))
+ x += cw + gap
+ return sheet
+
+
+def _build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--run-dir", required=True, type=Path)
+ parser.add_argument(
+ "--delay-ticks",
+ type=int,
+ help="override every GIF preview delay in 1/100 second ticks",
+ )
+ return parser
+
+
+def _namespace_from_kwargs(**kwargs: object) -> argparse.Namespace:
+ parser = _build_parser()
+ values: dict[str, object] = {}
+ remaining = dict(kwargs)
+ for action in parser._actions:
+ if action.dest == "help":
+ continue
+ default = [] if action.nargs == "*" else action.default
+ if default is argparse.SUPPRESS:
+ default = None
+ value = remaining.pop(action.dest, default)
+ if getattr(action, "required", False) and value is None:
+ raise TypeError(f"missing required argument: {action.dest}")
+ values[action.dest] = value
+ if remaining:
+ names = ", ".join(sorted(remaining))
+ raise TypeError(f"unexpected keyword argument(s): {names}")
+ return argparse.Namespace(**values)
+def _run(args: argparse.Namespace):
+
+ run_dir = args.run_dir.expanduser().resolve()
+ # Read the manifest + request + frame tree under one shared read_guard, so a concurrent publish
+ # swap never lets preview observe a mid-swap state (a missing/partial generation). Reader
+ # isolation, same contract as serve/inspect (runio.read_guard ↔ publish_guard).
+ with read_guard(run_dir):
+ return _run_guarded(args, run_dir)
+
+
+def _run_guarded(args, run_dir):
+ manifest = require_frames_manifest(run_dir) # fail loud if absent/corrupt
+ # 읽기는 게이트 경유 (`load_request`) — raw 로 읽으면 은퇴 키 런에서 이관이 비껴간다.
+ # 이 소비자는 request 없는 런도 허용하므로 부재만 관용한다 (게이트는 부재에 fail-loud).
+ request_path = run_dir / REQUEST_FILENAME
+ request = load_request(run_dir) if request_path.is_file() else {}
+ state_meta = request.get("states", {})
+
+ qa_dir = run_dir / "qa"
+ qa_dir.mkdir(parents=True, exist_ok=True)
+
+ summary = []
+ state_sheets: list[tuple[str, Image.Image]] = []
+ for row in manifest.get("rows", []):
+ state = row["state"]
+ files = row.get("files", [])
+ if not files:
+ summary.append({"state": state, "ok": False, "note": "no frame files"})
+ continue
+ frames = load_frames(run_dir, files)
+ fps = int(state_meta.get(state, {}).get("fps", 6)) or 6
+ loop = bool(state_meta.get(state, {}).get("loop", True))
+
+ sheet = contact_sheet(frames)
+ sheet.save(qa_dir / f"{state}-contact.png")
+ state_sheets.append((state, sheet))
+
+ duration = (
+ delay_ticks_to_duration_ms(args.delay_ticks)
+ if args.delay_ticks
+ else max(1, round(1000 / fps))
+ )
+ save_clean_gif(
+ frames,
+ qa_dir / f"{state}.gif",
+ duration_ms=duration,
+ loop=0 if loop else 1,
+ )
+ summary.append(
+ {
+ "state": state,
+ "ok": True,
+ "frames": len(frames),
+ "fps": fps,
+ "delay_ticks": round(duration / 10),
+ "loop": loop,
+ }
+ )
+
+ # stacked all-state contact sheet
+ if state_sheets:
+ gap = 8
+ width = max(s.width for _, s in state_sheets) + 2 * gap
+ height = sum(s.height for _, s in state_sheets) + gap * (len(state_sheets) + 1)
+ stacked = Image.new("RGB", (width, height), (255, 255, 255))
+ y = gap
+ for _state, s in state_sheets:
+ stacked.paste(s, (gap, y))
+ y += s.height + gap
+ stacked.save(qa_dir / "all-contact.png")
+
+ # Any per-state failure makes the whole preview fail loud — never a top-level ok:true over a
+ # broken state (No Silent Fallback). The complete-generation gate above already rejects a
+ # missing/empty generation; this guards the residual per-state paths.
+ all_ok = bool(summary) and all(s.get("ok") for s in summary)
+ print(json.dumps({"ok": all_ok, "qa_dir": str(qa_dir), "states": summary}, ensure_ascii=False, indent=2))
+ return 0 if all_ok else 1
+
+
+
+def run(**kwargs: object):
+ return _run(_namespace_from_kwargs(**kwargs))
+
+def main() -> int:
+ parser = _build_parser()
+ args = parser.parse_args()
+ return _run(args)
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/sprite_gen/qa/score.py b/sprite_gen/qa/score.py
new file mode 100644
index 0000000..b4e4795
--- /dev/null
+++ b/sprite_gen/qa/score.py
@@ -0,0 +1,172 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Score sprite inspection reports and produce correction hints."""
+
+from __future__ import annotations
+
+import argparse
+import json
+from pathlib import Path
+from statistics import mean
+from typing import Any
+
+from sprite_gen.spec.runio import atomic_write_text
+
+
+def _unique(items: list[str]) -> list[str]:
+ seen: set[str] = set()
+ result: list[str] = []
+ for item in items:
+ if item in seen:
+ continue
+ seen.add(item)
+ result.append(item)
+ return result
+
+
+def _build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--inspect-report", required=True, type=Path)
+ parser.add_argument("--output", default="sprite-score.report.json")
+ parser.add_argument("--no-write", action="store_true")
+ return parser
+
+
+def _namespace_from_kwargs(**kwargs: object) -> argparse.Namespace:
+ parser = _build_parser()
+ values: dict[str, object] = {}
+ remaining = dict(kwargs)
+ for action in parser._actions:
+ if action.dest == "help":
+ continue
+ default = [] if action.nargs == "*" else action.default
+ if default is argparse.SUPPRESS:
+ default = None
+ value = remaining.pop(action.dest, default)
+ if getattr(action, "required", False) and value is None:
+ raise TypeError(f"missing required argument: {action.dest}")
+ values[action.dest] = value
+ if remaining:
+ names = ", ".join(sorted(remaining))
+ raise TypeError(f"unexpected keyword argument(s): {names}")
+ return argparse.Namespace(**values)
+
+
+def _hint_for_row(row: dict[str, Any], *, histogram_min: float, dhash_min: float) -> list[str]:
+ state = row["state"]
+ expected = int(row.get("expected_frames", 0))
+ found = int(row.get("found_frames", 0))
+ metrics = row.get("metrics") or {}
+ hints: list[str] = []
+ if found != expected:
+ hints.append(
+ f"{state}: The previous strip was read as {found} pose(s), but the request requires exactly "
+ f"{expected}. Regenerate as exactly {expected} full-body poses in {expected} equal invisible "
+ "horizontal slots. Keep clear gutters between poses; no limbs, props, shadows, or effects may cross a slot boundary."
+ )
+ hist_min = float((metrics.get("histogram_intersection") or {}).get("min", 1.0))
+ if histogram_min > 0 and hist_min < histogram_min:
+ hints.append(
+ f"{state}: Frame-to-frame color identity drift was detected (RGB histogram similarity {hist_min:.3f}). "
+ "Copy the accepted anchor palette, outfit colors, hair color, face markings, and outline weight in every pose."
+ )
+ row_dhash_min = float((metrics.get("dhash_similarity") or {}).get("min", 1.0))
+ if row_dhash_min < dhash_min:
+ hints.append(
+ f"{state}: Silhouette drift was detected (dHash similarity {row_dhash_min:.3f}). "
+ "Keep the same body proportions and camera angle; only change the limb motion needed for this action."
+ )
+ motion = float(metrics.get("motion_presence", 1.0))
+ if motion < 0.01 and expected > 1:
+ hints.append(
+ f"{state}: Adjacent frames are too similar (motion presence {motion:.4f}). "
+ "Make the action visibly progress across the row while preserving the same character identity and foot baseline."
+ )
+ for message in [*row.get("errors", []), *row.get("warnings", [])]:
+ text = str(message)
+ if "chroma-adjacent" in text:
+ hints.append(
+ f"{state}: Visible chroma residue remained after extraction. Use a flat clean chroma background and keep key-colored pixels away from the character."
+ )
+ elif "edge" in text:
+ hints.append(
+ f"{state}: Sprite content touched the frame edge. Leave the requested safe margin around every full-body pose."
+ )
+ elif "pitch" in text or "runlen" in text or "grid" in text:
+ hints.append(
+ f"{state}: Pixel-grid pitch instability was detected. Regenerate with a clearer true low-resolution pixel grid, or rerun extraction with the runlen crosscheck visible and review the before/after grid proof."
+ )
+ return hints
+
+
+def score_inspection(report: dict[str, Any]) -> dict[str, Any]:
+ rows: list[dict[str, Any]] = []
+ hints: list[str] = []
+ thresholds = report.get("thresholds") or {}
+ histogram_min = float(thresholds.get("histogram_min", 0.0))
+ dhash_min = float(thresholds.get("dhash_min", 0.55))
+ for row in report.get("rows", []):
+ expected = int(row.get("expected_frames", 0))
+ found = int(row.get("found_frames", 0))
+ errors = list(row.get("errors", []))
+ warnings = list(row.get("warnings", []))
+ metrics = row.get("metrics") or {}
+ score = 100.0
+ if found != expected:
+ score -= 35 + 10 * abs(found - expected)
+ score -= 13 * len(errors)
+ score -= 3 * len(warnings)
+ if float(metrics.get("motion_presence", 1.0)) < 0.01 and expected > 1:
+ score -= 12
+ if float((metrics.get("dhash_similarity") or {}).get("min", 1.0)) < dhash_min:
+ score -= 10
+ if histogram_min > 0 and float((metrics.get("histogram_intersection") or {}).get("min", 1.0)) < histogram_min:
+ score -= 10
+ score = max(0.0, min(100.0, score))
+ row_hints = _unique(_hint_for_row(row, histogram_min=histogram_min, dhash_min=dhash_min))
+ hints.extend(row_hints)
+ rows.append(
+ {
+ "state": row.get("state"),
+ "score": round(score, 2),
+ "candidate_rank": found * 100 - len(errors) * 10 - len(warnings),
+ "expected_frames": expected,
+ "found_frames": found,
+ "errors": errors,
+ "warnings": warnings,
+ "hints": row_hints,
+ }
+ )
+ scores = [float(row["score"]) for row in rows]
+ return {
+ "ok": bool(rows) and all(row["score"] >= 90 and not row["errors"] for row in rows),
+ "kind": "sprite-gen-score-report",
+ "source_report": report.get("run_dir"),
+ "overall_score": round(mean(scores), 2) if scores else 0.0,
+ "candidate_rank": sum(int(row["candidate_rank"]) for row in rows),
+ "rows": rows,
+ "hints": _unique(hints),
+ }
+
+
+def _run(args: argparse.Namespace) -> int:
+ report = json.loads(args.inspect_report.read_text(encoding="utf-8"))
+ scored = score_inspection(report)
+ if not args.no_write:
+ output = Path(args.output)
+ if not output.is_absolute():
+ output = args.inspect_report.parent / output
+ atomic_write_text(output, json.dumps(scored, ensure_ascii=False, indent=2) + "\n")
+ print(json.dumps({k: v for k, v in scored.items() if k != "rows"}, ensure_ascii=False, indent=2))
+ return 0 if scored["ok"] else 1
+
+
+def run(**kwargs: object) -> int:
+ return _run(_namespace_from_kwargs(**kwargs))
+
+
+def main() -> int:
+ return _run(_build_parser().parse_args())
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/sprite_gen/serve/__init__.py b/sprite_gen/serve/__init__.py
new file mode 100644
index 0000000..9881313
--- /dev/null
+++ b/sprite_gen/serve/__init__.py
@@ -0,0 +1 @@
+# SPDX-License-Identifier: Apache-2.0
diff --git a/sprite_gen/serve/composer/composer.css b/sprite_gen/serve/composer/composer.css
new file mode 100644
index 0000000..a643c58
--- /dev/null
+++ b/sprite_gen/serve/composer/composer.css
@@ -0,0 +1,280 @@
+/* SPDX-License-Identifier: Apache-2.0 */
+/* 조립 캔버스 — 큐레이터와 같은 화이트 베이스 토큰 (중립 그레이 + 블루 액센트 1개) */
+:root {
+ color-scheme: light;
+ --bg: #f6f7f9;
+ --panel: #ffffff;
+ --panel-2: #f1f3f6;
+ --line: #e4e7ec;
+ --text: #1f2430;
+ --muted: #6b7280;
+ --accent: #2563eb;
+ --accent-dim: #dbe5fb;
+ --danger: #dc2626;
+ --checker-a: #e9ebef;
+ --checker-b: #f4f5f7;
+}
+
+* { box-sizing: border-box; }
+/* `hidden` must win over any element's own display (.empty is display:flex,
+ #add-row is display:block — both would otherwise override the attribute). */
+[hidden] { display: none !important; }
+
+body {
+ margin: 0;
+ font: 14px/1.4 -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif;
+ background: var(--bg);
+ color: var(--text);
+}
+
+.topbar {
+ position: sticky;
+ top: 0;
+ z-index: 10;
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 10px 18px;
+ background: var(--panel);
+ border-bottom: 1px solid var(--line);
+}
+.title { font-size: 15px; }
+.muted { color: var(--muted); margin-left: 8px; font-weight: normal; font-size: 12px; }
+.actions { display: flex; align-items: center; gap: 12px; }
+.status { color: var(--muted); font-size: 12px; min-width: 60px; text-align: right; }
+.status.ok { color: #16a34a; }
+.status.err { color: var(--danger); }
+
+/* ── buttons: one component, variants change colour only (never size) ──
+ .btn is the single source for button shape — padding/height live here, so
+ no two buttons can diverge. --ghost/--accent/--dashed change colour/border
+ only. (This is the structural fix for the divergent-height defect.) */
+button { font: inherit; cursor: pointer; } /* reset (also covers icon buttons) */
+
+.btn {
+ padding: 7px 14px;
+ font-size: 13px;
+ border: 1px solid var(--line);
+ border-radius: 8px;
+ background: var(--panel);
+ color: var(--text);
+ white-space: nowrap;
+ box-shadow: 0 1px 2px rgba(16, 24, 40, 0.04);
+}
+.btn:hover { background: var(--panel-2); border-color: #d3d8e0; }
+.btn--ghost { background: transparent; box-shadow: none; }
+.btn--ghost:hover { background: var(--panel-2); }
+.btn--accent { background: var(--accent); color: #fff; border-color: var(--accent); }
+.btn--accent:hover { background: #1d55d0; border-color: #1d55d0; }
+.btn--dashed { display: block; width: 100%; border-style: dashed; color: var(--muted); background: transparent; box-shadow: none; }
+.btn--dashed:hover { background: var(--panel-2); color: var(--text); }
+
+/* ── layout ─────────────────────────────────────────────────────── */
+#layout {
+ display: grid;
+ grid-template-columns: 260px 1fr;
+ height: calc(100vh - 52px - 34px);
+}
+#sidebar {
+ border-right: 1px solid var(--line);
+ background: var(--panel);
+ overflow-y: auto;
+ display: flex;
+ flex-direction: column;
+}
+.panel-head {
+ padding: 9px 14px;
+ font-size: 11px;
+ letter-spacing: 0.04em;
+ text-transform: uppercase;
+ color: var(--muted);
+ border-bottom: 1px solid var(--line);
+ position: sticky;
+ top: 0;
+ background: var(--panel);
+}
+#tree { padding: 6px 0 20px; }
+#canvas { overflow-y: auto; padding: 18px 22px 40px; position: relative; }
+
+/* ── file tree ──────────────────────────────────────────────────── */
+.tree-node { user-select: none; }
+.tree-row {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ padding: 3px 12px;
+ cursor: default;
+ font-size: 13px;
+ border-radius: 6px;
+ margin: 0 6px;
+}
+.tree-row:hover { background: var(--panel-2); }
+.tree-row .twist {
+ width: 12px; height: 12px; flex: none;
+ color: var(--muted);
+ transition: transform 0.12s;
+}
+.tree-row.open .twist { transform: rotate(90deg); }
+.tree-row .leaf-dot { width: 12px; flex: none; }
+.tree-row .name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.tree-children { margin-left: 14px; }
+
+.tree-row.image { cursor: grab; }
+.tree-row.image:active { cursor: grabbing; }
+.tree-row.image .thumb {
+ width: 22px; height: 22px; flex: none;
+ object-fit: contain;
+ border: 1px solid var(--line);
+ border-radius: 4px;
+ background-color: var(--checker-a);
+ background-image:
+ linear-gradient(45deg, var(--checker-b) 25%, transparent 25%),
+ linear-gradient(-45deg, var(--checker-b) 25%, transparent 25%),
+ linear-gradient(45deg, transparent 75%, var(--checker-b) 75%),
+ linear-gradient(-45deg, transparent 75%, var(--checker-b) 75%);
+ background-size: 8px 8px;
+ background-position: 0 0, 0 4px, 4px -4px, -4px 0;
+}
+.tree-row.dragging { opacity: 0.4; }
+
+/* ── empty state ────────────────────────────────────────────────── */
+.empty {
+ position: absolute;
+ inset: 0;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ gap: 10px;
+ color: var(--muted);
+ text-align: center;
+ padding: 20px;
+}
+.empty svg { color: #c4c9d2; }
+.empty-title { font-size: 16px; color: var(--text); font-weight: 600; }
+.empty-sub { font-size: 13px; max-width: 380px; line-height: 1.6; }
+.empty-actions { display: flex; gap: 8px; align-items: center; margin-top: 6px; }
+
+/* ── rows (composition canvas) ──────────────────────────────────── */
+.row {
+ background: var(--panel);
+ border: 1px solid var(--line);
+ border-radius: 10px;
+ margin-bottom: 14px;
+ overflow: hidden;
+}
+.row-head {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 8px 12px;
+ border-bottom: 1px solid var(--line);
+ background: var(--panel-2);
+}
+.row-head .row-name {
+ font-weight: 600;
+ font-size: 13.5px;
+ border: 1px solid transparent;
+ border-radius: 6px;
+ padding: 2px 6px;
+ background: transparent;
+ color: var(--text);
+ min-width: 120px;
+}
+.row-head .row-name:focus { outline: none; border-color: var(--accent); background: var(--panel); }
+.row-head .count { color: var(--muted); font-size: 12px; }
+.row-head .spacer { flex: 1; }
+.row-head .row-del {
+ color: var(--muted); border: none; background: transparent; box-shadow: none;
+ padding: 3px 6px;
+}
+.row-head .row-del:hover { color: var(--danger); background: transparent; }
+
+.row-strip {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 8px;
+ padding: 12px;
+ min-height: 84px;
+ align-content: flex-start;
+}
+.row-strip.drop-hot {
+ background: var(--accent-dim);
+ outline: 2px dashed var(--accent);
+ outline-offset: -6px;
+}
+.row-empty-hint {
+ color: var(--muted);
+ font-size: 12.5px;
+ align-self: center;
+ padding: 0 6px;
+}
+
+.cell {
+ position: relative;
+ width: 72px;
+}
+.cell .frame {
+ width: 72px; height: 72px;
+ object-fit: contain;
+ border: 1px solid var(--line);
+ border-radius: 6px;
+ background-color: var(--checker-a);
+ background-image:
+ linear-gradient(45deg, var(--checker-b) 25%, transparent 25%),
+ linear-gradient(-45deg, var(--checker-b) 25%, transparent 25%),
+ linear-gradient(45deg, transparent 75%, var(--checker-b) 75%),
+ linear-gradient(-45deg, transparent 75%, var(--checker-b) 75%);
+ background-size: 12px 12px;
+ background-position: 0 0, 0 6px, 6px -6px, -6px 0;
+ display: block;
+}
+.cell .cap {
+ font-size: 10.5px;
+ color: var(--muted);
+ margin-top: 3px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+.cell .cell-del {
+ position: absolute;
+ top: -6px; right: -6px;
+ width: 18px; height: 18px;
+ border-radius: 50%;
+ border: 1px solid var(--line);
+ background: var(--panel);
+ color: var(--muted);
+ font-size: 11px;
+ line-height: 1;
+ padding: 0;
+ display: none;
+ box-shadow: 0 1px 3px rgba(16,24,40,0.12);
+}
+.cell:hover .cell-del { display: block; }
+.cell .cell-del:hover { color: var(--danger); }
+
+#canvas-actions { margin-top: 2px; }
+
+#build-bar {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ margin-top: 18px;
+ padding-top: 16px;
+ border-top: 1px solid var(--line);
+}
+.build-result { font-size: 12.5px; color: var(--muted); }
+.build-result.ok { color: #16a34a; }
+.build-result.err { color: var(--danger); }
+
+.hintbar {
+ height: 34px;
+ display: flex;
+ align-items: center;
+ padding: 0 18px;
+ font-size: 12px;
+ color: var(--muted);
+ background: var(--panel);
+ border-top: 1px solid var(--line);
+}
diff --git a/sprite_gen/serve/composer/index.html b/sprite_gen/serve/composer/index.html
new file mode 100644
index 0000000..002efdd
--- /dev/null
+++ b/sprite_gen/serve/composer/index.html
@@ -0,0 +1,59 @@
+<!DOCTYPE html>
+<!-- SPDX-License-Identifier: Apache-2.0 -->
+<html lang="en">
+ <head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <title>sprite-gen compose</title>
+ <link rel="stylesheet" href="/composer.css" />
+ </head>
+ <body>
+ <!-- Skeleton only: interactive controls are rendered into the mount points
+ (#toolbar, #empty-actions, #canvas-actions, #build-bar) by controls.js,
+ so a control is defined once and never duplicated as markup. -->
+ <header class="topbar">
+ <div class="title">
+ <strong>sprite-gen</strong> <span id="t-title"></span>
+ <span id="mount-label" class="muted"></span>
+ </div>
+ <div class="actions" id="toolbar">
+ <span id="status" class="status"></span>
+ </div>
+ </header>
+
+ <div id="layout">
+ <aside id="sidebar">
+ <div id="tree-head" class="panel-head"></div>
+ <div id="tree"></div>
+ </aside>
+ <main id="canvas">
+ <div id="empty" class="empty" hidden>
+ <svg viewBox="0 0 48 48" width="44" height="44" aria-hidden="true">
+ <rect x="6" y="10" width="36" height="28" rx="3" fill="none" stroke="currentColor" stroke-width="2"/>
+ <path d="M6 16 L20 16 L23 12 L6 12 Z" fill="none" stroke="currentColor" stroke-width="2" stroke-linejoin="round"/>
+ <path d="M18 27 L24 27 M21 24 L21 30" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
+ </svg>
+ <div id="empty-title" class="empty-title"></div>
+ <div id="empty-sub" class="empty-sub"></div>
+ <div class="empty-actions" id="empty-actions"></div>
+ </div>
+ <div id="rows"></div>
+ <div id="canvas-actions"></div>
+ <div id="build-bar" hidden></div>
+ </main>
+ </div>
+
+ <footer class="hintbar" id="hintbar"></footer>
+
+ <!-- Load order = dependency order (classic scripts share globals):
+ strings -> ui -> api -> session -> library/canvas -> controls -> boot -->
+ <script src="/src/i18n.js"></script>
+ <script src="/src/ui.js"></script>
+ <script src="/src/api.js"></script>
+ <script src="/src/session.js"></script>
+ <script src="/src/library.js"></script>
+ <script src="/src/canvas.js"></script>
+ <script src="/src/controls.js"></script>
+ <script src="/src/boot.js"></script>
+ </body>
+</html>
diff --git a/sprite_gen/serve/composer/src/api.js b/sprite_gen/serve/composer/src/api.js
new file mode 100644
index 0000000..c0490d2
--- /dev/null
+++ b/sprite_gen/serve/composer/src/api.js
@@ -0,0 +1,68 @@
+// SPDX-License-Identifier: Apache-2.0
+// composer/api.js — the server boundary. Every call to the compose server lives
+// here; no other module builds a fetch. Domain: transport, not model or view.
+
+async function apiGetState() {
+ const res = await fetch("/api/state");
+ return res.json();
+}
+
+async function apiMount(dir) {
+ const res = await fetch("/api/mount", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ dir }),
+ });
+ const data = await res.json();
+ if (!res.ok) throw new Error(data.error || `HTTP ${res.status}`);
+ return data; // { mount, dir, entries }
+}
+
+// Native OS chooser (server-side). kind "folder" -> { dir }; kind "image" ->
+// { dir: <parent>, files }. { cancelled: true } if dismissed; throws with code
+// "unsupported-platform" (501) off macOS so the caller can fall back to a prompt.
+async function apiPick(kind) {
+ const res = await fetch(`/api/pick?kind=${encodeURIComponent(kind)}`, { method: "POST" });
+ const data = await res.json();
+ if (res.status === 501) {
+ const err = new Error(data.error || "unsupported");
+ err.code = "unsupported-platform";
+ throw err;
+ }
+ if (!res.ok) throw new Error(data.error || `HTTP ${res.status}`);
+ return data; // { dir } | { dir, files } | { cancelled: true }
+}
+
+async function apiBrowse(dir) {
+ const url = dir ? `/api/browse?dir=${encodeURIComponent(dir)}` : "/api/browse";
+ const res = await fetch(url);
+ const data = await res.json();
+ if (!res.ok) throw new Error(data.error || `HTTP ${res.status}`);
+ return data; // { dir, entries }
+}
+
+function imgUrl(path) {
+ return `/api/browse-img?path=${encodeURIComponent(path)}`;
+}
+
+async function apiBuild(outDir, rows) {
+ const res = await fetch("/api/build", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ outDir, rows }),
+ });
+ const data = await res.json();
+ if (!res.ok) throw new Error(data.error || `HTTP ${res.status}`);
+ return data; // { runDir, states, frames, cell }
+}
+
+async function apiOpenCuration(runDir) {
+ const res = await fetch("/api/open-curation", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ runDir }),
+ });
+ const data = await res.json();
+ if (!res.ok) throw new Error(data.error || `HTTP ${res.status}`);
+ return data; // { url }
+}
diff --git a/sprite_gen/serve/composer/src/boot.js b/sprite_gen/serve/composer/src/boot.js
new file mode 100644
index 0000000..8aeccce
--- /dev/null
+++ b/sprite_gen/serve/composer/src/boot.js
@@ -0,0 +1,36 @@
+// SPDX-License-Identifier: Apache-2.0
+// composer/boot.js — bootstrap only. Loads server state, sets language, renders
+// the controls (controls.js) and the initial view. Loaded last; classic scripts
+// share globals via the load order declared in index.html.
+
+// Static text nodes (headings, empty-state copy, mount label). Interactive
+// controls own their own labels via controls.renderControls().
+function applyText() {
+ document.documentElement.lang = lang;
+ document.getElementById("t-title").textContent = t("title");
+ document.getElementById("tree-head").textContent = t("treeHead");
+ document.getElementById("empty-title").textContent = t("emptyTitle");
+ document.getElementById("empty-sub").textContent = t("emptySub");
+ document.getElementById("hintbar").textContent = t("emptySub");
+ document.getElementById("mount-label").textContent = session.mount || t("noMount");
+}
+
+async function boot() {
+ let state = {};
+ try { state = await apiGetState(); } catch (_) { /* serve blank */ }
+ lang = new URLSearchParams(location.search).get("lang") || state.lang || "en";
+ session.mount = state.mount || null;
+
+ applyText();
+ renderControls();
+ refreshCanvasChrome();
+
+ if (session.mount) {
+ await loadTree(session.mount);
+ if (session.rows.length === 0) addRow();
+ renderRows();
+ setStatus(t("ready"));
+ }
+}
+
+boot();
diff --git a/sprite_gen/serve/composer/src/canvas.js b/sprite_gen/serve/composer/src/canvas.js
new file mode 100644
index 0000000..1d381da
--- /dev/null
+++ b/sprite_gen/serve/composer/src/canvas.js
@@ -0,0 +1,122 @@
+// SPDX-License-Identifier: Apache-2.0
+// composer/canvas.js — the row composition canvas (right main).
+//
+// Each row maps 1:1 to a run-dir state. Files dropped from the library become
+// reference cells (session.js). Rendering is a straightforward re-draw from the
+// session; nothing here writes to disk. Controls come from ui.js (icon buttons).
+
+function makeCell(row, cell) {
+ const el = document.createElement("div");
+ el.className = "cell";
+ const img = document.createElement("img");
+ img.className = "frame";
+ img.src = imgUrl(cell.path);
+ img.alt = cell.name;
+ const cap = document.createElement("div");
+ cap.className = "cap";
+ cap.textContent = cell.name;
+ cap.title = cell.path;
+ const del = iconButton({
+ name: "close",
+ cls: "cell-del",
+ onClick: () => { removeCell(row.id, cell.path); renderRows(); },
+ });
+ el.appendChild(img);
+ el.appendChild(cap);
+ el.appendChild(del);
+ return el;
+}
+
+function makeRow(row) {
+ const el = document.createElement("div");
+ el.className = "row";
+ el.dataset.rowId = row.id;
+
+ const head = document.createElement("div");
+ head.className = "row-head";
+ const nameInput = document.createElement("input");
+ nameInput.className = "row-name";
+ nameInput.value = row.name;
+ nameInput.spellcheck = false;
+ nameInput.addEventListener("change", () => {
+ row.name = nameInput.value.trim() || row.name;
+ nameInput.value = row.name;
+ });
+ const count = document.createElement("span");
+ count.className = "count";
+ count.textContent = t("frames", row.cells.length);
+ const spacer = document.createElement("span");
+ spacer.className = "spacer";
+ const del = iconButton({
+ name: "close",
+ cls: "row-del",
+ title: t("deleteRow"),
+ onClick: () => { deleteRow(row.id); renderRows(); },
+ });
+ head.appendChild(nameInput);
+ head.appendChild(count);
+ head.appendChild(spacer);
+ head.appendChild(del);
+
+ const strip = document.createElement("div");
+ strip.className = "row-strip";
+ if (row.cells.length === 0) {
+ const hint = document.createElement("span");
+ hint.className = "row-empty-hint";
+ hint.textContent = t("rowEmptyHint");
+ strip.appendChild(hint);
+ } else {
+ for (const cell of row.cells) strip.appendChild(makeCell(row, cell));
+ }
+
+ // drop target
+ strip.addEventListener("dragover", (ev) => {
+ if (ev.dataTransfer.types.includes("application/x-sprite-file")) {
+ ev.preventDefault();
+ ev.dataTransfer.dropEffect = "copy";
+ strip.classList.add("drop-hot");
+ }
+ });
+ strip.addEventListener("dragleave", () => strip.classList.remove("drop-hot"));
+ strip.addEventListener("drop", (ev) => {
+ ev.preventDefault();
+ strip.classList.remove("drop-hot");
+ const raw = ev.dataTransfer.getData("application/x-sprite-file");
+ if (!raw) return;
+ let file;
+ try { file = JSON.parse(raw); } catch { return; }
+ if (addCell(row.id, file)) {
+ setStatus(t("dropAdded", file.name, row.name), "ok");
+ renderRows();
+ }
+ });
+
+ el.appendChild(head);
+ el.appendChild(strip);
+ return el;
+}
+
+function renderRows() {
+ const rowsEl = document.getElementById("rows");
+ rowsEl.innerHTML = "";
+ for (const row of session.rows) rowsEl.appendChild(makeRow(row));
+ updateBuildBar();
+}
+
+// The build bar appears once at least one row holds a file — a build with no
+// frames is not a build. renderRows() runs on every composition mutation, so
+// hiding the "open curation" button here retires a stale build: after an edit
+// the last run dir is superseded, and doBuild() re-shows the button on success.
+function updateBuildBar() {
+ document.getElementById("build-bar").hidden = !(session.mount && sessionHasFrames());
+ document.getElementById("open-cur-btn").hidden = true;
+ document.getElementById("build-result").textContent = "";
+}
+
+// Toggle the blank/mounted view. The add-row button's visibility is owned by
+// controls.renderCanvasActions (it renders it hidden until a folder is open).
+function refreshCanvasChrome() {
+ const mounted = !!session.mount;
+ document.getElementById("empty").hidden = mounted;
+ document.getElementById("rows").hidden = !mounted;
+}
diff --git a/sprite_gen/serve/composer/src/controls.js b/sprite_gen/serve/composer/src/controls.js
new file mode 100644
index 0000000..0189a41
--- /dev/null
+++ b/sprite_gen/serve/composer/src/controls.js
@@ -0,0 +1,165 @@
+// SPDX-License-Identifier: Apache-2.0
+// composer/controls.js — the app's action controls, rendered from single sources.
+//
+// Every button here goes through ui.button (one shape, one size). The open actions
+// are defined ONCE and rendered into both the toolbar and the empty state, so the
+// two placements cannot drift apart — the structural reason two "Open" buttons can
+// no longer differ in height.
+
+const OPEN_ACTIONS = [
+ { kind: "folder", labelKey: "mount", remountKey: "remount" },
+ { kind: "image", labelKey: "openImage" },
+];
+
+function openActionButtons() {
+ return OPEN_ACTIONS.map((a) => {
+ const label = a.kind === "folder" && session.mount ? t(a.remountKey) : t(a.labelKey);
+ return button({ label, onClick: () => doMount(a.kind) });
+ });
+}
+
+function renderToolbar() {
+ const bar = document.getElementById("toolbar");
+ const status = document.getElementById("status"); // keep the live status node
+ bar.innerHTML = "";
+ bar.appendChild(status);
+ for (const b of openActionButtons()) bar.appendChild(b);
+ bar.appendChild(button({ label: t("langLabel"), variant: "ghost", onClick: toggleLang }));
+}
+
+function renderEmptyActions() {
+ const c = document.getElementById("empty-actions");
+ c.innerHTML = "";
+ for (const b of openActionButtons()) c.appendChild(b);
+}
+
+function renderCanvasActions() {
+ const c = document.getElementById("canvas-actions");
+ c.innerHTML = "";
+ c.appendChild(button({
+ id: "add-row", label: t("addRow"), variant: "dashed",
+ hidden: !session.mount,
+ onClick: () => { addRow(); renderRows(); },
+ }));
+}
+
+function renderBuildBar() {
+ const bar = document.getElementById("build-bar");
+ bar.innerHTML = "";
+ bar.appendChild(button({ id: "build-btn", label: t("build"), variant: "accent", onClick: doBuild }));
+ bar.appendChild(button({ id: "open-cur-btn", label: t("openCuration"), hidden: true }));
+ const res = document.createElement("span");
+ res.id = "build-result";
+ res.className = "build-result";
+ bar.appendChild(res);
+}
+
+function renderControls() {
+ renderToolbar();
+ renderEmptyActions();
+ renderCanvasActions();
+ renderBuildBar();
+}
+
+function toggleLang() {
+ lang = lang === "en" ? "ko" : "en";
+ const url = new URL(location.href);
+ url.searchParams.set("lang", lang);
+ history.replaceState(null, "", url);
+ applyText();
+ renderControls();
+ renderRows();
+}
+
+// ── open / mount ──────────────────────────────────────────────────
+async function resolveFolder(kind) {
+ // Prefer the native OS chooser; fall back to a path prompt only where the native
+ // dialog is unavailable (non-macOS) — an explicit, observable path. For kind
+ // "image" the server returns the picked image's parent folder as `dir`.
+ try {
+ const picked = await apiPick(kind);
+ if (picked.cancelled) return null;
+ return picked.dir;
+ } catch (e) {
+ if (e.code === "unsupported-platform") {
+ const typed = window.prompt(t("mountPrompt"), session.mount || "");
+ return typed ? typed.trim() : null;
+ }
+ throw e;
+ }
+}
+
+async function doMount(kind = "folder") {
+ let dir;
+ try {
+ dir = await resolveFolder(kind);
+ } catch (e) {
+ setStatus(t("mountFail", e.message), "err");
+ return;
+ }
+ if (!dir) return;
+ try {
+ const data = await apiMount(dir);
+ session.mount = data.mount;
+ applyText();
+ renderToolbar(); // folder button flips to "change folder"
+ renderCanvasActions(); // add-row becomes visible
+ refreshCanvasChrome();
+ await loadTree(session.mount);
+ if (session.rows.length === 0) addRow(); // seed one row so the drop target shows
+ renderRows();
+ setStatus(t("ready"), "ok");
+ } catch (e) {
+ setStatus(t("mountFail", e.message), "err");
+ }
+}
+
+// ── build / handoff ───────────────────────────────────────────────
+function suggestOutDir() {
+ const m = (session.mount || "").replace(/\/+$/, "");
+ return m ? `${m}-sprite` : "";
+}
+
+async function doBuild() {
+ if (!sessionHasFrames()) {
+ setStatus(t("needRows"), "err");
+ return;
+ }
+ const outDir = window.prompt(t("buildPrompt"), suggestOutDir());
+ if (!outDir) return;
+ const result = document.getElementById("build-result");
+ const buildBtn = document.getElementById("build-btn");
+ const openBtn = document.getElementById("open-cur-btn");
+ buildBtn.disabled = true;
+ result.className = "build-result";
+ result.textContent = t("building");
+ try {
+ const data = await apiBuild(outDir.trim(), sessionBuildRows());
+ result.className = "build-result ok";
+ result.textContent = t("buildDone", data.states.length, data.frames) + " · " + data.runDir;
+ openBtn.hidden = false;
+ openBtn.onclick = () => doOpenCuration(data.runDir);
+ setStatus(t("ready"), "ok");
+ } catch (e) {
+ result.className = "build-result err";
+ result.textContent = t("buildFail", e.message);
+ setStatus(t("buildFail", e.message), "err");
+ } finally {
+ buildBtn.disabled = false;
+ }
+}
+
+async function doOpenCuration(runDir) {
+ const openBtn = document.getElementById("open-cur-btn");
+ openBtn.disabled = true;
+ setStatus(t("opening"));
+ try {
+ const data = await apiOpenCuration(runDir);
+ window.open(data.url, "_blank");
+ setStatus(t("ready"), "ok");
+ } catch (e) {
+ setStatus(t("openFail", e.message), "err");
+ } finally {
+ openBtn.disabled = false;
+ }
+}
diff --git a/sprite_gen/serve/composer/src/i18n.js b/sprite_gen/serve/composer/src/i18n.js
new file mode 100644
index 0000000..fe15b98
--- /dev/null
+++ b/sprite_gen/serve/composer/src/i18n.js
@@ -0,0 +1,75 @@
+// SPDX-License-Identifier: Apache-2.0
+// composer/i18n.js — bilingual strings (en/ko). Classic script, shared globals.
+
+const STR = {
+ en: {
+ title: "compose",
+ mount: "Open folder",
+ remount: "Change folder",
+ openImage: "Open image",
+ treeHead: "Library",
+ emptyTitle: "Compose a sprite from a folder",
+ emptySub: "Open a folder of images, then drag files onto rows to build each animation state. Originals are never copied or changed.",
+ emptyMount: "Open a folder",
+ addRow: "+ Add row",
+ newRowName: "new-state",
+ rowEmptyHint: "Drag image files here",
+ frames: (n) => `${n} frame${n === 1 ? "" : "s"}`,
+ deleteRow: "Delete row",
+ mountPrompt: "Absolute path of the folder to open:",
+ mounted: (p) => p,
+ mountFail: (m) => `Open failed: ${m}`,
+ browseFail: (m) => `Browse failed: ${m}`,
+ ready: "Ready",
+ dropAdded: (name, row) => `Added ${name} to ${row}`,
+ noMount: "No folder open yet",
+ build: "Build sprite",
+ building: "Building...",
+ buildPrompt: "Output run directory (absolute path):",
+ buildDone: (states, frames) => `Built ${states} state${states === 1 ? "" : "s"}, ${frames} frame${frames === 1 ? "" : "s"}`,
+ buildFail: (m) => `Build failed: ${m}`,
+ needRows: "Add at least one file to a row first",
+ openCuration: "Open curation view",
+ opening: "Opening curation view...",
+ openFail: (m) => `Open failed: ${m}`,
+ langLabel: "한국어",
+ },
+ ko: {
+ title: "조립",
+ mount: "폴더 열기",
+ remount: "폴더 바꾸기",
+ openImage: "이미지 열기",
+ treeHead: "라이브러리",
+ emptyTitle: "폴더에서 스프라이트를 조립한다",
+ emptySub: "이미지 폴더를 열고, 파일을 줄로 드래그해서 각 애니메이션 상태를 짠다. 원본은 복사도 변경도 되지 않는다.",
+ emptyMount: "폴더 열기",
+ addRow: "+ 줄 추가",
+ newRowName: "새-상태",
+ rowEmptyHint: "여기로 이미지 파일을 드래그",
+ frames: (n) => `${n}장`,
+ deleteRow: "줄 삭제",
+ mountPrompt: "열 폴더의 절대 경로:",
+ mounted: (p) => p,
+ mountFail: (m) => `폴더 열기 실패: ${m}`,
+ browseFail: (m) => `탐색 실패: ${m}`,
+ ready: "준비됨",
+ dropAdded: (name, row) => `${name} 을(를) ${row} 에 추가`,
+ noMount: "아직 연 폴더 없음",
+ build: "스프라이트 빌드",
+ building: "빌드 중...",
+ buildPrompt: "출력 run 디렉토리 (절대 경로):",
+ buildDone: (states, frames) => `${states}개 상태, ${frames}장 빌드됨`,
+ buildFail: (m) => `빌드 실패: ${m}`,
+ needRows: "먼저 줄에 파일을 하나 이상 넣어라",
+ openCuration: "큐레이션 뷰 열기",
+ opening: "큐레이션 뷰 여는 중...",
+ openFail: (m) => `열기 실패: ${m}`,
+ langLabel: "English",
+ },
+};
+
+let lang = "en";
+function t(key, ...args) {
+ const v = STR[lang][key];
+ return typeof v === "function" ? v(...args) : v;
+}
diff --git a/sprite_gen/serve/composer/src/library.js b/sprite_gen/serve/composer/src/library.js
new file mode 100644
index 0000000..c3296c8
--- /dev/null
+++ b/sprite_gen/serve/composer/src/library.js
@@ -0,0 +1,88 @@
+// SPDX-License-Identifier: Apache-2.0
+// composer/library.js — the read-only library file tree (left sidebar).
+//
+// Lazy: a folder's children are fetched only when first expanded. Image rows are
+// drag sources; the payload is the file's absolute path + name, which a canvas row
+// consumes as a reference. The library never mutates the folder — it only reads.
+
+function makeDirNode(entry) {
+ const node = document.createElement("div");
+ node.className = "tree-node";
+ const row = document.createElement("div");
+ row.className = "tree-row dir";
+ row.innerHTML = icon("twist") + `<span class="name"></span>`;
+ row.querySelector(".name").textContent = entry.name;
+ const children = document.createElement("div");
+ children.className = "tree-children";
+ children.hidden = true;
+ let loaded = false;
+
+ row.addEventListener("click", async () => {
+ const open = children.hidden;
+ if (open && !loaded) {
+ try {
+ const data = await apiBrowse(entry.path);
+ renderEntries(children, data.entries);
+ loaded = true;
+ } catch (e) {
+ setStatus(t("browseFail", e.message), "err");
+ return;
+ }
+ }
+ children.hidden = !open;
+ row.classList.toggle("open", open);
+ });
+
+ node.appendChild(row);
+ node.appendChild(children);
+ return node;
+}
+
+function makeImageNode(entry) {
+ const node = document.createElement("div");
+ node.className = "tree-node";
+ const row = document.createElement("div");
+ row.className = "tree-row image";
+ row.draggable = true;
+ const thumb = document.createElement("img");
+ thumb.className = "thumb";
+ thumb.src = imgUrl(entry.path);
+ thumb.loading = "lazy";
+ thumb.alt = "";
+ const name = document.createElement("span");
+ name.className = "name";
+ name.textContent = entry.name;
+ row.appendChild(thumb);
+ row.appendChild(name);
+
+ row.addEventListener("dragstart", (ev) => {
+ ev.dataTransfer.setData(
+ "application/x-sprite-file",
+ JSON.stringify({ path: entry.path, name: entry.name })
+ );
+ ev.dataTransfer.effectAllowed = "copy";
+ row.classList.add("dragging");
+ });
+ row.addEventListener("dragend", () => row.classList.remove("dragging"));
+
+ node.appendChild(row);
+ return node;
+}
+
+function renderEntries(container, entries) {
+ container.innerHTML = "";
+ for (const entry of entries) {
+ container.appendChild(entry.type === "dir" ? makeDirNode(entry) : makeImageNode(entry));
+ }
+}
+
+async function loadTree(mountDir) {
+ const treeEl = document.getElementById("tree");
+ treeEl.innerHTML = "";
+ try {
+ const data = await apiBrowse(mountDir);
+ renderEntries(treeEl, data.entries);
+ } catch (e) {
+ setStatus(t("browseFail", e.message), "err");
+ }
+}
diff --git a/sprite_gen/serve/composer/src/session.js b/sprite_gen/serve/composer/src/session.js
new file mode 100644
index 0000000..8df6d82
--- /dev/null
+++ b/sprite_gen/serve/composer/src/session.js
@@ -0,0 +1,59 @@
+// SPDX-License-Identifier: Apache-2.0
+// composer/session.js — the virtual composition session (pure model).
+//
+// The "unsaved buffer": the mounted library root and rows -> file references.
+// Nothing here touches the network or the DOM. A row cell is a reference
+// { path, name } into the mounted folder; no original file is copied. The build
+// seam materializes this into a run dir.
+
+const session = {
+ mount: null, // absolute path of the mounted library root (or null)
+ rows: [], // [{ id, name, cells: [{ path, name }] }]
+};
+
+let _rowSeq = 0;
+function newRowId() {
+ _rowSeq += 1;
+ return `row-${_rowSeq}`;
+}
+
+function addRow(name) {
+ const row = { id: newRowId(), name: name || t("newRowName"), cells: [] };
+ session.rows.push(row);
+ return row;
+}
+
+function deleteRow(id) {
+ session.rows = session.rows.filter((r) => r.id !== id);
+}
+
+function rowById(id) {
+ return session.rows.find((r) => r.id === id) || null;
+}
+
+// A file may sit in more than one row, but not twice in the SAME row — a duplicate
+// drop on one row is a no-op.
+function addCell(rowId, file) {
+ const row = rowById(rowId);
+ if (!row) return false;
+ if (row.cells.some((c) => c.path === file.path)) return false;
+ row.cells.push({ path: file.path, name: file.name });
+ return true;
+}
+
+function removeCell(rowId, path) {
+ const row = rowById(rowId);
+ if (!row) return;
+ row.cells = row.cells.filter((c) => c.path !== path);
+}
+
+function sessionHasFrames() {
+ return session.rows.some((r) => r.cells.length > 0);
+}
+
+// The build payload: rows with at least one cell, as { name, cells:[{path,name}] }.
+function sessionBuildRows() {
+ return session.rows
+ .filter((r) => r.cells.length)
+ .map((r) => ({ name: r.name, cells: r.cells.map((c) => ({ path: c.path, name: c.name })) }));
+}
diff --git a/sprite_gen/serve/composer/src/ui.js b/sprite_gen/serve/composer/src/ui.js
new file mode 100644
index 0000000..72b1fe9
--- /dev/null
+++ b/sprite_gen/serve/composer/src/ui.js
@@ -0,0 +1,53 @@
+// SPDX-License-Identifier: Apache-2.0
+// composer/ui.js — shared UI primitives. The single source for icons and for
+// button creation, so two controls can never diverge in size or shape.
+
+// Inline SVG icons — one definition each (previously duplicated as delSvg/twistSvg).
+const ICONS = {
+ close:
+ '<svg viewBox="0 0 16 16" width="11" height="11" aria-hidden="true">'
+ + '<path d="M4 4l8 8M12 4l-8 8" fill="none" stroke="currentColor" '
+ + 'stroke-width="1.8" stroke-linecap="round"/></svg>',
+ twist:
+ '<svg class="twist" viewBox="0 0 16 16" aria-hidden="true">'
+ + '<path d="M6 4l5 4-5 4" fill="none" stroke="currentColor" stroke-width="1.8" '
+ + 'stroke-linecap="round" stroke-linejoin="round"/></svg>',
+};
+
+function icon(name) {
+ return ICONS[name] || "";
+}
+
+// The ONE place a text/action button is created. `variant` changes colour only —
+// padding and height live on `.btn`, so no two buttons can differ in size. This is
+// the structural fix for "Open image is a different height from Open folder".
+// variant: "default" | "ghost" | "accent" | "dashed".
+function button({ label, variant = "default", onClick, id, title, hidden = false } = {}) {
+ const el = document.createElement("button");
+ el.type = "button";
+ el.className = "btn" + (variant && variant !== "default" ? ` btn--${variant}` : "");
+ if (id) el.id = id;
+ if (title) el.title = title;
+ el.hidden = hidden;
+ if (label != null) el.textContent = label;
+ if (onClick) el.addEventListener("click", onClick);
+ return el;
+}
+
+// A small icon-only button (card actions: delete a cell/row). Its own component,
+// consistent among its instances; shares the icon SSoT above.
+function iconButton({ name, cls, onClick, title }) {
+ const el = document.createElement("button");
+ el.type = "button";
+ el.className = cls;
+ if (title) el.title = title;
+ el.innerHTML = icon(name);
+ if (onClick) el.addEventListener("click", onClick);
+ return el;
+}
+
+function setStatus(msg, kind) {
+ const el = document.getElementById("status");
+ el.textContent = msg || "";
+ el.className = "status" + (kind ? " " + kind : "");
+}
diff --git a/sprite_gen/serve/curator/curator.css b/sprite_gen/serve/curator/curator.css
new file mode 100644
index 0000000..d3e97fd
--- /dev/null
+++ b/sprite_gen/serve/curator/curator.css
@@ -0,0 +1,1572 @@
+/* SPDX-License-Identifier: Apache-2.0 */
+/* 깨끗한 라이트(화이트 베이스) 테마 — 중립 그레이 + 블루 액센트 1개 (2026-07-02) */
+:root {
+ color-scheme: light;
+ --bg: #f6f7f9;
+ --panel: #ffffff;
+ --panel-2: #f1f3f6;
+ --line: #e4e7ec;
+ --text: #1f2430;
+ --muted: #6b7280;
+ --accent: #2563eb;
+ --accent-dim: #dbe5fb;
+ --reject: #eceef2;
+ --danger: #dc2626;
+ --checker-a: #e9ebef;
+ --checker-b: #f4f5f7;
+}
+
+* { box-sizing: border-box; }
+
+body {
+ margin: 0;
+ font: 14px/1.4 -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif;
+ background: var(--bg);
+ color: var(--text);
+}
+
+.topbar {
+ position: sticky;
+ top: 0;
+ z-index: 10;
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 10px 18px;
+ background: var(--panel);
+ border-bottom: 1px solid var(--line);
+}
+.title { font-size: 15px; }
+.muted { color: var(--muted); margin-left: 8px; font-weight: normal; }
+.actions { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; justify-content: flex-end; row-gap: 6px; }
+.status { color: var(--muted); font-size: 12px; min-width: 80px; text-align: right; }
+.status.ok { color: #16a34a; }
+.status.err { color: var(--danger); }
+/* 고칠 수 없지만 알려야 하는 것 — 오류(빨강)도 성공(초록)도 아니다 */
+.status.warn { color: #b45309; }
+
+button {
+ background: var(--panel);
+ color: var(--text);
+ border: 1px solid var(--line);
+ border-radius: 8px;
+ padding: 7px 14px;
+ cursor: pointer;
+ font-size: 13px;
+ box-shadow: 0 1px 2px rgba(16, 24, 40, 0.04);
+ /* 좁은 카드에서 "빼기" 같은 한글 라벨이 글자 단위로 부러지지 않게 */
+ white-space: nowrap;
+ flex: none;
+}
+button:hover { background: var(--panel-2); border-color: #d3d8e0; }
+button.ghost { background: transparent; padding: 3px 8px; font-size: 12px; box-shadow: none; }
+button.ghost:hover { background: var(--panel-2); }
+/* flip 버튼은 도구형(누를 때마다 반전) — 활성 강조 폐기 (maintainer 2026-07-19, 구 maintainer 2026-05-28 토글 강조 제거) */
+
+/* 공통 커스텀 툴팁 (data-tip). 네이티브 title 대체 — 위임형 단일 팝오버. */
+#sg-tip {
+ position: fixed;
+ z-index: 4000;
+ max-width: 360px;
+ padding: 6px 9px;
+ font-size: 11.5px;
+ line-height: 1.45;
+ color: var(--text);
+ background: var(--panel, #fff);
+ border: 1px solid var(--line);
+ border-radius: 7px;
+ box-shadow: 0 6px 22px rgba(15, 23, 42, 0.16);
+ pointer-events: none; /* 기본 툴팁은 통과 (호버 방해 없음) */
+ opacity: 0;
+ visibility: hidden;
+ word-break: break-word;
+ white-space: pre-line;
+}
+#sg-tip.open { opacity: 1; visibility: visible; }
+/* 복사 가능 툴팁: 마우스를 팝오버 안으로 옮겨 텍스트를 드래그·복사 (에이전트 협업) */
+#sg-tip.copyable { pointer-events: auto; }
+#sg-tip.copyable .sg-tip-text { user-select: text; cursor: text; font-family: var(--mono, ui-monospace, SFMono-Regular, Menlo, monospace); font-size: 11px; }
+
+/* 좌측 파일트리 사이드바 + 본문 2단 레이아웃 (쿠마피커 도크 스타일) */
+#layout { display: flex; align-items: flex-start; min-width: 0; }
+#sidebar {
+ position: sticky;
+ top: var(--topbar-h, 49px); /* 실측값은 boot 가 --topbar-h 로 주입 */
+ flex: 0 0 320px;
+ width: 320px;
+ /* 내용 길이와 무관하게 좌측을 전체 높이로 가른다 (쫙 갈라진 스플릿) */
+ height: calc(100vh - var(--topbar-h, 49px));
+ overflow-y: auto;
+ border-right: 1px solid var(--line);
+ background: var(--panel);
+ padding: 12px 10px 24px 12px;
+}
+#sidebar:empty { display: none; }
+main { flex: 1; min-width: 0; padding: 18px; display: flex; flex-direction: column; gap: 26px; }
+
+/* 사이드바 접기/펴기 — 폭·패딩·투명도 트랜지션, 토글 탭은 경계선에 붙는다 */
+#sidebar { transition: flex-basis 0.28s ease, width 0.28s ease, padding 0.28s ease, opacity 0.2s ease; }
+body.sidebar-collapsed #sidebar {
+ flex-basis: 0;
+ width: 0;
+ padding-left: 0;
+ padding-right: 0;
+ opacity: 0;
+ overflow: hidden;
+ border-right: none;
+}
+#sidebar-toggle {
+ position: sticky;
+ top: calc(var(--topbar-h, 49px) + 12px);
+ z-index: 5;
+ flex: none;
+ align-self: flex-start;
+ width: 17px;
+ height: 46px;
+ margin-left: -1px;
+ padding: 0;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ border: 1px solid var(--line);
+ border-left: none;
+ border-radius: 0 8px 8px 0;
+ background: var(--panel);
+ box-shadow: 1px 1px 4px rgba(0, 0, 0, 0.05);
+ cursor: pointer;
+}
+#sidebar-toggle svg { transition: transform 0.28s ease; color: var(--muted); }
+body.sidebar-collapsed #sidebar-toggle svg { transform: rotate(180deg); }
+#sidebar-toggle:hover svg { color: var(--accent, #0ea5e9); }
+
+.state {
+ background: var(--panel);
+ border: 1px solid var(--line);
+ border-radius: 10px;
+ padding: 14px 16px 18px;
+ /* 클릭 스크롤 도착 시 sticky 상단바가 타이틀을 가리지 않게 */
+ scroll-margin-top: calc(var(--topbar-h, 49px) + 14px);
+}
+.state-head {
+ display: flex;
+ align-items: baseline;
+ gap: 12px;
+ margin-bottom: 12px;
+}
+.state-head .name { font-size: 16px; font-weight: 600; }
+.state-head .meta { color: var(--muted); font-size: 12px; }
+.state-head .action { color: var(--muted); font-size: 12px; font-style: italic; }
+.state-warn { color: var(--danger); font-size: 12px; }
+/* 여백 침범 정보 알림 — 경고가 아니라 순한 안내 톤 (리롤 대상 아님) */
+.state-note { color: var(--muted); font-size: 12px; border: 1px solid var(--line); border-radius: 5px; padding: 1px 7px; }
+/* 방향 앵커 배지 — 이 줄이 해당 방향의 identity 원천임을 표시 */
+.anchor-badge { color: var(--accent, #0ea5e9); font-size: 12px; font-weight: 600; border: 1px solid var(--accent-dim, rgba(14,165,233,0.35)); border-radius: 5px; padding: 1px 7px; white-space: nowrap; flex: none; }
+/* 방향 그룹 구분 헤더 (directions 계약 런) */
+.dir-head { font-size: 13px; font-weight: 700; letter-spacing: 0.02em; color: var(--muted); margin: 6px 2px -16px; text-transform: uppercase; }
+.dir-head.dir-mirror { font-weight: 500; font-style: italic; margin-bottom: -14px; }
+
+/* 생성 구조 트리 — base → idle 행 → 앵커 → rows 파이프라인 개요 */
+.pipeline-tree .tree { padding: 4px 2px 2px; }
+.pipeline-tree .tree ul { list-style: none; margin: 2px 0 0; padding-left: 26px; }
+.pipeline-tree .tree > ul { margin-left: 13px; }
+.pipeline-tree .tree li { position: relative; padding: 5px 0 3px 14px; }
+/* 커넥터 기하:
+ - 트렁크(li::before) = 계속 아래로 내려가는 직선. 마지막 자식은 트렁크 없음.
+ - 가지(li::after) = 트렁크에서 노드로 꺾여 들어가는 └ 모양, 모서리는 라운드.
+ 모든 가지가 부드러운 곡선으로 노드에 붙고, 마지막 가지는 곡선만 남아 끝난다. */
+.pipeline-tree .tree li::before {
+ content: "";
+ position: absolute;
+ left: -13px;
+ top: 0;
+ bottom: 0;
+ width: 1px;
+ background: var(--line);
+}
+.pipeline-tree .tree li:last-child::before { display: none; }
+.pipeline-tree .tree li::after {
+ content: "";
+ position: absolute;
+ left: -13px;
+ top: 0;
+ width: 27px;
+ height: 19px;
+ border-left: 1px solid var(--line);
+ border-bottom: 1px solid var(--line);
+ border-bottom-left-radius: 9px;
+ pointer-events: none;
+}
+.tree-node {
+ position: relative;
+ display: inline-flex;
+ align-items: center;
+ gap: 7px;
+ padding: 3px 9px;
+ border: 1px solid var(--line);
+ border-radius: 7px;
+ background: var(--panel-2);
+ font-size: 12.5px;
+ vertical-align: middle;
+}
+.tree-node img {
+ height: 30px;
+ width: 30px;
+ object-fit: contain;
+ background: repeating-conic-gradient(#ececec 0% 25%, #f8f8f8 0% 50%) 0 0 / 8px 8px;
+ border-radius: 4px;
+}
+.tree-node .thumb-missing { height: 30px; width: 30px; border: 1px dashed var(--line); border-radius: 4px; }
+.tree-node.pending { border-style: dashed; color: var(--muted); }
+.tree-node .tn-label { font-weight: 600; }
+.tree-node .tn-note { color: var(--muted); font-size: 11.5px; }
+.tree-node.clickable { cursor: pointer; }
+.tree-node.clickable:hover { border-color: var(--accent, #0ea5e9); }
+.tree-node.anchor { border-color: var(--accent-dim, rgba(14,165,233,0.4)); }
+.tree-node.anchor .tn-label { color: var(--accent, #0ea5e9); }
+.tree-node.mirror { border-style: dashed; font-style: italic; color: var(--muted); }
+.tree-node.tree-root { background: var(--panel); font-size: 13px; }
+/* 폴더 노드 — 파일트리 뼈대. 박스 없이 아이콘+경로 라벨만. 클릭 = 접기/펴기 */
+.tree-node.folder { border: none; background: transparent; padding: 2px 2px; }
+.tree-node.folder svg { color: var(--muted); flex: none; }
+.tree-node.folder .caret { transition: transform 0.2s ease; transform: rotate(90deg); }
+.folder-collapsed > .tree-node.folder .caret { transform: rotate(0deg); }
+.folder-collapsed > ul { display: none; }
+.tree-node.folder.clickable:hover { border: none; background: var(--panel-2); border-radius: 6px; }
+/* 파이프라인 / 파일 — 사이드바 상위 블록 */
+.tree-block { margin-bottom: 10px; }
+.tree-block > .tree-node.folder { font-weight: 700; }
+.tree-block > .tree-node.folder .tn-label { font-family: inherit; font-size: 12.5px; letter-spacing: 0.02em; text-transform: uppercase; }
+.tree-block > ul { margin-top: 2px; }
+
+/* 파이프라인 블록 — 트렁크에 대시가 아래로 흐른다 (파이프에 물 흐르듯, 느긋하게).
+ 가지 곡선은 액센트 정적, 가지 끝(노드 왼쪽 모서리)에 화살촉이 정확히 붙는다. */
+.tree-block.pipeline li::before {
+ background:
+ repeating-linear-gradient(to bottom,
+ rgba(37, 99, 235, 0) 0 11px,
+ rgba(37, 99, 235, 0.75) 11px 16px),
+ linear-gradient(rgba(37, 99, 235, 0.28), rgba(37, 99, 235, 0.28));
+ background-size: 1px 27px, 1px 100%;
+ background-repeat: repeat-y, no-repeat;
+ animation: pipe-flow 2.3s linear infinite;
+}
+@keyframes pipe-flow {
+ to { background-position: 0 27px, 0 0; }
+}
+/* 파이프라인 가지는 CSS 곡선 대신 SVG(.branch)가 그린다 — 대시가 곡선을 타고 흐름 */
+.tree-block.pipeline li::after { display: none; }
+.tree-block.pipeline svg.branch {
+ position: absolute;
+ left: -7px;
+ top: 0;
+ pointer-events: none;
+ overflow: visible;
+}
+.tree-block.pipeline svg.branch path { fill: none; stroke-linecap: round; }
+.tree-block.pipeline svg.branch .rail { stroke: rgba(37, 99, 235, 0.28); stroke-width: 1; }
+.tree-block.pipeline svg.branch .dash {
+ stroke: rgba(37, 99, 235, 0.75);
+ stroke-width: 1;
+ stroke-dasharray: 5 12;
+ animation: branch-flow 1.45s linear infinite;
+}
+@keyframes branch-flow {
+ to { stroke-dashoffset: -17; }
+}
+/* 화살촉: 가지 밑변(y=19px 라인) 연장선상에서 노드 모서리에 밀착 (li 좌표 기준) */
+.tree-block.pipeline li > .tree-node:first-of-type::before {
+ content: "";
+ position: absolute;
+ left: -5px;
+ top: 10px;
+ border-top: 3.5px solid transparent;
+ border-bottom: 3.5px solid transparent;
+ border-left: 5px solid rgba(37, 99, 235, 0.6);
+}
+@media (prefers-reduced-motion: reduce) {
+ .tree-block.pipeline li::before { animation: none; }
+ .tree-block.pipeline svg.branch .dash { animation: none; }
+}
+
+/* 트리에서 이동해 온 대상 패널 하이라이트 — 도착 후 따닥! 두 번 깜빡이고 즉시 끝 */
+@keyframes target-flash {
+ 0% { box-shadow: 0 0 0 2px rgba(37, 99, 235, 0); }
+ 25% { box-shadow: 0 0 0 2px rgba(37, 99, 235, 0.9); }
+ 50% { box-shadow: 0 0 0 2px rgba(37, 99, 235, 0.5); }
+ 75% { box-shadow: 0 0 0 2px rgba(37, 99, 235, 1); }
+ 100% { box-shadow: 0 0 0 2px rgba(37, 99, 235, 0); }
+}
+.state.flash-target { animation: target-flash 0.22s ease 1; }
+.tree-node.folder .tn-label { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12.5px; }
+/* 런 경로: 한 줄 + 앞쪽 말줄임 — 뒤(폴더명)가 중요하므로 끝을 보여주고 앞을 …로.
+ direction:rtl 트릭; 전체 경로는 hover 툴팁(title). */
+.pipeline-tree .tree-path {
+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
+ font-size: 11.5px;
+ display: block;
+ max-width: 100%;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ direction: rtl;
+ text-align: left;
+ cursor: default;
+}
+
+/* 사이드바 안에서는 카드 껍데기를 벗고 세로 밀도 위주로 */
+#sidebar .pipeline-tree { background: transparent; border: none; border-radius: 0; padding: 2px 2px 8px; }
+#sidebar .pipeline-tree .state-head { flex-direction: column; align-items: flex-start; gap: 3px; margin-bottom: 8px; }
+#sidebar .pipeline-tree .state-head .name { font-size: 13px; }
+#sidebar .pipeline-tree .tree ul { padding-left: 14px; }
+#sidebar .pipeline-tree .tree li { padding-left: 8px; }
+#sidebar .pipeline-tree .tree li::before { left: -7px; }
+#sidebar .pipeline-tree .tree li::after { left: -7px; width: 15px; border-bottom-left-radius: 7px; }
+#sidebar .tree-rows { flex-direction: column; gap: 2px; }
+#sidebar .tree-node { font-size: 12px; padding: 2px 7px; max-width: 100%; }
+#sidebar .tree-node .tn-label { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+#sidebar .tree-node .tn-note { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+#sidebar .tree-node img { height: 22px; width: 22px; }
+#sidebar .tree-node.raw-only img { width: 40px; }
+#sidebar .tree-node.tree-root img { height: 28px; width: 28px; }
+.tree-rows { display: flex; flex-wrap: wrap; gap: 0 4px; }
+.tree-rows li { padding-right: 0; }
+/* raw 는 생성됐고 추출 전 — 중간 진행 상태 (raw 스트립 썸네일) */
+.tree-node.raw-only { border-style: dotted; }
+.tree-node.raw-only img { width: 52px; object-fit: cover; }
+
+/* 런 세대 변경 배너 — 폴링이 프레임 재생성을 감지하면 표시 */
+#reload-banner {
+ position: fixed;
+ left: 50%;
+ bottom: 26px;
+ transform: translateX(-50%);
+ z-index: 3000;
+ background: var(--accent, #0ea5e9);
+ color: #fff;
+ border: none;
+ border-radius: 999px;
+ padding: 9px 18px;
+ font-size: 13px;
+ font-weight: 600;
+ box-shadow: 0 8px 26px rgba(0, 0, 0, 0.25);
+ cursor: pointer;
+}
+
+/* 큐레이션 무효화 알림 — 프레임 재생성으로 드롭된 행 + 백업 파일 안내 (조용한 소실 금지) */
+#curation-dropped-note {
+ position: sticky;
+ top: 0;
+ z-index: 2500;
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 9px 14px;
+ font-size: 12.5px;
+ background: rgba(234, 179, 8, 0.12);
+ border-bottom: 1px solid rgba(128, 128, 128, 0.25);
+}
+#curation-dropped-note button { margin-left: auto; }
+
+/* 복제 인스턴스 배지 — 원본 프레임 번호를 항상 노출 */
+.clone-badge {
+ display: inline-flex;
+ align-items: center;
+ gap: 3px;
+ font-size: 10.5px;
+ opacity: 0.85;
+ border: 1px solid rgba(128, 128, 128, 0.35);
+ border-radius: 5px;
+ padding: 0 5px;
+}
+
+.state-body { display: flex; gap: 18px; align-items: flex-start; min-width: 0; }
+.frames {
+ display: flex;
+ gap: 12px;
+ overflow-x: auto;
+ padding-bottom: 8px;
+ flex: 1;
+ /* (maintainer 2026-05-28) flex child 가 content (3000px+) 만큼 늘어나면 overflow-x:auto
+ 가 발화 안 함 — 가로 18 frame 다 못 봄. min-width:0 으로 flex 의 default
+ min-content 동작을 끄고 부모 폭에 fit + 가로 scrollbar 가 발화하도록. */
+ min-width: 0;
+}
+
+.card {
+ flex: 0 0 auto;
+ width: 168px;
+ background: var(--panel-2);
+ border: 2px solid var(--line);
+ border-radius: 8px;
+ padding: 8px;
+ user-select: none;
+}
+.card.selected { border-color: var(--accent); }
+.card.missing { border-style: dashed; }
+/* 방향 앵커 프레임 = 이 방향의 identity 한 장 (생성에 붙는 그 프레임). 선택
+ 테두리와 구분되게 은은한 틴트 + 얇은 균일 테두리로만 표시한다 (액센트 바 금지). */
+.card.is-anchor { border-color: #b45309; background: rgba(180, 83, 9, 0.05); }
+.card-top .anchor-frame-badge {
+ font-size: 9.5px;
+ font-weight: 700;
+ letter-spacing: 0.04em;
+ color: #b45309;
+ border: 1px solid rgba(180, 83, 9, 0.35);
+ border-radius: 4px;
+ padding: 0 4px;
+ white-space: nowrap;
+}
+.card-controls .anchor-btn.on { color: #b45309; background: rgba(180, 83, 9, 0.1); }
+.card-top .anchor-frame-badge.pinned { background: rgba(180, 83, 9, 0.12); }
+/* 증명되지 않는 핀 = 경고색 (지금 이대로 생성하면 fail-loud 한다) */
+.card-top .anchor-frame-badge.stale { color: #b91c1c; border-color: rgba(185, 28, 28, 0.4); background: rgba(185, 28, 28, 0.08); }
+.card.is-anchor:has(.anchor-frame-badge.stale) { border-color: #b91c1c; background: rgba(185, 28, 28, 0.04); }
+.card-controls .anchor-btn.stale { color: #b91c1c; background: rgba(185, 28, 28, 0.1); }
+
+/* two rows per state: sequence (top) + candidate pool (bottom) */
+.zones { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 10px; }
+.zone { border-radius: 8px; padding: 6px 8px 4px; }
+.zone-seq { background: rgba(37, 99, 235, 0.04); border: 1px solid var(--accent-dim); }
+.zone-pool { background: rgba(17, 24, 39, 0.02); border: 1px dashed var(--line); }
+.zone-label {
+ font-size: 11px;
+ color: var(--muted);
+ margin: 2px 2px 6px;
+ letter-spacing: 0.03em;
+}
+.zone .frames { flex: none; min-height: 64px; } /* droppable even when empty */
+
+.card-top {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ gap: 6px;
+ margin-bottom: 6px;
+ font-size: 12px;
+ color: var(--muted);
+ /* 헤더(타이틀 줄) 전체가 드래그 핸들 — 타이틀을 잡고 임계값을 넘으면 순서변경/
+ 시퀀스↔풀 이동. 그냥 클릭은 아무 것도 안 한다 (maintainer 2026-07-15). 우측 아이콘
+ 버튼은 pointerdown 전파를 끊어 드래그를 시작하지 않는다. */
+ cursor: grab;
+ padding: 1px 1px 1px 2px;
+ touch-action: none; /* claim the pointer so the scroll row doesn't steal the drag */
+}
+.card-top:active { cursor: grabbing; }
+.card.dragging .card-top { cursor: grabbing; }
+.card-top .ct-left {
+ display: flex;
+ align-items: center; /* 좌측 복제 버튼(svg)과 타이틀 수직 정렬 */
+ gap: 6px;
+ min-width: 0;
+ flex: 1;
+}
+.card-top .idx {
+ color: var(--text);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ min-width: 0;
+} /* long imported labels truncate instead of breaking the card-top layout */
+/* 실콘텐츠 픽셀 크기 — 타이틀 옆 인라인 (한 줄 정보). 사이즈 통일 검수용. */
+.card-top .psize {
+ font-size: 10.5px;
+ color: var(--muted);
+ font-variant-numeric: tabular-nums;
+ white-space: nowrap;
+ flex: none;
+}
+.card.dragging {
+ border-color: var(--accent);
+ box-shadow: 0 12px 30px rgba(15, 23, 42, 0.18);
+ opacity: 0.97;
+ cursor: grabbing;
+ transition: none; /* fixed-positioned card must track the cursor 1:1 */
+}
+/* the gap the lifted card will drop into */
+.card-placeholder {
+ flex: 0 0 auto;
+ border-radius: 8px;
+ border: 2px dashed var(--accent-dim);
+ background: rgba(37, 99, 235, 0.05);
+}
+
+.stage {
+ position: relative;
+ width: 152px;
+ aspect-ratio: var(--cell-aspect, 1);
+ border-radius: 5px;
+ overflow: hidden;
+ /* 스프라이트 드래그 = 이동(move) 커서 — 손(grab)은 뷰 팬 전용 어휘 (maintainer 2026-07-20:
+ 캐릭터 이동이 손 모양이라 직관적이지 않다). 팬 상태(pan-space/pan-tool)가 grab 으로 덮는다. */
+ cursor: move;
+ background-color: var(--checker-a);
+ background-image:
+ linear-gradient(45deg, var(--checker-b) 25%, transparent 25%),
+ linear-gradient(-45deg, var(--checker-b) 25%, transparent 25%),
+ linear-gradient(45deg, transparent 75%, var(--checker-b) 75%),
+ linear-gradient(-45deg, transparent 75%, var(--checker-b) 75%);
+ background-size: 16px 16px;
+ background-position: 0 0, 0 8px, 8px -8px, -8px 0;
+}
+.stage:active { cursor: grabbing; }
+.stage img {
+ position: absolute;
+ inset: 0;
+ width: 100%;
+ height: 100%;
+ object-fit: contain;
+ transform-origin: center;
+ pointer-events: none;
+ z-index: 1;
+}
+/* 원본 픽셀보다 확대 표시될 때만 붙는 클래스 — 픽셀아트 계단을 그대로 보여준다.
+ 부여 주체는 display.js `applyPixelScaling` 하나뿐이다 (표시 기하로 판정·재평가). */
+.px-upscale { image-rendering: pixelated; }
+/* 변형 편집 중 실시간 격자 스냅 프리뷰 캔버스 (픽셀 언페이크 줄 전용, applyCardTransform 소유) */
+.stage .snap-canvas {
+ position: absolute;
+ inset: 0;
+ width: 100%;
+ height: 100%;
+ z-index: 1;
+ display: none;
+ pointer-events: none;
+ /* nearest 여부는 여기서 정하지 않는다 — 이 캔버스도 버퍼≠표시 해상도라
+ display.js `applyPixelScaling` 이 판정하고 `.px-upscale` 로만 부여된다.
+ (무조건 규칙이 남아 소스 해상도 버퍼를 축소 표시에서 데시메이션했다 — validator R1) */
+}
+.grid-overlay {
+ position: absolute;
+ inset: 0;
+ width: 100%;
+ height: 100%;
+ z-index: 0;
+ display: none;
+ pointer-events: none;
+}
+body.show-grid .grid-overlay { display: block; }
+body.show-grid .stage { background-image: none; background-color: #eef0f3; }
+.rotate-handle {
+ position: absolute;
+ top: 4px;
+ left: 50%;
+ width: 16px;
+ height: 16px;
+ margin-left: -8px;
+ border-radius: 50%;
+ background: var(--accent);
+ border: 2px solid #fff;
+ cursor: grab;
+ opacity: 0;
+ transition: opacity 0.12s;
+ z-index: 2;
+}
+.stage:hover .rotate-handle { opacity: 0.9; }
+.shear-handle {
+ position: absolute;
+ left: 4px;
+ bottom: 4px;
+ width: 14px;
+ height: 14px;
+ border-radius: 3px;
+ background: #ffb450;
+ border: 2px solid #fff;
+ cursor: nwse-resize;
+ opacity: 0;
+ transition: opacity 0.12s;
+ z-index: 2;
+}
+.stage:hover .shear-handle { opacity: 0.9; }
+.missing-label {
+ position: absolute;
+ inset: 0;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ color: var(--danger);
+ font-size: 12px;
+}
+
+/* 푸터 2층: (1) 정보 줄 — 크기·변형값 (봐야 하는 정보) / (2) 버튼 줄 */
+.card-info {
+ display: flex;
+ align-items: baseline;
+ gap: 8px;
+ margin-top: 6px;
+ min-height: 14px;
+}
+.card-info .psize { font-size: 10.5px; color: var(--text); font-variant-numeric: tabular-nums; white-space: nowrap; flex: none; }
+.card-info .tvals { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: right; }
+/* 버튼이 카드 폭(168px)을 넘으면 잘리지 말고 2줄로 접힌다 — 로케일마다 라벨 폭이
+ 달라(빼기 / remove) 한 줄 고정은 언제든 다시 넘친다 (maintainer 2026-07-26 실측 오버플로). */
+.card-controls {
+ display: flex;
+ align-items: center;
+ flex-wrap: wrap;
+ gap: 4px;
+ margin-top: 4px;
+}
+.tvals { font-size: 10px; color: var(--muted); font-variant-numeric: tabular-nums; }
+
+.preview {
+ flex: 0 0 auto;
+ width: 180px;
+ text-align: center;
+}
+.preview h4 { margin: 0 0 6px; font-size: 12px; color: var(--muted); font-weight: 500; }
+.preview canvas {
+ width: 160px;
+ border-radius: 6px;
+ background-color: var(--checker-a);
+ background-image:
+ linear-gradient(45deg, var(--checker-b) 25%, transparent 25%),
+ linear-gradient(-45deg, var(--checker-b) 25%, transparent 25%),
+ linear-gradient(45deg, transparent 75%, var(--checker-b) 75%),
+ linear-gradient(-45deg, transparent 75%, var(--checker-b) 75%);
+ background-size: 16px 16px;
+ background-position: 0 0, 0 8px, 8px -8px, -8px 0;
+}
+.preview .count { font-size: 11px; color: var(--muted); margin-top: 4px; }
+.pv-controls {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ gap: 4px;
+ margin-top: 8px;
+}
+.pv-controls button.ghost {
+ padding: 3px 8px;
+ font-size: 13px;
+ line-height: 1;
+}
+.pv-controls .pv-play { min-width: 32px; }
+.pv-controls button:disabled { opacity: 0.4; cursor: default; }
+.pv-controls button:disabled:hover { background: transparent; }
+.pv-speed {
+ background: var(--panel-2);
+ color: var(--text);
+ border: 1px solid var(--line);
+ border-radius: 5px;
+ padding: 3px 4px;
+ font-size: 11px;
+ cursor: pointer;
+}
+.pv-pos {
+ font-size: 11px;
+ color: var(--muted);
+ margin-top: 4px;
+ font-variant-numeric: tabular-nums;
+}
+
+.fatal {
+ margin: 40px auto;
+ max-width: 560px;
+ background: var(--panel);
+ border: 1px solid var(--danger);
+ border-radius: 8px;
+ padding: 18px;
+ color: var(--danger);
+ white-space: pre-wrap;
+}
+
+/* pixel unfake apply checkbox (top-right) + view toggle */
+.unfake-apply {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ font-size: 12px;
+ /* --fg 는 어디에도 정의돼 있지 않아 폴백이 항상 이겼다 — 라이트 배경 위 #ddd 는
+ 반투명처럼 보임 (maintainer 지적 2026-07-17). 버튼(.gif-btn)과 같은 잉크색으로 통일. */
+ color: var(--fg-dim, #64748b);
+ border: 1px solid var(--line, #3a3a3a);
+ border-radius: 6px;
+ padding: 4px 10px;
+ cursor: pointer;
+ user-select: none;
+ white-space: nowrap;
+}
+.unfake-apply input {
+ margin: 0;
+ cursor: pointer;
+}
+
+/* top base reference row */
+.base-row .base-stage {
+ padding: 12px;
+ display: flex;
+ justify-content: flex-start;
+}
+.base-row .base-stage img {
+ max-width: 100%;
+ max-height: 240px;
+ border: 1px solid var(--line, #3a3a3a);
+ border-radius: 8px;
+ background:
+ repeating-conic-gradient(#e8e8e8 0% 25%, #f7f7f7 0% 50%) 0 0 / 16px 16px;
+}
+
+/* nearest 샘플링 여부는 CSS 가 무조건 정하지 않는다 — 표시 기하로 판정하는
+ display.js `applyPixelScaling` 이 단일 소유자이고 `.px-upscale` 로만 부여된다.
+ (여기 있던 무조건 `.stage img` 규칙이 그 판정을 덮어써 고해상 원본 트윈을
+ 축소 표시에서 nearest 데시메이션시켰다 — maintainer 2026-07-24) */
+
+/* 픽셀 그리드 오버레이 (줄별 체크박스 / 상단 전체 토글) — display 는 sizePxGrids 가 소유 */
+.stage .pxgrid {
+ position: absolute;
+ inset: 0;
+ z-index: 2; /* snap-canvas(z1) 위 — 픽셀 언페이크 뷰에서도 격자가 보여야 한다 */
+ pointer-events: none;
+ display: none;
+ background-image:
+ linear-gradient(to right, rgba(220, 40, 40, 0.28) 1px, transparent 1px),
+ linear-gradient(to bottom, rgba(40, 110, 220, 0.28) 1px, transparent 1px);
+}
+
+/* 상태별 생성 ref 칩 (어떤 재료로 이 줄을 생성했는가) + 우측 줄별 표시/굽기 컨트롤 */
+.state-refs { display: flex; align-items: center; gap: 8px; margin: 2px 0 8px; flex-wrap: wrap; }
+.state-refs .refs-label { font-size: 12px; opacity: 0.6; }
+.state-refs .row-controls { margin-left: auto; display: inline-flex; gap: 8px;
+ /* 컨트롤이 많아도 카드 밖으로 안 나가게 — 오른쪽 정렬 유지한 채 줄바꿈 (maintainer 2026-07-18) */
+ flex-wrap: wrap; justify-content: flex-end; row-gap: 4px; min-width: 0; }
+.row-toggle { padding: 3px 8px; background: var(--panel, transparent); }
+
+/* 하단 힌트바 — 힌트 span 이 구분자 없이 붙지 않게 (회귀 2026-07-14 픽) */
+.hintbar {
+ display: flex;
+ flex-wrap: wrap;
+ justify-content: center;
+ gap: 4px 18px;
+ padding: 10px 16px 14px;
+ font-size: 12px;
+ color: var(--muted);
+}
+.hintbar span { position: relative; }
+.hintbar span + span::before {
+ content: "·";
+ position: absolute;
+ left: -11px;
+ color: var(--line);
+}
+
+/* 검출된 입력 격자 오버레이 (원본 표시 줄 전용) — 추출이 실제로 자른 절단선, 초록 */
+.stage .ingrid {
+ position: absolute;
+ inset: 0;
+ z-index: 2;
+ width: 100%;
+ height: 100%;
+ pointer-events: none;
+ display: none;
+ z-index: 2;
+}
+
+/* 보관함 — 후보 풀에서도 제외한 프레임. 접힌 칩 + 쇽 팝오버 + 드래그 복구 */
+.archive-wrap { position: relative; margin-top: 6px; display: flex; }
+.archive-wrap.empty { opacity: 0.45; }
+.archive-chip {
+ display: inline-flex;
+ align-items: center;
+ gap: 5px;
+ font-size: 11.5px;
+ color: var(--muted);
+ border: 1px dashed var(--line);
+ border-radius: 6px;
+ padding: 2px 9px;
+}
+.archive-chip:hover { border-color: var(--accent, #0ea5e9); color: var(--accent, #0ea5e9); }
+.archive-pop {
+ position: absolute;
+ left: 0;
+ bottom: calc(100% + 6px);
+ z-index: 50;
+ min-width: 180px;
+ max-width: 420px;
+ background: var(--panel);
+ border: 1px solid var(--line);
+ border-radius: 9px;
+ padding: 8px 10px;
+ box-shadow: 0 10px 32px rgba(0, 0, 0, 0.14);
+ transform: translateY(6px) scale(0.92);
+ transform-origin: left bottom;
+ opacity: 0;
+ pointer-events: none;
+ transition: transform 0.16s cubic-bezier(0.2, 1.4, 0.4, 1), opacity 0.14s ease;
+}
+.archive-pop.open { transform: none; opacity: 1; pointer-events: auto; }
+.archive-pop .ap-hint { font-size: 11px; color: var(--muted); margin-bottom: 6px; }
+.ap-cards { display: flex; flex-wrap: wrap; gap: 6px; }
+.ap-card {
+ display: inline-flex;
+ align-items: center;
+ gap: 5px;
+ border: 1px solid var(--line);
+ border-radius: 6px;
+ padding: 2px 7px;
+ font-size: 11.5px;
+ background: var(--panel-2);
+ cursor: grab;
+ user-select: none;
+}
+.ap-card img { height: 26px; width: 26px; object-fit: contain; }
+.ap-ghost { position: fixed; z-index: 3000; pointer-events: none; opacity: 0.85; }
+/* 확대 스크러버 — 스테이지 내부 우하단, 호버 시 표시. [−][돋보기⁺ 드래그][+] */
+.stage .scale-scrub {
+ position: absolute;
+ right: 4px;
+ bottom: 4px;
+ z-index: 3;
+ display: inline-flex;
+ align-items: center;
+ gap: 0;
+ color: var(--muted);
+ background: rgba(255, 255, 255, 0.94);
+ border: 1px solid var(--line);
+ border-radius: 7px;
+ padding: 1px 3px;
+ box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
+ opacity: 0;
+ transition: opacity 0.15s ease;
+}
+.stage:hover .scale-scrub { opacity: 1; }
+.scale-scrub .ss-step { padding: 2px 3px; }
+.scale-scrub .ss-grab { cursor: ew-resize; padding: 2px 3px; display: inline-flex; touch-action: none; }
+.scale-scrub .ss-grab:hover, .scale-scrub .ss-step:hover { color: var(--accent, #0ea5e9); }
+
+/* 버튼 줄: [반전][초기화][앵커] ... [넣기/빼기][보관] (오른쪽 그룹).
+ 아이콘 전용 버튼은 헤더 우측(ct-right)과 같은 컴팩트 규격으로 통일한다 —
+ button.ghost 기본 padding(3px 8px)을 그대로 쓰면 글자 없는 버튼이 30px 을 먹는다. */
+.card-controls .flip-btn, .card-controls .reset-btn { flex: none; }
+.card-controls .flip-btn,
+.card-controls .reset-btn,
+.card-controls .anchor-btn,
+.card-controls .arch-btn {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ padding: 3px;
+ border-radius: 5px;
+ color: var(--muted);
+ line-height: 0;
+}
+.card-controls .flip-btn:hover,
+.card-controls .reset-btn:hover {
+ color: var(--accent, #0ea5e9);
+ background: rgba(37, 99, 235, 0.08);
+}
+/* 넣기·빼기 + 보관을 한 묶음으로 오른쪽 정렬 (성격이 비슷한 멤버십 액션) */
+.card-controls .ctrl-group { margin-left: auto; display: inline-flex; align-items: center; gap: 3px; flex: none; }
+
+/* 헤더 우측 아이콘 버튼 (복제·확대) — 균일한 라인 아이콘 버튼 */
+.card-top .ct-right { display: inline-flex; align-items: center; gap: 2px; flex: none; }
+.card-top .ct-right .ghost {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ padding: 3px;
+ border-radius: 5px;
+ color: var(--muted);
+ line-height: 0;
+}
+.card-top .ct-right .ghost:hover { color: var(--accent, #0ea5e9); background: rgba(37, 99, 235, 0.08); }
+.card-top .zoom-btn { cursor: zoom-in; }
+
+/* 넣기/빼기 = 시퀀스⇄풀 토글 버튼. 색상 강조 없이 방향 아이콘(위/아래)+라벨로만 구분. */
+.sel-btn {
+ flex: none;
+ display: inline-flex;
+ align-items: center;
+ gap: 3px;
+ font-size: 11px;
+ padding: 2px 7px 2px 5px;
+ border-radius: 6px;
+ border: 1px solid var(--line);
+ background: var(--panel);
+ color: var(--text);
+ cursor: pointer;
+ white-space: nowrap;
+ line-height: 1.4;
+}
+.sel-btn svg { display: block; }
+.sel-btn:hover { border-color: var(--accent, #0ea5e9); color: var(--accent, #0ea5e9); }
+/* 보관 버튼 규격은 위 아이콘 버튼 공통 규칙이 소유한다 (여기 재선언 금지) */
+.card-controls .arch-btn:hover { color: var(--accent, #0ea5e9); background: rgba(37, 99, 235, 0.08); }
+
+/* 픽셀 편집 툴바 (확대 모달) */
+.edit-toolbar { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }
+.edit-toolbar .ghost { display: inline-flex; align-items: center; gap: 4px; border: 1px solid var(--line); border-radius: 6px; }
+.edit-toolbar .ghost.active { background: var(--accent, #0ea5e9); color: #fff; border-color: transparent; }
+.et-swatches { display: inline-flex; gap: 3px; }
+.swatch { width: 18px; height: 18px; padding: 0; border: 1px solid rgba(0, 0, 0, 0.18); border-radius: 4px; cursor: pointer; box-shadow: none; }
+.et-color { width: 26px; height: 22px; padding: 0 1px; border: 1px solid var(--line); border-radius: 5px; background: var(--panel); cursor: pointer; }
+.et-note { font-size: 11px; }
+.stage.pixel-editing { cursor: crosshair; }
+/* 스포이드 모드 = 색 집기 커서 (copy) 로 구분 */
+.stage.pixel-editing.picking { cursor: copy; }
+.stage.pixel-editing .rotate-handle, .stage.pixel-editing .shear-handle, .stage.pixel-editing .scale-scrub { display: none; }
+
+/* 보관함 풀 모달 — 일반 카드 크기 그리드 + 복구 버튼 */
+#archive-modal { position: fixed; inset: 0; z-index: 2000; display: flex; align-items: center; justify-content: center; padding: 24px; }
+#archive-modal .zoom-backdrop { position: absolute; inset: 0; background: rgba(15, 18, 24, 0.5); }
+/* 카드가 많아도 화면 밖으로 넘치지 않게 — 모달 자체를 뷰포트에 가두고 내부 스크롤.
+ #archive-modal 스코프로 .zoom-card.card 기본값을 확실히 덮는다 (특정성). */
+#archive-modal .arch-modal-card {
+ position: relative;
+ z-index: 1;
+ width: auto;
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+ max-width: min(92vw, 900px);
+ max-height: 86vh;
+ overflow: hidden;
+ padding: 14px 16px 12px;
+ background: var(--panel, #fff);
+ box-shadow: 0 18px 60px rgba(0, 0, 0, 0.35);
+ border-radius: 12px;
+}
+#archive-modal .arch-modal-card .zoom-head { flex: none; }
+.arch-grid { display: flex; flex-wrap: wrap; gap: 12px; overflow: auto; padding: 2px; align-content: flex-start; }
+.arch-card { width: 168px; } /* row 카드와 동일 규격 — 프레임 그리드 (maintainer 2026-07-18) */
+.arch-card .stage { cursor: default; }
+.arch-card .card-controls { justify-content: center; gap: 6px; }
+
+/* 확대 편집 모달 — 한 프레임 크게, 격자/픽셀 언페이크 토글하며 조정 */
+#zoom-modal { position: fixed; inset: 0; z-index: 2000; display: flex; align-items: center; justify-content: center; }
+#zoom-modal .zoom-backdrop { position: absolute; inset: 0; background: rgba(15, 18, 24, 0.5); }
+/* 3계층 계약 (maintainer 2026-07-20): 모달 = 최대 크기 고정, 그 안의 뷰포트가 화면
+ 배율·팬을 소유, 캐릭터(스테이지)는 뷰포트 안에서 자유 확대/이동. */
+.zoom-card.card {
+ position: relative;
+ z-index: 1;
+ width: 94vw;
+ height: 94vh;
+ overflow: hidden;
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+ padding: 14px 16px 12px;
+ background: var(--panel, #fff);
+ box-shadow: 0 18px 60px rgba(0, 0, 0, 0.35);
+ border-radius: 12px;
+}
+.zoom-head { display: flex; align-items: center; gap: 8px; }
+/* 타이틀 = 복붙 대상 (maintainer 2026-07-20: 프레임 이름을 블록 지정해 복사) — .card 의
+ user-select:none 상속을 풀어준다. 줌/비교/아카이브 모달 공통. */
+.zoom-head .zoom-title { font-weight: 600; font-size: 15px; margin-right: 6px; user-select: text; cursor: text; }
+.zoom-head .row-controls { margin-left: auto; display: inline-flex; gap: 8px; }
+/* flex 컨테이너(column)가 높이를 눌러 aspect-ratio 를 깨지 않게 — 확대는 뷰포트
+ 스크롤로 수용. (회귀 2026-07-14: flex-shrink 가 스테이지 높이만 줄여
+ 스프라이트/격자가 가로로 찌그러졌다.) */
+.zoom-card .stage { width: 480px; flex: 0 0 auto; }
+/* 뷰포트 계층: stage-row 가 남은 높이를 전부 차지, 그 안의 뷰포트가 스크롤 소유.
+ stage-pad 의 큰 사방 패딩 = 자유 팬 (어느 구석이든 화면 중앙으로 끌어올 수 있다). */
+.zoom-card .stage-row { flex: 1 1 auto; min-height: 0; }
+/* align-self:stretch — stage-row 는 align-items:flex-start (팔레트 도크 계약) 라
+ 명시로 늘려야 뷰포트가 높이 제약을 받아 스크롤/센터링이 산다 (회귀 2026-07-20:
+ 뷰포트가 콘텐츠 높이만큼 자라 세로 팬 불능 + 코너 위젯이 카드 밖으로 밀림). */
+.stage-viewwrap { position: relative; flex: 1 1 auto; align-self: stretch; min-width: 0; min-height: 0; display: flex; }
+.stage-viewport {
+ flex: 1 1 auto;
+ min-width: 0;
+ min-height: 0;
+ overflow: auto;
+ border: 1px solid var(--line, #e2e8f0);
+ border-radius: 10px;
+ background: var(--panel-2, #f8fafc);
+}
+.stage-pad { width: max-content; padding: 46vh 46vw; }
+.stage-viewport.pan-tool, body.pan-space .stage-viewport { cursor: grab; }
+/* 돋보기 위젯 — 화면 배율 전용 (스프라이트 크기 = scale-scrub, 별도 어휘) */
+.view-nav {
+ display: inline-flex;
+ align-items: center;
+ gap: 2px;
+ color: var(--muted);
+ background: rgba(255, 255, 255, 0.94);
+ border: 1px solid var(--line, #e2e8f0);
+ border-radius: 7px;
+ padding: 1px 4px;
+}
+.view-nav .vn-label { font-size: 11px; min-width: 38px; text-align: center; user-select: none; }
+.view-nav button { padding: 2px 4px; display: inline-flex; }
+.view-nav button:hover { color: var(--accent, #0ea5e9); }
+.view-nav.vn-corner {
+ position: absolute;
+ right: 12px;
+ bottom: 12px;
+ z-index: 5;
+ box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
+}
+.ref-chip { display: inline-flex; align-items: center; gap: 6px; text-decoration: none; color: inherit;
+ border: 1px solid rgba(128,128,128,0.3); border-radius: 6px; padding: 2px 8px 2px 2px; }
+.ref-chip:hover { border-color: rgba(128,128,128,0.6); }
+.ref-chip img { height: 40px; width: auto; border-radius: 4px; display: block; }
+.ref-chip span { font-size: 11px; opacity: 0.8; }
+
+/* 줄 단위 GIF 다운로드 버튼 — row-controls 안, 체크박스 토글과 같은 높이 */
+.gif-btn {
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ padding: 2px 8px;
+ font-size: 11px;
+ color: var(--fg-dim, #64748b);
+ background: transparent;
+ border: 1px solid var(--line, #e2e8f0);
+ border-radius: 6px;
+ cursor: pointer;
+}
+.gif-btn:hover { color: var(--fg, #0f172a); border-color: var(--fg-dim, #94a3b8); }
+.gif-btn:disabled { opacity: 0.5; cursor: default; }
+.gif-btn svg { display: block; }
+
+/* AI 중간 프레임(보간) 버튼의 파라미터 팝오버 */
+.gen-wrap { position: relative; display: inline-flex; }
+.gen-pop[hidden] { display: none !important; } /* display:flex 가 hidden 속성을 이기지 못하게 */
+.tween-picking .card { cursor: crosshair; }
+.tween-picking .card.selected { border-color: var(--line); } /* 픽 모드에선 기존 선택 파랑 억제 */
+.tween-picking .card.tween-picked {
+ border-color: var(--accent);
+ box-shadow: 0 0 0 2px var(--accent-dim);
+}
+.gen-pop {
+ position: absolute;
+ top: calc(100% + 4px);
+ right: 0;
+ z-index: 40;
+ display: flex;
+ gap: 6px;
+ align-items: center;
+ padding: 6px 8px;
+ background: var(--bg, #ffffff);
+ border: 1px solid var(--line, #e2e8f0);
+ border-radius: 6px;
+ box-shadow: 0 4px 14px rgba(15, 23, 42, 0.12);
+}
+.gen-pop label {
+ display: inline-flex;
+ gap: 3px;
+ align-items: center;
+ font-size: 10px;
+ color: var(--fg-dim, #64748b);
+ white-space: nowrap;
+}
+.gen-pop input {
+ width: 46px;
+ padding: 2px 4px;
+ font-size: 11px;
+ border: 1px solid var(--line, #e2e8f0);
+ border-radius: 4px;
+ background: transparent;
+ color: inherit;
+}
+
+/* 최종 아틀라스 섹션 — 페이지 맨 아래: 시트(좌) | 런타임 manifest(우) */
+.final-atlas .atlas-split {
+ display: flex;
+ gap: 14px;
+ /* 기준은 아틀라스 시트 (maintainer 지시 2026-07-17): JSON 패널 높이는 JS
+ (syncAtlasDocHeight)가 시트 실측 높이로 고정한다 — stretch 를 쓰면 JSON 이
+ 길 때 반대로 JSON 이 기준이 돼 버린다. */
+ align-items: flex-start;
+ margin-top: 10px;
+}
+.final-atlas .atlas-sheet {
+ flex: 0 1 52%;
+ min-width: 0;
+ display: block;
+ background:
+ repeating-conic-gradient(rgba(148, 163, 184, 0.18) 0% 25%, transparent 0% 50%) 0 0 / 16px 16px;
+ border: 1px solid var(--line, #e2e8f0);
+ border-radius: 8px;
+ padding: 8px;
+}
+.final-atlas .atlas-sheet img {
+ display: block;
+ width: 100%;
+ height: auto;
+}
+.final-atlas .atlas-doc {
+ flex: 1 1 48%;
+ min-width: 0;
+ display: flex;
+ flex-direction: column;
+ border: 1px solid var(--line, #e2e8f0);
+ border-radius: 8px;
+ overflow: hidden;
+}
+.final-atlas .atlas-doc-head {
+ padding: 6px 10px;
+ font-size: 11.5px;
+ color: var(--fg-dim, #64748b);
+ border-bottom: 1px solid var(--line, #e2e8f0);
+ background: var(--bg-soft, #f8fafc);
+}
+.final-atlas .atlas-doc-json {
+ margin: 0;
+ padding: 10px;
+ flex: 1;
+ min-height: 0;
+ overflow: auto;
+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
+ font-size: 11px;
+ line-height: 1.45;
+ white-space: pre;
+}
+.final-atlas .atlas-pending {
+ margin-top: 10px;
+ padding: 18px;
+ border: 1px dashed var(--line, #cbd5e1);
+ border-radius: 8px;
+ color: var(--fg-dim, #64748b);
+ font-size: 12.5px;
+}
+
+.gen-pop select {
+ padding: 2px 4px;
+ font-size: 11px;
+ border: 1px solid var(--line, #e2e8f0);
+ border-radius: 4px;
+ background: transparent;
+ color: inherit;
+}
+
+/* 저장 실패 배너 — 상태줄과 달리 무시할 수 없게 상단 고정 (죽은 탭 편집 유실 방지) */
+.save-lost-banner {
+ position: fixed;
+ top: 0;
+ left: 0;
+ right: 0;
+ z-index: 5000;
+ padding: 10px 18px;
+ background: #fef2f2;
+ color: var(--danger, #dc2626);
+ border-bottom: 1px solid #fecaca;
+ font-size: 13px;
+ font-weight: 600;
+ text-align: center;
+}
+
+/* 보간 생성 중 스피너 — Generate 버튼 안에서 돈다 */
+.gen-spin {
+ display: inline-block;
+ width: 12px;
+ height: 12px;
+ vertical-align: -2px;
+ border: 2px solid var(--accent-dim, #dbe5fb);
+ border-top-color: var(--accent, #2563eb);
+ border-radius: 50%;
+ animation: sg-spin 0.8s linear infinite;
+}
+@keyframes sg-spin { to { transform: rotate(360deg); } }
+
+
+/* 마키(영역 선택) — 점선 박스, 개미행렬 애니메이션 */
+.marquee {
+ position: absolute;
+ z-index: 6;
+ pointer-events: none;
+ border: 1px dashed var(--accent, #2563eb);
+ background: rgba(37, 99, 235, 0.07);
+ animation: sg-ants 0.6s linear infinite;
+}
+@keyframes sg-ants { to { border-color: rgba(37, 99, 235, 0.35); } }
+.stage.selecting { cursor: crosshair; }
+/* 변형 툴 — 기본 모드. 선택이 있으면 그 영역만, 없으면 셀 전체를 옮긴다. */
+.stage.transforming { cursor: move; }
+.stage.lassoing { cursor: crosshair; }
+/* 올가미 — 그리는 중 윤곽(위)과 확정 마스크(아래). 둘 다 포인터 통과. */
+.lasso-path, .lasso-mask {
+ position: absolute;
+ inset: 0;
+ width: 100%;
+ height: 100%;
+ pointer-events: none;
+}
+.lasso-path { z-index: 5; }
+.lasso-mask { z-index: 4; }
+/* 영역 변형 실시간 미리보기 — 스테이지 위에 겹치는 결과 레이어 (포인터는 통과). */
+.region-preview {
+ position: absolute;
+ inset: 0;
+ width: 100%;
+ height: 100%;
+ pointer-events: none;
+ z-index: 3;
+}
+
+
+/* 팔레트 도크 — Aseprite 식 세로 팔레트 (maintainer 지시 2026-07-17):
+ 위 = 현재 쓰인 색 전부(같은 색 1개, 빈도순), 아래 = 자유 색상 피커 */
+.stage-row { display: flex; align-items: flex-start; gap: 8px; }
+.stage-row .stage { flex: 1 1 auto; }
+.palette-dock {
+ flex: 0 0 auto;
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ align-items: center;
+ padding: 6px;
+ border: 1px solid var(--line, #e4e7ec);
+ border-radius: 8px;
+ background: var(--panel-2, #f1f3f6);
+ max-height: 72vh;
+}
+.palette-swatches {
+ display: grid;
+ grid-template-columns: repeat(2, 18px); /* 두 줄(2열) — maintainer 지시 2026-07-17 */
+ gap: 3px;
+ overflow-y: auto;
+ min-height: 0;
+ padding: 1px;
+}
+.palette-swatches .swatch { flex: none; }
+.palette-swatches .swatch.current { outline: 2px solid var(--accent, #2563eb); outline-offset: 1px; }
+.palette-dock .et-color { width: 24px; height: 24px; padding: 0; border: 1px solid var(--line); border-radius: 5px; background: transparent; flex: none; }
+
+/* 호흡 모드 — 드래그 가슴선 + 컨트롤 바 */
+.breathe-line {
+ position: absolute;
+ left: 0;
+ right: 0;
+ height: 0;
+ border-top: 2px dashed rgba(220, 40, 40, 0.75);
+ cursor: ns-resize;
+ z-index: 5;
+}
+.breathe-line::after { /* 잡기 쉬운 히트 영역 */
+ content: "";
+ position: absolute;
+ left: 0;
+ right: 0;
+ top: -6px;
+ height: 12px;
+}
+.breathe-line-v { /* 세로선 (몸통 축·반폭, 영역 조정 UI 2026-07-30) */
+ top: 0;
+ bottom: 0;
+ left: auto;
+ right: auto;
+ height: auto;
+ width: 0;
+ border-top: none;
+ border-left: 2px dashed rgba(40, 110, 220, 0.7);
+ cursor: ew-resize;
+}
+.breathe-line-v::after {
+ left: -6px;
+ right: auto;
+ top: 0;
+ width: 12px;
+ height: 100%;
+}
+.breathe-axis { border-left-style: solid; border-left-color: rgba(40, 110, 220, 0.45); }
+.breathe-recalc { /* 해부 재계산 중 배지 (zoom-editor setRecalcBadge) */
+ position: absolute;
+ top: 8px;
+ right: 8px;
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ padding: 3px 9px;
+ font-size: 11px;
+ color: #333;
+ background: rgba(255, 255, 255, 0.92);
+ border: 1px solid var(--line);
+ border-radius: 12px;
+ z-index: 6;
+ pointer-events: none;
+}
+.breathe-recalc-spin {
+ width: 10px;
+ height: 10px;
+ border: 2px solid rgba(40, 110, 220, 0.25);
+ border-top-color: rgba(40, 110, 220, 0.9);
+ border-radius: 50%;
+ animation: breathe-recalc-rot 0.7s linear infinite;
+}
+@keyframes breathe-recalc-rot { to { transform: rotate(360deg); } }
+.breathe-bar { display: inline-flex; align-items: center; gap: 6px; margin-left: 8px; }
+.breathe-auto { padding: 2px 7px; font-size: 11px; border: 1px solid var(--line); border-radius: 4px; background: transparent; color: inherit; cursor: pointer; }
+.breathe-auto:hover:not(:disabled) { border-color: var(--accent); color: var(--accent); }
+.breathe-bar select { padding: 2px 4px; font-size: 11px; border: 1px solid var(--line); border-radius: 4px; background: transparent; color: inherit; }
+.breathe-count { display: inline-flex; align-items: center; gap: 3px; font-size: 11px; color: var(--muted); }
+.breathe-count input { width: 44px; padding: 2px 4px; font-size: 11px; border: 1px solid var(--line); border-radius: 4px; text-align: center; }
+.breathe-count button { padding: 2px 7px; font-size: 12px; border: 1px solid var(--line); border-radius: 4px; background: transparent; cursor: pointer; }
+.breathe-count button:hover { border-color: var(--accent); color: var(--accent); }
+.breathe-fit-badge { color: #b45309; font-size: 11px; font-weight: 600; margin-left: 2px; }
+/* 줄 fps 스텝퍼 — 전체 재생 속도 (프레임별 시간은 복제가 담당) */
+.fps-stepper { display: inline-flex; align-items: center; gap: 3px; font-size: 11px; color: var(--fg-dim, #64748b); }
+.fps-stepper .fps-value { min-width: 34px; text-align: center; font-variant-numeric: tabular-nums; }
+.fps-stepper button { padding: 2px 7px; font-size: 12px; border: 1px solid var(--line); border-radius: 4px; background: transparent; cursor: pointer; color: inherit; }
+.fps-stepper button:hover { border-color: var(--accent); color: var(--accent); }
+.fps-stepper button:disabled { opacity: 0.5; cursor: default; }
+/* 최종 굽기 필름스트립 — 시퀀스×호흡주기 LCM 전개를 그대로 나열 */
+.breathe-strip { margin-top: 8px; }
+.breathe-strip .bs-caption { font-size: 11.5px; color: var(--muted); margin-bottom: 5px; }
+.breathe-strip .bs-frames { display: flex; gap: 4px; overflow-x: auto; padding-bottom: 4px; }
+.breathe-strip .bs-cell { flex: none; display: flex; flex-direction: column; align-items: center; gap: 2px; }
+.breathe-strip .bs-cell canvas { width: 56px; height: 56px; border: 1px solid var(--line); border-radius: 4px; background: repeating-conic-gradient(#ececec 0% 25%, #f8f8f8 0% 50%) 0 0 / 8px 8px; }
+.breathe-strip .bs-cap { font-size: 9.5px; color: var(--muted); white-space: nowrap; }
+/* 파이프라인 진행 바 — 상단 고정 얇은 바 (표시 전용) */
+#op-progress { position: fixed; top: 0; left: 0; right: 0; height: 3px; z-index: 5000; background: transparent; pointer-events: none; }
+#op-progress[hidden] { display: none; }
+.op-progress-fill { height: 100%; width: 0; background: var(--accent, #2563eb); transition: width 0.4s ease; }
+.op-progress-fill.indeterminate { animation: op-indet 1.2s linear infinite; width: 40% !important; }
+@keyframes op-indet { from { transform: translateX(-100%); } to { transform: translateX(350%); } }
+/* 줄 헤더 호흡 토글: 체크박스 = 시퀀스 투입 on/off, 라벨 클릭 = 에디터 열기 */
+.breathe-toggle { display: inline-flex; align-items: center; gap: 4px; }
+.breathe-toggle .breathe-open { display: inline-flex; align-items: center; gap: 3px; cursor: pointer; }
+.breathe-toggle .breathe-open:hover { color: var(--accent); }
+
+/* 호흡 포커스 모드 — 가슴선·진폭·생성만 남기고 편집 크롬 전부 숨김 */
+.zoom-card.breathe-focus .edit-toolbar > :not(.breathe-bar) { display: none; }
+.zoom-card.breathe-focus .breathe-bar { margin-left: 0; }
+/* 포커스 모드: 스테이지는 제 크기 유지 (스트립이 카드 폭을 키워도 안 따라 늘어남),
+ 스트립은 스테이지 폭 언저리에서 가로 스크롤 */
+.zoom-card.breathe-focus .stage { flex: 0 0 auto; }
+.zoom-card.breathe-focus .breathe-strip { max-width: 560px; }
+.zoom-card.breathe-focus .palette-dock,
+.zoom-card.breathe-focus .row-controls,
+.zoom-card.breathe-focus .card-controls,
+.zoom-card.breathe-focus .rotate-handle,
+.zoom-card.breathe-focus .shear-handle,
+.zoom-card.breathe-focus .zoom-prev,
+.zoom-card.breathe-focus .zoom-next,
+.zoom-card.breathe-focus .scale-scrub { display: none !important; }
+
+/* 앵커 비교 캔버스 — 나란히/겹침 + 공유 바닥선 + 드래그 가이드 */
+#compare-modal { position: fixed; inset: 0; z-index: 2000; display: flex; align-items: center; justify-content: center; padding: 24px; }
+#compare-modal .zoom-backdrop { position: absolute; inset: 0; background: rgba(15, 18, 24, 0.5); }
+/* 3계층 계약 (maintainer 2026-07-20): 카드 = 최대 크기 고정, 뷰포트(.cmp-scroll)가 배율·팬 소유 */
+#compare-modal .cmp-card { position: relative; z-index: 1; width: 94vw; height: 92vh; overflow: hidden; display: flex; flex-direction: column; gap: 10px; padding: 14px 16px 12px; background: var(--panel, #fff); box-shadow: 0 18px 60px rgba(0,0,0,0.35); border-radius: 12px; }
+#compare-modal .cmp-controls { margin-left: auto; display: inline-flex; gap: 8px; align-items: center; }
+#compare-modal .cmp-zoom { padding: 2px 4px; font-size: 12px; border: 1px solid var(--line); border-radius: 4px; }
+#compare-modal .cmp-hint { font-size: 11.5px; color: var(--muted); }
+#compare-modal .cmp-stage { position: relative; flex: none; background-color: var(--checker-a); background-image: linear-gradient(45deg, var(--checker-b) 25%, transparent 25%), linear-gradient(-45deg, var(--checker-b) 25%, transparent 25%), linear-gradient(45deg, transparent 75%, var(--checker-b) 75%), linear-gradient(-45deg, transparent 75%, var(--checker-b) 75%); background-size: 16px 16px; background-position: 0 0, 0 8px, 8px -8px, -8px 0; border-radius: 6px; }
+#compare-modal .cmp-canvas { display: block; image-rendering: pixelated; cursor: crosshair; }
+#compare-modal .cmp-guides { position: absolute; inset: 0; pointer-events: none; }
+#compare-modal .cmp-body { display: flex; gap: 10px; flex: 1 1 auto; min-height: 0; }
+#compare-modal .cmp-list { flex: 0 0 190px; overflow-y: auto; display: flex; flex-direction: column; gap: 2px; border: 1px solid var(--line); border-radius: 8px; padding: 6px; }
+#compare-modal .cmp-viewwrap { position: relative; flex: 1 1 auto; min-width: 0; display: flex; }
+#compare-modal .cmp-item { display: flex; align-items: center; gap: 7px; font-size: 12px; padding: 3px 5px; border-radius: 6px; cursor: pointer; }
+#compare-modal .cmp-item:hover { background: var(--panel-2); }
+#compare-modal .cmp-item img { width: 26px; height: 26px; object-fit: contain; }
+/* 뷰포트: stage-pad 의 사방 패딩으로 자유 팬 — 중앙 정렬은 오픈 시 스크롤로 놓는다
+ (compare.js render 의 1회 centerView). */
+#compare-modal .cmp-scroll { overflow: auto; flex: 1; min-width: 0; border: 1px solid var(--line); border-radius: 10px; background: var(--panel-2, #f8fafc); }
+/* 가이드: 0px 선은 못 잡는다 — 9px 히트영역 안에 선을 그린다 (maintainer "안 움직여") */
+#compare-modal .cmp-guide { position: absolute; pointer-events: auto; }
+#compare-modal .cmp-guide.gh { left: 0; right: 0; height: 9px; margin-top: -4px; cursor: ns-resize; }
+#compare-modal .cmp-guide.gh::before { content: ""; position: absolute; left: 0; right: 0; top: 4px; border-top: 2px dashed rgba(220, 38, 38, 0.85); }
+#compare-modal .cmp-guide.gv { top: 0; bottom: 0; width: 9px; margin-left: -4px; cursor: ew-resize; }
+#compare-modal .cmp-guide.gv::before { content: ""; position: absolute; top: 0; bottom: 0; left: 4px; border-left: 2px dashed rgba(220, 38, 38, 0.85); }
+#compare-modal .cmp-guide.focused.gh::before { border-top-style: solid; border-top-width: 3px; }
+#compare-modal .cmp-guide.focused.gv::before { border-left-style: solid; border-left-width: 3px; }
+#compare-modal .cmp-guide.gh span { position: absolute; right: 4px; top: -14px; font-size: 10.5px; color: #dc2626; background: rgba(255,255,255,0.85); padding: 0 4px; border-radius: 3px; }
+#compare-modal .cmp-guide.gv span { position: absolute; left: 8px; top: 4px; font-size: 10.5px; color: #dc2626; background: rgba(255,255,255,0.85); padding: 0 4px; border-radius: 3px; }
+#compare-modal .cmp-zoom-label { font-size: 12px; color: var(--muted); min-width: 30px; }
+#compare-modal .cmp-legend { display: flex; gap: 16px; font-size: 12px; color: var(--muted); }
+#compare-modal .cmp-key .cmp-name { font-weight: 600; color: var(--text); }
+
+/* 손(팬) 툴 — Space 홀드(임시) / 버튼 토글: 잡기 커서로 팬 가능 상태를 알린다.
+ 팬 소유자 = 뷰포트 (.stage-viewport / .cmp-scroll) — 3계층 계약. */
+body.pan-space #zoom-modal .stage,
+body.pan-space #zoom-modal .stage-viewport,
+body.pan-space #compare-modal .cmp-scroll,
+body.pan-space #compare-modal .cmp-stage,
+body.pan-space #compare-modal .cmp-canvas,
+#zoom-modal .stage-viewport.pan-tool,
+#zoom-modal .stage-viewport.pan-tool .stage,
+#compare-modal .cmp-scroll.pan-tool,
+#compare-modal .cmp-scroll.pan-tool .cmp-canvas { cursor: grab; }
+.et-hand.active, .cmp-hand.active { background: #e8ecf4; color: #2563eb; border-color: #2563eb; }
+
+/* 줄 저장 팝오버 — 공용 .dl-wrap/.dl-menu 재사용, 줄 헤더 안 인라인 배치.
+ .dl-wrap 의 inline-block(뒤쪽 규칙)을 이기도록 2클래스 지정 — 버튼이 형제 컨트롤
+ 높이(stretch)에 맞는다 (maintainer 2026-07-19 "저장버튼 높이가 안 맞네"). */
+.dl-wrap.row-dl-wrap { display: inline-flex; align-items: stretch; }
+.row-dl-wrap .dl-menu { right: 0; left: auto; } /* 맨 우측 배치라 메뉴는 오른끝 정렬 */
+
+/* 확대뷰 호흡 토글 — 끄면 조정 컨트롤이 쉰다 (무호흡 재생 확인용) */
+.breathe-enable { margin-right: 2px; }
+.breathe-bar select:disabled, .breathe-bar input:disabled, .breathe-bar button:disabled { opacity: 0.45; cursor: default; }
+
+/* 복제 링크 상태 버튼 — 배지 옆 (하단 컨트롤 줄 과밀로 잘리던 문제 해소, maintainer 2026-07-18) */
+.link-state-btn { padding: 1px 4px; flex: none; }
+.link-state-btn svg { display: block; }
+
+/* 아틀라스 스테일 배지 — 편집 이후 아직 굽지 않음 (관측 가능한 스테일 상태) */
+.atlas-bake-btn.stale {
+ border-color: #c9862a;
+ color: #c9862a;
+}
+
+/* 저장 팝오버 (비교/상단 공용) */
+.cmp-dl-wrap, .dl-wrap { position: relative; display: inline-block; }
+.cmp-dl-menu[hidden], .dl-menu[hidden] { display: none; } /* hidden 이 display:flex 를 이겨야 한다 */
+.cmp-dl-menu, .dl-menu {
+ position: absolute;
+ top: calc(100% + 4px);
+ right: 0;
+ z-index: 40;
+ display: flex;
+ flex-direction: column;
+ min-width: 132px;
+ padding: 4px;
+ background: #fff;
+ border: 1px solid #d7d7dc;
+ border-radius: 8px;
+ box-shadow: 0 6px 20px rgba(20, 22, 30, 0.12);
+}
+.cmp-dl-menu button, .dl-menu button {
+ border: 0;
+ background: none;
+ text-align: left;
+ padding: 6px 10px;
+ border-radius: 6px;
+ font: inherit;
+ cursor: pointer;
+ white-space: nowrap;
+}
+.cmp-dl-menu button:hover, .dl-menu button:hover { background: #f0f1f5; }
+
+/* 장기 heal/추출 첫 로드 로딩 패널 (plan long-op-loading-ux) */
+.op-loading {
+ max-width: 460px;
+ margin: 18vh auto 0;
+ padding: 28px 32px;
+ border: 1px solid var(--line, #e2e8f0);
+ border-radius: 12px;
+ text-align: center;
+ display: flex;
+ flex-direction: column;
+ gap: 14px;
+}
+.op-loading-title { font-size: 15px; font-weight: 600; }
+.op-loading-bar {
+ height: 6px;
+ border-radius: 3px;
+ background: var(--line, #e2e8f0);
+ overflow: hidden;
+}
+.op-loading-fill {
+ height: 100%;
+ border-radius: 3px;
+ background: var(--accent, #3b82f6);
+ transition: width 0.4s ease;
+}
+.op-loading-fill.indeterminate { animation: op-loading-slide 1.4s ease-in-out infinite; }
+@keyframes op-loading-slide {
+ 0% { transform: translateX(-100%); }
+ 100% { transform: translateX(100%); }
+}
+.op-loading-live { font-size: 13px; color: var(--fg-dim, #64748b); min-height: 1.2em; }
+.op-loading-note { font-size: 12px; color: var(--fg-dim, #94a3b8); }
+
+/* ── 컬러웨이(recolor variant) 비교·픽 ─────────────────────────────────────
+ 스테이지는 시트를 겹쳐 쌓고 active 하나만 보인다: 목록 위를 지나가면 같은 자리에서
+ 즉시 갈아끼워져(전부 선로드) 한 칸짜리 색차가 깜빡임으로 드러난다. 나란히 비교는
+ 오른쪽 썸네일 목록이 겸한다. */
+.recolor-variants .rc-split {
+ display: flex;
+ gap: 14px;
+ align-items: flex-start;
+ margin-top: 10px;
+}
+.recolor-variants .rc-stage {
+ position: relative;
+ flex: 1 1 58%;
+ min-width: 0;
+ background:
+ repeating-conic-gradient(rgba(148, 163, 184, 0.18) 0% 25%, transparent 0% 50%) 0 0 / 16px 16px;
+ border: 1px solid var(--line, #e2e8f0);
+ border-radius: 8px;
+ padding: 8px;
+}
+.recolor-variants .rc-stage img {
+ display: block;
+ width: 100%;
+ height: auto;
+}
+/* 첫 장만 흐름에 남겨 스테이지 높이를 정하고, 나머지는 그 위에 겹친다 — 교체할 때
+ 레이아웃이 흔들리면 "같은 자리 비교" 가 깨진다. */
+.recolor-variants .rc-stage img:not(:first-of-type) {
+ position: absolute;
+ left: 8px;
+ top: 8px;
+ width: calc(100% - 16px);
+}
+.recolor-variants .rc-stage img { visibility: hidden; }
+.recolor-variants .rc-stage img.active { visibility: visible; }
+.recolor-variants .rc-stage-label {
+ position: absolute;
+ right: 10px;
+ bottom: 8px;
+ font-size: 11.5px;
+ color: var(--fg-dim, #64748b);
+ background: rgba(255, 255, 255, 0.82);
+ border-radius: 4px;
+ padding: 1px 6px;
+}
+.recolor-variants .rc-list {
+ flex: 1 1 42%;
+ min-width: 0;
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ max-height: 420px;
+ overflow: auto;
+}
+.recolor-variants .rc-thumb {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 6px 8px;
+ border: 1px solid var(--line, #e2e8f0);
+ border-radius: 8px;
+ cursor: pointer;
+}
+.recolor-variants .rc-thumb.previewing { border-color: var(--accent, #3b82f6); }
+.recolor-variants .rc-thumb.picked { background: var(--bg-soft, #f8fafc); }
+.recolor-variants .rc-thumb.missing { border-style: dashed; }
+/* 썸네일 = 프레임 한 칸 창문. `cropped` 면 안의 <img> 가 상자 크기로 확대돼 밀려
+ 들어가 있고(recolorSwatchStyle), 창문이 나머지를 잘라낸다. 상자를 못 받은 런은
+ 창문이 시트 전체를 담는다 — 그때만 이미지가 창문 폭에 맞춰 줄어든다. */
+.recolor-variants .rc-swatch {
+ display: block;
+ flex: none;
+ width: 64px;
+ height: 64px;
+ overflow: hidden;
+ background:
+ repeating-conic-gradient(rgba(148, 163, 184, 0.18) 0% 25%, transparent 0% 50%) 0 0 / 8px 8px;
+}
+.recolor-variants .rc-swatch img {
+ display: block;
+ max-width: 100%;
+ height: auto;
+}
+.recolor-variants .rc-swatch.cropped img { max-width: none; }
+.recolor-variants .rc-thumb-body {
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+ min-width: 0;
+ flex: 1;
+}
+.recolor-variants .rc-name { font-size: 12.5px; font-weight: 600; }
+.recolor-variants .rc-note,
+.recolor-variants .rc-manifest,
+.recolor-variants .rc-missing { font-size: 11.5px; color: var(--fg-dim, #64748b); }
+.recolor-variants .rc-warn { font-size: 11.5px; color: var(--warn, #b45309); }
+.recolor-variants .rc-pick { flex: none; }
+.recolor-variants .rc-thumb.picked .rc-pick { color: var(--accent, #3b82f6); }
+.recolor-variants .rc-unknown {
+ margin-top: 10px;
+ padding: 8px 10px;
+ border: 1px solid var(--warn, #b45309);
+ border-radius: 8px;
+ font-size: 12px;
+ color: var(--warn, #b45309);
+}
diff --git a/sprite_gen/serve/curator/index.html b/sprite_gen/serve/curator/index.html
new file mode 100644
index 0000000..5752a12
--- /dev/null
+++ b/sprite_gen/serve/curator/index.html
@@ -0,0 +1,78 @@
+<!DOCTYPE html>
+<!-- SPDX-License-Identifier: Apache-2.0 -->
+<html lang="en">
+ <head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <title>sprite-gen curation</title>
+ <link rel="stylesheet" href="/curator.css" />
+ </head>
+ <body>
+ <header class="topbar">
+ <div class="title">
+ <strong>sprite-gen</strong> <span id="t-title"></span>
+ <span id="character" class="muted"></span>
+ </div>
+ <div class="actions">
+ <span id="status" class="status"></span>
+ <button id="lang-toggle" type="button" class="ghost"></button>
+ <label id="pxgrid-wrap" class="unfake-apply" hidden>
+ <input type="checkbox" id="pxgrid-check" />
+ <span id="pxgrid-label"></span>
+ </label>
+ <label id="unfake-wrap" class="unfake-apply" hidden>
+ <input type="checkbox" id="unfake-apply" />
+ <span id="pp-label"></span>
+ </label>
+ <button id="compare-open" type="button" class="ghost"></button>
+ <button id="grid-toggle" type="button" class="ghost" hidden></button>
+ <span class="dl-wrap">
+ <button id="dl-main" type="button"></button>
+ <div id="dl-main-menu" class="dl-menu" hidden>
+ <button id="compose" type="button"></button>
+ <button id="export" type="button"></button>
+ <button id="export-gif" type="button"></button>
+ </div>
+ </span>
+ </div>
+ </header>
+ <div id="layout">
+ <aside id="sidebar"></aside>
+ <button id="sidebar-toggle" type="button" aria-label="toggle file tree">
+ <svg viewBox="0 0 16 16" width="11" height="11" aria-hidden="true">
+ <path d="M10.5 2.5 5 8l5.5 5.5" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/>
+ </svg>
+ </button>
+ <main id="states"></main>
+ </div>
+ <footer class="hintbar" id="hintbar"></footer>
+ <script src="/src/util.js"></script>
+ <script src="/src/i18n.js"></script>
+ <script src="/src/tooltip.js"></script>
+ <script src="/src/view-nav.js"></script>
+ <script src="/src/store.js"></script>
+ <script src="/src/status.js"></script>
+ <script src="/src/progress.js"></script>
+ <script src="/src/persistence.js"></script>
+ <script src="/src/display.js"></script>
+ <script src="/src/transform-provider.js"></script>
+ <script src="/src/transforms.js"></script>
+ <script src="/src/lasso-select.js"></script>
+ <script src="/src/region-transform.js"></script>
+ <script src="/src/zones.js"></script>
+ <script src="/src/gen-trigger.js"></script>
+ <script src="/src/row-controls.js"></script>
+ <script src="/src/row-export.js"></script>
+ <script src="/src/tween.js"></script>
+ <script src="/src/breathe.js"></script>
+ <script src="/src/cards.js"></script>
+ <script src="/src/zoom-editor.js"></script>
+ <script src="/src/base-editor.js"></script>
+ <script src="/src/pipeline-tree.js"></script>
+ <script src="/src/atlas.js"></script>
+ <script src="/src/recolor.js"></script>
+ <script src="/src/compare.js"></script>
+ <script src="/src/chrome.js"></script>
+ <script src="/src/boot.js"></script>
+ </body>
+</html>
diff --git a/sprite_gen/serve/curator/src/atlas.js b/sprite_gen/serve/curator/src/atlas.js
new file mode 100644
index 0000000..7769596
--- /dev/null
+++ b/sprite_gen/serve/curator/src/atlas.js
@@ -0,0 +1,164 @@
+// SPDX-License-Identifier: Apache-2.0
+// curator/atlas.js — 최종 아틀라스 섹션 (시트 + manifest 뷰)
+// 로드 순서 SSoT = index.html (classic script 전역 어휘 공유; 빌드 스텝 없음)
+
+// 아틀라스는 다운로드/합성 시점의 산출물이라 계산 시각을 함께 표시한다 — 큐레이션을
+// 더 만졌으면 다음 다운로드가 다시 계산한다 (버튼 = 라이브 상태의 다운로드 계약).
+async function renderFinalAtlas(info) {
+ let section = document.getElementById("final-atlas");
+ if (!section) {
+ section = document.createElement("div");
+ section.id = "final-atlas";
+ section.className = "state final-atlas";
+ document.getElementById("states").appendChild(section);
+ }
+ if (!info) {
+ section.innerHTML =
+ `<div class="state-head"><span class="name">${t("treeAtlas")}</span></div>` +
+ `<div class="atlas-pending">${t("atlasPending")}</div>`;
+ return;
+ }
+ const stamp = STR[lang].atlasStamp(new Date(info.mtime * 1000).toLocaleString());
+ let docHtml = "";
+ if (info.manifestUrl) {
+ try {
+ const res = await fetch(info.manifestUrl);
+ const doc = await res.json();
+ docHtml = `<pre class="atlas-doc-json">${escapeHtml(JSON.stringify(doc, null, 2))}</pre>`;
+ } catch {
+ docHtml = `<pre class="atlas-doc-json">manifest.json 읽기 실패</pre>`;
+ }
+ }
+ section.innerHTML =
+ `<div class="state-head"><span class="name">${t("treeAtlas")}</span>` +
+ `<span class="meta">sprite-sheet-alpha.png · ${escapeHtml(stamp)}</span>` +
+ `<button type="button" class="ghost atlas-bake-btn" data-tip="${t("tAtlasBake")}">${t("atlasBake")}</button></div>` +
+ `<div class="atlas-split">` +
+ `<a class="atlas-sheet" href="${escapeHtml(info.url)}" target="_blank">` +
+ `<img src="${escapeHtml(info.url)}" alt="final atlas" /></a>` +
+ (docHtml
+ ? `<div class="atlas-doc"><div class="atlas-doc-head">${t("atlasDoc")}</div>${docHtml}</div>`
+ : "") +
+ `</div>`;
+ const bakeBtn = section.querySelector(".atlas-bake-btn");
+ // 스테일 관측성 (maintainer 2026-07-19 "아틀라스가 내가 편집한 게 아닌"): 시트는
+ // 마지막 굽기 시점의 산출물이다 — 그 뒤 편집이 있으면 버튼에 배지로 알린다.
+ if (typeof lastEditAt !== "undefined" && lastEditAt > info.mtime * 1000) markAtlasStale();
+ if (bakeBtn) bakeBtn.addEventListener("click", async () => {
+ bakeBtn.disabled = true;
+ bakeBtn.textContent = t("atlasBaking");
+ try {
+ await flushSave(); // 서버는 디스크 truth 를 굽는다 — 대기 중 편집 저장부터
+ const res = await fetch("/api/compose", { method: "POST" });
+ const data = await res.json();
+ if (!res.ok || !data.ok) throw new Error(data.error || res.status);
+ await refreshFinalAtlas();
+ setStatus(t("atlasBaked"), "ok");
+ } catch (e) {
+ setStatus(t("atlasBakeFail") + e.message, "err");
+ bakeBtn.disabled = false;
+ bakeBtn.textContent = t("atlasBake");
+ }
+ });
+ syncAtlasDocHeight();
+ ensureAtlasObserver(); // 레이지 굽기 — 섹션 가시성 감시
+}
+
+// JSON 패널 높이 = 아틀라스 시트 높이 (maintainer 지시 2026-07-17: 기준은 아틀라스 —
+// stretch 는 JSON 이 길면 반대로 JSON 이 기준이 돼 버린다). 이미지 로드 후 실측으로
+// 고정하고, 창 리사이즈 때 다시 잰다. JSON 이 더 길면 패널 안에서 스크롤.
+function syncAtlasDocHeight() {
+ const section = document.getElementById("final-atlas");
+ if (!section) return;
+ const sheetImg = section.querySelector(".atlas-sheet img");
+ const doc = section.querySelector(".atlas-doc");
+ if (!sheetImg || !doc) return;
+ const apply = () => {
+ const h = section.querySelector(".atlas-sheet").offsetHeight;
+ if (h > 0) doc.style.height = h + "px";
+ };
+ if (sheetImg.complete && sheetImg.naturalWidth) apply();
+ else sheetImg.addEventListener("load", apply, { once: true });
+ if (!syncAtlasDocHeight._wired) {
+ syncAtlasDocHeight._wired = true;
+ window.addEventListener("resize", () => {
+ clearTimeout(syncAtlasDocHeight._t);
+ syncAtlasDocHeight._t = setTimeout(syncAtlasDocHeight, 120);
+ });
+ }
+}
+
+// 다운로드가 아틀라스/manifest 를 다시 계산했을 수 있으니 섹션을 최신 파일로 갱신
+// ── 레이지 자동 굽기 (maintainer 2026-07-19 "실시간 반영, 단 느린 컴퓨터 렉 걱정"):
+// 편집은 dirty 만 표시하고, 아틀라스 섹션이 **화면에 보일 때만** 디바운스 굽기를
+// 돌린다 — 안 보는 동안엔 비용 0, 스크롤로 내려오는 순간 최신으로 한 번에 반영.
+// 디바운스는 직전 compose 실측 소요시간의 3배(최소 0.8s)로 자동 조절 — 느린
+// 머신일수록 덜 자주 굽는다. 굽는 중 새 편집은 끝나고 한 번 더 (코얼레싱).
+// 수동 "지금 상태로 굽기" 버튼은 즉시 실행용으로 유지.
+let autoBakeTimer = null;
+let autoBakeRunning = false;
+let autoBakeDirty = false;
+let atlasDirty = false;
+let atlasVisible = false;
+let atlasObserver = null;
+let lastBakeMs = 100;
+function noteAtlasEdit() {
+ atlasDirty = true;
+ if (atlasVisible) scheduleAutoBake();
+}
+function ensureAtlasObserver() {
+ const section = document.getElementById("final-atlas");
+ if (!section || atlasObserver) return;
+ atlasObserver = new IntersectionObserver((ents) => {
+ atlasVisible = ents.some((e) => e.isIntersecting);
+ if (atlasVisible && atlasDirty) scheduleAutoBake();
+ });
+ atlasObserver.observe(section);
+}
+async function autoBakeAtlas() {
+ if (autoBakeRunning) { autoBakeDirty = true; return; }
+ autoBakeRunning = true;
+ let failed = null;
+ try {
+ const t0 = performance.now();
+ const res = await fetch("/api/compose", { method: "POST" });
+ lastBakeMs = performance.now() - t0;
+ const data = await res.json().catch(() => ({}));
+ if (res.ok && data.ok) {
+ atlasDirty = false;
+ await refreshFinalAtlas();
+ } else if (res.status === 503) autoBakeDirty = true; // 서버 바쁨 — 재시도
+ else failed = data.error || String(res.status);
+ } catch (e) {
+ failed = e.message;
+ }
+ autoBakeRunning = false;
+ // 지속 실패(500 등)는 재시도 루프를 돌리지 않는다 — 한 번 보고하고 배지 유지,
+ // 다음 편집(저장)이 오면 다시 시도 (회귀 2026-07-19: 추출 미완 상태에서
+ // 500 을 0.8s 간격으로 무한 재타격).
+ if (failed) setStatus(t("atlasBakeFail") + failed, "err");
+ else if (autoBakeDirty) { autoBakeDirty = false; scheduleAutoBake(); }
+}
+function scheduleAutoBake() {
+ clearTimeout(autoBakeTimer);
+ autoBakeTimer = setTimeout(autoBakeAtlas, Math.max(800, lastBakeMs * 3));
+}
+
+// 편집 직후 호출 (scheduleSave) — "편집 이후 안 구움" 을 버튼 배지로 보이게 한다.
+// (자동 굽기가 곧 갱신하므로 배지는 굽기 완료까지의 과도 상태 표시가 된다.)
+function markAtlasStale() {
+ const btn = document.querySelector(".atlas-bake-btn");
+ if (btn && !btn.disabled && !btn.classList.contains("stale")) {
+ btn.classList.add("stale");
+ btn.textContent = `${t("atlasBake")} · ${t("atlasStale")}`;
+ }
+}
+
+async function refreshFinalAtlas() {
+ const now = Math.floor(Date.now() / 1000);
+ renderFinalAtlas({
+ url: `/run/sprite-sheet-alpha.png?v=${now}`,
+ mtime: now,
+ manifestUrl: `/run/manifest.json?v=${now}`,
+ });
+}
diff --git a/sprite_gen/serve/curator/src/base-editor.js b/sprite_gen/serve/curator/src/base-editor.js
new file mode 100644
index 0000000..065e196
--- /dev/null
+++ b/sprite_gen/serve/curator/src/base-editor.js
@@ -0,0 +1,89 @@
+// SPDX-License-Identifier: Apache-2.0
+// curator/base-editor.js — 베이스 소스 편집 (검출 격자 논리 이미지 → 줌 모달 재사용)
+// 로드 순서 SSoT = index.html (classic script 전역 어휘 공유; 빌드 스텝 없음)
+
+// 최상단 base 참조 줄 — 아이덴티티 truth 를 생성 결과와 나란히 비교하기 위한
+// 읽기 전용 표시 (선택/변형/굽기와 무관).
+function renderBaseRow() {
+ const wrap = document.createElement("section");
+ wrap.className = "state base-row";
+ wrap.innerHTML =
+ `<div class="state-head"><h3>base</h3>` +
+ `<span class="muted">${t("baseNote")}</span>` +
+ `<button type="button" class="ghost base-edit-btn" data-tip="${t("tBaseEdit")}">✎ ${t("baseEditBtn")}</button></div>` +
+ `<div class="base-stage"><img src="${escapeHtml(run.baseUrl)}" alt="base source" draggable="false" /></div>`;
+ const editBtn = wrap.querySelector(".base-edit-btn");
+ editBtn.addEventListener("click", async () => {
+ // 격자 검출(첫 회 수 초) + 논리 이미지 빌드 동안 버튼 스피너 — 멈춘 것처럼 보이지 않게
+ if (editBtn.disabled) return;
+ editBtn.disabled = true;
+ const label = editBtn.innerHTML;
+ editBtn.innerHTML = '<span class="gen-spin" aria-label="loading"></span>';
+ try {
+ await openBaseEditor();
+ } finally {
+ editBtn.innerHTML = label;
+ editBtn.disabled = false;
+ }
+ });
+ document.getElementById("states").appendChild(wrap);
+}
+
+// ── 베이스 편집 = 줌 모달과 같은 컴포넌트 (maintainer 지시 2026-07-17 "같은 컴포넌트를
+// 쓰라" — 별도 모달 구현은 폐기). 검출 격자의 논리 해상도로 가상 상태 "__base__" 를
+// 만들어 openZoom 으로 연다. 도구/단축키/마키/줌/팬 전부 프레임 편집과 단일 코드.
+async function openBaseEditor() {
+ let grid = null;
+ try {
+ grid = (await (await fetch("/api/base-grid")).json()).grid || null;
+ } catch { grid = null; }
+ if (!grid) {
+ setStatus(t("baseEditFail") + "no confident pixel grid on the base", "err");
+ return;
+ }
+ const rawUrl = run.baseUrl + (run.baseUrl.includes("?") ? "&" : "?") + "edit=" + Date.now();
+ // 진짜 격자 기반 논리 이미지 (maintainer 지적 2026-07-17: 균일 등분 격자는 이미지와
+ // 어긋난다): 검출 절단선(xEdges/yEdges)의 블록 "중심"을 raw 에서 샘플해 논리
+ // 해상도 PNG 를 만든다. 이후 모달의 표시·편집·격자·팔레트는 전부 이 균일 논리
+ // 공간이라 프레임과 동일하게 정확히 떨어진다. raw 는 pp OFF 의 원본 뷰(plain
+ // twin 자리)로 쓴다. 저장(논리 ops→raw 확장)은 서버가 같은 절단선으로 한다.
+ const rawImg = new Image();
+ rawImg.src = rawUrl;
+ await new Promise((ok, err) => { rawImg.onload = ok; rawImg.onerror = err; });
+ const cols = grid.xEdges.length - 1;
+ const rows = grid.yEdges.length - 1;
+ const probe = document.createElement("canvas");
+ probe.width = rawImg.naturalWidth;
+ probe.height = rawImg.naturalHeight;
+ const pc = probe.getContext("2d");
+ pc.drawImage(rawImg, 0, 0);
+ const raw = pc.getImageData(0, 0, probe.width, probe.height).data;
+ const logical = document.createElement("canvas");
+ logical.width = cols;
+ logical.height = rows;
+ const lc = logical.getContext("2d");
+ const out = lc.createImageData(cols, rows);
+ for (let j = 0; j < rows; j++) {
+ for (let i = 0; i < cols; i++) {
+ const cx = Math.floor((grid.xEdges[i] + grid.xEdges[i + 1]) / 2);
+ const cy = Math.floor((grid.yEdges[j] + grid.yEdges[j + 1]) / 2);
+ const s = (cy * probe.width + cx) * 4;
+ const d = (j * cols + i) * 4;
+ out.data[d] = raw[s];
+ out.data[d + 1] = raw[s + 1];
+ out.data[d + 2] = raw[s + 2];
+ out.data[d + 3] = 255;
+ }
+ }
+ lc.putImageData(out, 0, 0);
+ baseView = { cols, rows, xEdges: grid.xEdges, yEdges: grid.yEdges,
+ url: logical.toDataURL("image/png"), rawUrl };
+ baseLogicalImg = new Image();
+ baseLogicalImg.src = baseView.url;
+ await new Promise((ok) => { baseLogicalImg.onload = ok; });
+ if (!entries[BASE_STATE]) {
+ entries[BASE_STATE] = { pixels: {}, transforms: {}, order: [0], sel: new Set([0]),
+ clones: {}, archived: [] };
+ }
+ openZoom(BASE_STATE, 0);
+}
diff --git a/sprite_gen/serve/curator/src/boot.js b/sprite_gen/serve/curator/src/boot.js
new file mode 100644
index 0000000..52072f1
--- /dev/null
+++ b/sprite_gen/serve/curator/src/boot.js
@@ -0,0 +1,206 @@
+// SPDX-License-Identifier: Apache-2.0
+// curator/boot.js — 부트스트랩 — 런 로드 → 전 도메인 초기 렌더 (항상 마지막 로드)
+// 로드 순서 SSoT = index.html (classic script 전역 어휘 공유; 빌드 스텝 없음)
+
+async function boot() {
+ try {
+ const res = await fetch("/api/run");
+ run = await res.json();
+ if (run.error) {
+ if (run.busy) {
+ // 재추출 진행 중 — 정식 로딩 패널(진행 바·현재 행)을 띄우고 끝나면 자동 재시도.
+ // busy 응답에는 run.lang 이 실려 온다 (첫 탭도 서버 --lang 로 렌더).
+ lang = new URLSearchParams(location.search).get("lang") || run.lang || lang || "en";
+ document.documentElement.lang = lang;
+ renderLoadingPanel();
+ startOpProgressWatch(() => window.location.reload());
+ return;
+ }
+ throw new Error(run.error);
+ }
+ } catch (e) {
+ document.getElementById("states").innerHTML =
+ `<div class="fatal">${t("runLoadFail")}\n${e.message}</div>`;
+ return;
+ }
+ // initial language: ?lang= (set by the toggle) overrides the server --lang
+ lang = new URLSearchParams(location.search).get("lang") || run.lang || "en";
+ document.documentElement.lang = lang;
+ // 자가치유 보고 (실시간 계약): 서버가 이번 로드에서 stale 프레임을 재계산했으면
+ // 조용히 알려만 준다 — '재추출' 버튼/개념은 없다. raw 가 없어 못 고친 행도 관측.
+ // (표시는 boot 끝의 최종 setStatus 자리에서 — 중간 상태 메시지에 덮이지 않게)
+ const healParts = [];
+ if (run.heal) {
+ if (run.heal.healed && run.heal.healed.length) healParts.push(`엔진 갱신 반영: ${run.heal.healed.join(", ")}`);
+ if (run.heal.kept_stale && run.heal.kept_stale.length) healParts.push(`원본 없음(구엔진 유지): ${run.heal.kept_stale.join(", ")}`);
+ if (run.heal.failed && run.heal.failed.length) healParts.push(`재계산 실패(이전 세대 유지): ${run.heal.failed.join(", ")}`);
+ }
+ // pixel-unfake twin state must resolve BEFORE first render (frameUrl reads it):
+ // per-state truth = states.<state>.pixel_unfake override > run-wide default > on.
+ seedUnfakeState(run);
+ // 격자 오버레이는 모든 줄이 가진다 — "격자 가능 줄" 이라는 집합 자체를 두지 않는다.
+ // 집합이 존재하면 언젠가 필터가 다시 붙는다 (validator R3 실증: 5줄 mutant 로 병 복원).
+ // 스위치가 없으면 되살릴 knob 도 없다.
+ gridStates = {};
+ applyStaticLang();
+ const cmpBtn = document.getElementById("compare-open");
+ if (cmpBtn) {
+ cmpBtn.textContent = t("cmpOpen");
+ cmpBtn.title = t("tCmpOpen");
+ cmpBtn.addEventListener("click", openCompare);
+ }
+ document.getElementById("character").textContent = `${run.characterId} · ${run.cell.width}×${run.cell.height}`;
+ if (run.iso) gridToggle.hidden = false;
+ {
+ // 퍼펙 전체 토글 — 항상 보인다 (조건 게이트 = 컨트롤 숨김 버그 클래스).
+ // 줄들이 섞이면(일부 on/off) indeterminate 로 표시한다 (syncUnfakeControls).
+ const unfakeWrap = document.getElementById("unfake-wrap");
+ const unfakeCheck = document.getElementById("unfake-apply");
+ unfakeWrap.hidden = false;
+ unfakeCheck.addEventListener("change", () => {
+ const on = unfakeCheck.checked;
+ for (const s of run.states) unfakeStates[s.name] = on;
+ syncUnfakeControls();
+ refreshVariantImages();
+ scheduleSave();
+ });
+ }
+ // 픽셀 격자 전체 토글 — 표시 전용 오버레이 (굽기와 무관), 줄별 체크박스와 같은 truth.
+ // 항상 보인다: 격자는 스크립트가 결정론으로 재는 것이라 "모름"이 없다.
+ const pxWrap = document.getElementById("pxgrid-wrap");
+ const pxCheck = document.getElementById("pxgrid-check");
+ pxWrap.hidden = false;
+ pxCheck.addEventListener("change", () => {
+ const on = pxCheck.checked;
+ for (const s of run.states) gridStates[s.name] = on;
+ syncGridControls();
+ sizePxGrids();
+ });
+ seedEntries();
+ if (run.directionGroups && run.directionGroups.length) {
+ anchorStates = new Set(run.directionGroups.map((g) => g.anchor).filter(Boolean));
+ // 생성 방향(미러 제외) + 사용자 앵커 프레임 지정 시드 — 앵커 배지/버튼의 입력
+ anchorDirections = run.directionGroups.filter((g) => !g.mirrorOf).map((g) => g.direction);
+ anchorPicks = {};
+ for (const [direction, pick] of Object.entries((run.curation && run.curation.anchors) || {})) {
+ if (pick && typeof pick.state === "string" && Number.isInteger(Number(pick.index))) {
+ // `stale` 을 **반드시 왕복**시킨다: 이걸 버리면 무관한 편집의 autosave 가 낡은 핀을
+ // 현재 세대로 세탁해 오류 배너가 사라진다 (validator 5차 기각 실측). 서버 writer 도
+ // fail-safe 로 막지만, 뷰가 진실을 들고 있어야 배지/버튼 상태가 맞는다.
+ anchorPicks[direction] = { state: pick.state, index: Number(pick.index) };
+ if (pick.stale) {
+ anchorPicks[direction].stale = true;
+ anchorPicks[direction].stale_reason = pick.stale_reason || "regenerated";
+ }
+ }
+ }
+ // 해석 실패(지정이 사라진 프레임을 가리킴 등)는 조용히 넘기지 않는다 — 이 상태로
+ // 생성하면 엔진이 fail-loud 하므로 사용자가 지금 알아야 한다. 단 `anchorPending`
+ // (그 방향 앵커 행을 아직 안 뽑았다)은 **정상 작업 구간**이라 오류로 칠하지 않는다 —
+ // 그러면 생성 중인 모든 런에 빨간 배너가 뜬다 (validator 검증 2026-07-25 파생 증상 2).
+ const broken = run.directionGroups.filter((g) => g.anchorError && !g.anchorPending);
+ if (broken.length) {
+ healParts.push(...broken.map((g) => STR[lang].anchorError(g.direction, g.anchorError)));
+ }
+ }
+ // 컬러웨이 채택은 트리 배지도 쓴다 — 트리를 그리기 전에 진실을 세운다.
+ seedRecolorPick(run);
+ await seedTreeProgress();
+ renderPipelineTree();
+ setInterval(pollTreeProgress, 3000);
+ if (run.baseUrl) renderBaseRow();
+ // 방향 계약 런: 방향별 그룹(앵커 우선) + 미러 방향(생성 생략) 스트립으로 렌더.
+ // 계약 없는 런은 기존 flat 순서 그대로.
+ if (run.directionGroups && run.directionGroups.length) {
+ const byName = new Map(run.states.map((s) => [s.name, s]));
+ const rendered = new Set();
+ for (const group of run.directionGroups) {
+ const headEl = document.createElement("div");
+ headEl.className = "dir-head" + (group.mirrorOf ? " dir-mirror" : "");
+ headEl.textContent = group.mirrorOf
+ ? STR[lang].dirMirrorLabel(group.direction, group.mirrorOf)
+ : STR[lang].dirGroupLabel(group.direction);
+ document.getElementById("states").appendChild(headEl);
+ for (const name of group.states) {
+ const st = byName.get(name);
+ if (st) { renderState(st); rendered.add(name); }
+ }
+ }
+ // 방향 접두사에 안 걸린 잔여 상태는 끝에 그대로 (숨기지 않는다)
+ for (const state of run.states) if (!rendered.has(state.name)) renderState(state);
+ } else {
+ for (const state of run.states) renderState(state);
+ }
+ syncUnfakeControls();
+ syncGridControls();
+ refreshVariantImages();
+ // 레거시 테이크 방식 호흡의 자가 이전 (시퀀스 위상 프레임 → 사이드카 레이어)
+ {
+ const migrated = run.states.filter((s) => migrateLegacyBreathe(s.name));
+ if (migrated.length) {
+ for (const s of migrated) rebuildState(s.name);
+ scheduleSave();
+ setStatus(`호흡 레이어로 자동 이전: ${migrated.map((s) => s.name).join(", ")}`);
+ }
+ }
+ // breathe 가 켜진 채 anatomy 캐시 없이 로드된 줄: 서버에 물어 채운다. 안 그러면 미리보기가
+ // 조용히 정지 그림을 그려 "체크됐는데 안 쉰다" 가 된다 (굽기는 서버가 재서 정상). 검출은
+ // 서버 SSoT 라 로컬 추정하지 않는다 — 실패하면 loud 하게 알린다 (조용한 폴백 금지).
+ {
+ const need = run.states.filter((s) => {
+ const b = entries[s.name] && entries[s.name].breathe;
+ return b && !b.anatomy;
+ });
+ if (need.length) {
+ const filled = [];
+ await Promise.all(need.map(async (s) => {
+ try { if (await ensureBreatheAnatomy(s.name)) filled.push(s.name); }
+ catch (err) {
+ setStatus(`${s.name} 호흡 해부 로드 실패 — 미리보기가 숨쉬지 않는다: ${err.message}`, "err");
+ }
+ }));
+ if (filled.length) {
+ for (const n of filled) rebuildState(n);
+ scheduleSave();
+ }
+ }
+ }
+ // 세대 불일치로 서버가 이번 로드에서 무효화한 행 알림 — 조용한 소실 금지.
+ // 로드는 아무것도 쓰지 않으므로 이 시점엔 아직 잃은 것이 없다. 원문이 실제로 덮이는
+ // 순간(다음 저장) writer 가 curation.stale-<hash>.json 을 남긴다 — 복원 경로는 그거다.
+ if (run.curationDropped && run.curationDropped.length) {
+ const note = document.createElement("div");
+ note.id = "curation-dropped-note";
+ note.textContent = STR[lang].curationDropped(run.curationDropped);
+ const dismiss = document.createElement("button");
+ dismiss.type = "button";
+ dismiss.className = "ghost";
+ dismiss.textContent = "✕";
+ dismiss.addEventListener("click", () => note.remove());
+ note.appendChild(dismiss);
+ document.body.prepend(note);
+ }
+ await renderFinalAtlas(run.atlas);
+ // 컬러웨이 비교·픽 섹션 — 베이크 산출물(`<run>/variants/`)이 있는 런에만 뜬다.
+ renderRecolorVariants(run.recolor);
+ // 힌트바를 우측 본문 컬럼 끝으로 이동 — 좌측 스플릿이 페이지 바닥까지 유지되게
+ document.getElementById("states").appendChild(document.getElementById("hintbar"));
+ // 표시 샘플링 판정은 기하가 바뀔 때마다 다시 답해야 한다 (창 크기·패널 폭이
+ // 바뀌면 같은 이미지가 확대에서 축소로 넘어간다) — sizePxGrids 가 그 갱신 지점.
+ let resizeTimer = null;
+ window.addEventListener("resize", () => {
+ clearTimeout(resizeTimer);
+ resizeTimer = setTimeout(sizePxGrids, 120);
+ });
+ installPixelScalingLoadHook();
+ syncPixelScaling();
+ if (healParts.length) {
+ const hadFailure = (run.heal && run.heal.failed && run.heal.failed.length)
+ || (run.directionGroups || []).some((g) => g.anchorError && !g.anchorPending);
+ setStatus(healParts.join(" · "), hadFailure ? "err" : "ok");
+ } else {
+ setStatus(run.curation && Object.keys(run.curation.states || {}).length ? t("loaded") : t("ready"));
+ }
+}
+
+boot();
diff --git a/sprite_gen/serve/curator/src/breathe.js b/sprite_gen/serve/curator/src/breathe.js
new file mode 100644
index 0000000..4a44448
--- /dev/null
+++ b/sprite_gen/serve/curator/src/breathe.js
@@ -0,0 +1,607 @@
+// SPDX-License-Identifier: Apache-2.0
+// curator/breathe.js — 결정론 호흡 후처리 레이어 (사이드카) — 토글·위상·봉투 워프 미러
+// 로드 순서 SSoT = index.html (classic script 전역 어휘 공유; 빌드 스텝 없음)
+//
+// 호흡은 프레임 선택(깜빡임)과 직교하는 변조 레이어다 (maintainer 확정 2026-07-18).
+// truth = entries[state].breathe = {depth, breaths, lag, rigid_row, anatomy} | null.
+//
+// **검출은 여기서 하지 않는다** (maintainer 결정 2026-07-25 b안). 목 병목·대칭 눈쌍·부속
+// 판정은 서버(`sprite_gen/anatomy.py`)가 GET /api/breathe-anatomy 로 한 번 돌려
+// 사이드카에 숫자로 얼려두고, 이 파일은 그 숫자로 **워프만** 미러링한다. 검출까지
+// JS 가 재구현하면 굽기와 미리보기의 진실이 둘로 갈라진다.
+//
+// 미러 대상은 sprite_gen/breathe.py 의 fit_breathe_pattern / phase_frame 이다.
+// 같은 봉투·같은 정수 연산이라 프리뷰와 굽기가 픽셀 동일해야 한다.
+
+// 서버 상수 미러 (sprite_gen/breathe.py)
+const BREATHE_TAPER = 0.055;
+const BREATHE_FOOT = 0.28;
+const BREATHE_MAX_ROW_STRAIN = 0.25;
+// 사이드카 허용 범위 — 파이썬 curation.BREATHE_*_MAX 미러. UI 가 이 밖의 값을 만들면
+// 굽기가 loud reject 하므로 컨트롤이 여기서 막아야 한다.
+const BREATHE_DEPTH_MAX = 0.20;
+const BREATHE_BREATHS_MAX = 8;
+const BREATHE_LAG_MAX = 0.45;
+
+// 굽기가 거부하는 프레임은 미리보기도 만들어 주지 않는다.
+// 파이썬은 셀 밖으로 나간 불투명 픽셀을 세어 SystemExit 으로 멈추고 행당 변형 상한도
+// 강제한다. 미러가 그걸 안 지키면 (a) 프리뷰는 멀쩡한데 굽기가 죽고 (b) row-export 의
+// WebM/MP4 는 서버를 안 거치므로 **잘린 영상이 그대로 사용자 손에 들어간다**
+// (validator 실측 2026-07-25: 여백 0 셀에서 불투명 73px 소실, 오류 0건).
+class BreatheRefused extends Error {}
+
+let pendingBreathe = false; // 호흡 라벨 → 줌 모달 오픈 시 호흡 모드 진입 플래그
+
+function stateBreathe(stateName) {
+ const e = entries[stateName];
+ return e && e.breathe ? e.breathe : null;
+}
+
+// 서버 fit_breathe_pattern 미러 — 위상은 [0,1) 연속값이다 (구 정수 분할선 단계 아님).
+// breaths 회가 시퀀스 안에서 정확히 반복되므로 루프 이음매도 등분 보정도 없다.
+function breathePattern(cfg, seqLen) {
+ if (!seqLen || seqLen <= 0) return [];
+ const breaths = Math.max(1, cfg.breaths || 1);
+ // 분자를 정수 나머지로 **먼저** 접는다 — 파이썬 fit_breathe_pattern 과 같은 식이어야
+ // 같은 double 이 나온다. `(i*breaths/seqLen) % 1` 로 쓰면 수학적으로 같은 위상이 서로
+ // 다른 double 이 되어 프리뷰가 굽기와 갈린다 (validator 실측 2026-07-25: seq=30 breaths=7
+ // 에서 slot 24 py=0.6 vs js=0.5999999999999996 → 4바이트 차이).
+ return Array.from({ length: seqLen }, (_, i) => ((i * breaths) % seqLen) / seqLen);
+}
+
+// 연속 위상이라 요청 횟수가 그대로 성립한다 (물리 클램프 없음).
+function breatheFitCount(cfg, seqLen) {
+ if (!seqLen || seqLen <= 0) return 0;
+ return Math.max(1, cfg.breaths || 1);
+}
+
+function breatheWave(t) {
+ return 0.86 * Math.sin(2 * Math.PI * t) + 0.14 * Math.sin(4 * Math.PI * t);
+}
+
+function breatheSmoothstep(a, b, x) {
+ if (b <= a) return x >= b ? 1 : 0;
+ const u = Math.min(1, Math.max(0, (x - a) / (b - a)));
+ return u * u * (3 - 2 * u);
+}
+
+// 변형 강도 봉투 + 진폭 정규화 계수 (서버 envelope() 미러).
+function breatheEnvelope(anat) {
+ const height = anat.height;
+ const ru = 1 - anat.rigid_row / Math.max(1, height - 1);
+ const band = Math.max(1.5, BREATHE_TAPER * height) / Math.max(1, height);
+ const footTop = BREATHE_FOOT * ru;
+ const env = (u) =>
+ breatheSmoothstep(0, footTop, u) * (1 - breatheSmoothstep(ru - band, ru + band, u));
+ let total = 0;
+ for (let j = 0; j < height; j++) total += env(j / Math.max(1, height - 1));
+ const basisRows = Math.max(1, height - anat.basis_row);
+ return { env, ru, norm: total > 1e-6 ? basisRows / total : 0 };
+}
+
+// 부속 보호 가중 — 1 이면 그 열은 가로로 안 늘어난다 (밀리기만 한다).
+// 수동 밴드(영역 UI)는 무조건 켜지고 램프를 밴드 자체에 앵커한다 — 파이썬 protect 미러
+// (자동 램프는 max_half 앵커라 블롭에서 밴드 조정이 무력했다, 2026-07-30).
+function breatheProtect(anat) {
+ if (anat.torso_source === "manual") {
+ const mt0 = anat.torso_half;
+ const mt1 = mt0 + 2;
+ return (x) => breatheSmoothstep(mt0, mt1, Math.abs(x - anat.axis_x));
+ }
+ const hasAppendage = anat.max_half >= 1.3 * anat.torso_half;
+ if (!hasAppendage) return () => 0;
+ const t0 = anat.torso_half * 1.15;
+ const t1 = Math.max(t0 + 1, anat.max_half * 0.95);
+ return (x) => breatheSmoothstep(t0, t1, Math.abs(x - anat.axis_x));
+}
+
+// 파이썬 `breathe._fnv1a` / `anatomy_fingerprint` 미러. 미러가 지문을 **직접 계산**해야
+// 자기가 그리는 프레임이 얼린 해부와 맞는지 확인할 수 있다. 못 하면 굽기만 자가 복구하고
+// 프리뷰는 낡은 숫자로 계속 그린다 (validator 실측 2026-07-25: 픽셀 편집 후 최대 617바이트,
+// 불투명 픽셀 수까지 불일치). SHA-256 을 안 쓰는 이유는 브라우저에서 동기로 못 구해서다.
+function breatheFnv1a(text) {
+ // 파이썬은 `key.encode("utf-8")` 을 해시한다 — 여기도 **UTF-8 바이트**여야 한다.
+ // `charCodeAt` 로 하면 상태 이름에 비-ASCII 가 한 글자만 들어와도 갈린다.
+ const data = new TextEncoder().encode(text);
+ let h = 2166136261;
+ for (let i = 0; i < data.length; i++) h = Math.imul(h ^ data[i], 16777619) >>> 0;
+ return h;
+}
+
+// 파이썬 `breathe._num` 미러. `toFixed(6)` 은 파이썬 `f"{v:.6f}"` 와 경계에서 갈리고
+// (JS 는 이진값, 파이썬은 십진 표현 기준 반올림) 지수 표기도 다르다. 곱·합·floor 만 쓰면
+// 양쪽 다 IEEE754 double 이라 같은 입력에 반드시 같은 결과가 나온다.
+function breatheNum(v) {
+ if (v === null || v === undefined) return "~";
+ if (typeof v === "boolean") return v ? "1" : "0";
+ if (typeof v === "number") return String(Math.floor(v * 1000000.0 + 0.5));
+ return String(v);
+}
+
+function breatheCanon(v) {
+ if (Array.isArray(v)) return "[" + v.map(breatheCanon).join(",") + "]";
+ if (v && typeof v === "object") {
+ // 파이썬은 `sorted(key=str)`, JS 는 UTF-16 코드유닛 정렬 — 실제 키(`"x,y"`, 변형
+ // 필드명)는 전부 ASCII 라 같은 순서다. 비-ASCII 키가 생기면 이 가정이 깨진다.
+ return "{" + Object.keys(v).sort().map((k) => `${k}=${breatheCanon(v[k])}`).join(",") + "}";
+ }
+ return breatheNum(v);
+}
+
+// 파이썬 `breathe.reference_key` 미러 — **픽셀을 안 읽는다.**
+// 굽기는 BICUBIC(`apply_transform`), 웹뷰 캔버스는 NEAREST 라 같은 원본·같은 변형에도
+// 두 쪽이 만드는 그림이 다르다. 결과 픽셀을 해시하던 옛 지문이 회전·확대가 걸린 줄에서
+// 영구 불일치였던 이유다 (validator 실측 2026-07-26).
+// 파이썬 `curation.normalize_transform` 미러 — 항상 7키 전체.
+function breatheNormalizeTransform(raw) {
+ const t = raw && typeof raw === "object" ? raw : {};
+ const num = (v, d) => (v === undefined || v === null ? d : Number(v));
+ return { rotate: num(t.rotate, 0), scale: num(t.scale, 1), dx: num(t.dx, 0),
+ dy: num(t.dy, 0), shx: num(t.shx, 0), shy: num(t.shy, 0), flipX: t.flipX ? 1 : 0 };
+}
+
+function breatheReferenceKeyOf(p) {
+ return ["breathe-ref-v1", String(p.state), String(p.variant), String(p.requestStamp),
+ String(p.sourceIndex), String(p.sourceStamp),
+ breatheCanon(p.pixelOps || {}),
+ breatheCanon(breatheNormalizeTransform(p.transform))].join("|");
+}
+
+function breatheFingerprint(key) {
+ const parts = key.split("|");
+ const variant = parts.length > 5 ? parts[2] : "?";
+ const index = parts.length > 5 ? parts[4] : "?";
+ return `${variant}:${index}:${breatheFnv1a(key).toString(16).padStart(8, "0")}`;
+}
+
+function breatheSolidBox(data, w, h) {
+ let x0 = w, y0 = h, x1 = 0, y1 = 0;
+ for (let y = 0; y < h; y++) {
+ for (let x = 0; x < w; x++) {
+ if (data[(y * w + x) * 4 + 3] >= 128) {
+ if (x < x0) x0 = x;
+ if (y < y0) y0 = y;
+ if (x + 1 > x1) x1 = x + 1;
+ if (y + 1 > y1) y1 = y + 1;
+ }
+ }
+ }
+ return x1 > x0 && y1 > y0 ? [x0, y0, x1, y1] : null;
+}
+
+// 줄 단위 신선도 검사 — **기준 프레임 하나**에만 건다.
+//
+// 굽기는 줄의 첫 프레임으로 해부를 확정하고(`bake_breathe_sequence` 의 `images[0]`) 그
+// 한 벌로 모든 프레임을 굽는다. 그래서 프레임마다 지문을 보면 안 된다 — 깜빡임처럼
+// 정상적으로 다른 프레임까지 거부해 프리뷰가 통째로 죽는다. 봐야 하는 건 "얼린 해부가
+// **지금의 기준 프레임**에서 나온 것인가" 하나다.
+//
+// 이게 없으면 큐레이터 픽셀 편집기로 도트를 찍기만 해도(호흡을 건드릴 필요조차 없다)
+// 굽기는 자가 복구하고 프리뷰는 낡은 숫자로 계속 그린다 — 실측 최대 617바이트, 불투명
+// 픽셀 수까지 불일치 (validator 2026-07-25).
+function breatheAssertFresh(referenceKey, cfg) {
+ const anat = cfg && cfg.anatomy;
+ if (!anat) return; // 해부가 아예 없으면 굽기가 매번 재검출한다
+ if (!anat.fingerprint) {
+ // 해부는 있는데 지문이 없다 = **확인할 수 없다.** 조용히 통과시키면 낡은 숫자로
+ // 그리게 된다 — `refreshAnatomy` 가 실패해 지문만 무효화한 상태가 정확히 이 모양이고,
+ // 그때 미러가 통과해 굽기와 164바이트 갈렸다 (validator 실측 2026-07-26).
+ throw new BreatheRefused(
+ "해부에 지문이 없다 — 이 프레임에서 나온 값인지 확인할 수 없다. 해부를 갱신해라.");
+ }
+ if (!referenceKey) {
+ // 키를 못 만든다 = 기준 프레임의 정체를 모른다 (스탬프 없는 프레임, 빈 재생목록).
+ throw new BreatheRefused("기준 프레임 키를 만들 수 없다 — 신선도 확인 불가.");
+ }
+ const now = breatheFingerprint(referenceKey);
+ if (now !== anat.fingerprint) {
+ throw new BreatheRefused(
+ `해부가 지금의 기준 프레임에서 나온 게 아니다 — 얼린 지문 ${anat.fingerprint} vs `
+ + `현재 ${now}. 굽기는 다시 재서 굽는다. 해부를 갱신해야 프리뷰가 같아진다.`);
+ }
+}
+
+// 프리뷰 전용 래퍼 — 굽기가 거부하는 설정이면 **원본을 그리고 loud 하게 알린다.**
+// 내보내기(row-export)는 이 래퍼를 쓰지 않는다: 거기서는 예외가 그대로 올라가 파일이
+// 만들어지기 전에 중단돼야 한다. 프리뷰는 타이머 루프라 예외가 올라가면 재생이 죽으므로
+// 잡되, **조용히 워프된 그림을 보여주지는 않는다** — 못 굽는 설정이면 못 굽는 대로 보인다.
+let _breatheWarned = "";
+function breatheComposeForPreview(base, cfg, phase, referenceKey) {
+ // `reference` 는 **필수 인자**다. 선택으로 두면 호출부가 빠뜨렸을 때 신선도 검사가
+ // 조용히 건너뛰어져, 같은 웹뷰의 두 화면이 정반대로 행동한다 — 줄 카드는 거부하는데
+ // 호흡 편집 모달은 낡은 숫자로 그렸다 (validator 실측 2026-07-26: 12/12 위상 갈림, 알림 0건).
+ //
+ // 인자를 **안 넘긴 것**(프로그래머 실수)과 넘겼는데 **빈 값**(상태가 아직 안 실림)은
+ // 다르다: 전자는 하드 에러, 후자는 "확인할 수 없으니 워프하지 않는다" 로 부드럽게 거부.
+ if (arguments.length < 4) {
+ throw new Error("breatheComposeForPreview: referenceKey 인자가 필요하다 (신선도 검사)");
+ }
+ try {
+ breatheAssertFresh(referenceKey, cfg);
+ return breatheComposite(base, cfg, phase);
+ } catch (err) {
+ if (!(err instanceof BreatheRefused)) throw err;
+ if (_breatheWarned !== err.message) {
+ _breatheWarned = err.message;
+ setStatus(`호흡 미리보기 중단 — 이 설정은 굽기에서도 거부된다: ${err.message}`, "err");
+ }
+ return base;
+ }
+}
+
+// 서버 phase_frame 미러 — 캔버스 크기 불변, 발바닥 고정.
+// 세로는 행 국소 배율 누적, 가로는 행 안 밀도 적분(단조 → 접힘 없음). 전부 정수 연산.
+function breatheComposite(base, cfg, phase) {
+ const w = base.width;
+ const h = base.height;
+ const out = document.createElement("canvas");
+ out.width = w;
+ out.height = h;
+ const ctx = out.getContext("2d");
+ ctx.imageSmoothingEnabled = false;
+ const anat = cfg && cfg.anatomy;
+ // `rigid_row` 는 사람의 의도(입력)이고 `anatomy` 는 거기서 파생된 캐시다. 굽기는 둘이
+ // 어긋나면 재검출해 의도를 따르는데(`resolve_anatomy` 의 stale_override), 미러는 검출을
+ // 못 하므로 **낡은 캐시로 그리면 거짓말이 된다.** 그래서 거부한다 — 프리뷰는 원본을
+ // 보여주고 사용자는 해부를 갱신하라는 말을 듣는다 (validator 실측 2026-07-25: override 31
+ // 을 굽기는 따르고 미러는 23 으로 그려 12위상 전부, 최대 164바이트 갈렸다).
+ if (anat && cfg.rigid_row != null && Number(cfg.rigid_row) !== anat.rigid_row) {
+ throw new BreatheRefused(
+ `강체 경계가 어긋난다 — 사이드카 rigid_row ${cfg.rigid_row} vs 해부 ${anat.rigid_row}. `
+ + `굽기는 ${cfg.rigid_row} 로 다시 재서 굽는다. 해부를 갱신해야 프리뷰가 같아진다.`);
+ }
+ // axis_x / torso_half 도 rigid_row 와 같은 지위의 사람 의도 입력이다 (영역 UI 2026-07-30).
+ // 캐시가 의도와 어긋나면 낡은 숫자로 그리지 않는다 — 굽기는 의도로 다시 재서 굽는다.
+ if (anat && cfg.axis_x != null && Number(cfg.axis_x) !== anat.axis_x) {
+ throw new BreatheRefused(
+ `몸통 축이 어긋난다 — 사이드카 axis_x ${cfg.axis_x} vs 해부 ${anat.axis_x}. `
+ + `해부를 갱신해야 프리뷰가 같아진다.`);
+ }
+ if (anat && cfg.torso_half != null && Number(cfg.torso_half) !== anat.torso_half) {
+ throw new BreatheRefused(
+ `몸통 반폭이 어긋난다 — 사이드카 torso_half ${cfg.torso_half} vs 해부 ${anat.torso_half}. `
+ + `해부를 갱신해야 프리뷰가 같아진다.`);
+ }
+ if (!anat) {
+ // 해부 숫자가 아직 없다 — 서버가 채우기 전까지는 원본을 그대로 보여준다.
+ // 여기서 대충 추정해 그리면 굽기와 다른 그림을 보여주게 된다 (조용한 폴백 금지).
+ ctx.drawImage(base, 0, 0);
+ return out;
+ }
+ const srcData = base.getContext("2d").getImageData(0, 0, w, h);
+ const src = srcData.data;
+ const box = breatheSolidBox(src, w, h);
+ if (!box) {
+ ctx.drawImage(base, 0, 0);
+ return out;
+ }
+ const [bx0, by0, bx1, by1] = box;
+ const width = bx1 - bx0;
+ const height = by1 - by0;
+ const anchorX = bx0 + anat.axis_x;
+ const baseline = by1;
+ const { env, ru, norm } = breatheEnvelope(anat);
+ const pOf = breatheProtect(anat);
+ const depth = cfg.depth || 0.06;
+ // 가로 독립 진폭 — null/undefined 는 depth 따름(레거시 동일), 0 은 가로 항등 (파이썬 미러).
+ const depthX = cfg.depth_x == null ? depth : Number(cfg.depth_x);
+ let peak = 0;
+ for (let j = 0; j < anat.height; j++) peak = Math.max(peak, env(j / Math.max(1, anat.height - 1)));
+ for (const [axis, d] of [["depth", depth], ["depth_x", depthX]]) {
+ const strain = d * norm * peak;
+ if (strain > BREATHE_MAX_ROW_STRAIN) {
+ throw new BreatheRefused(
+ `행당 변형(${axis}) ${strain.toFixed(3)} > 상한 ${BREATHE_MAX_ROW_STRAIN} — 변형 구간이 너무 좁다 `
+ + `(강체 경계 ${anat.rigid_row}/${anat.height}). ${axis} 를 낮추거나 경계를 올려라.`);
+ }
+ }
+ const lag = cfg.lag == null ? 0.1 : cfg.lag;
+ const gain = (u, d) => {
+ const e = env(u);
+ if (e <= 0) return 0;
+ return d * norm * breatheWave(phase - lag * Math.min(1, u / Math.max(1e-6, ru))) * e;
+ };
+
+ const heights = [];
+ let acc = 0;
+ for (let j = 0; j < height; j++) {
+ const g = gain(1 - j / Math.max(1, height - 1), depth);
+ acc += g === 0 ? 1 : 1 / (1 + g);
+ heights.push(acc);
+ }
+ const total = Math.max(1, Math.round(acc));
+
+ const outImg = ctx.createImageData(w, h);
+ const od = outImg.data;
+ let yCursor = baseline - total;
+ let prev = 0;
+ let clipped = 0;
+ let deformed = false; // 이 위상에서 변형이 실제로 일어났나 (다듬기 게이트, 파이썬 미러)
+ for (let j = 0; j < height; j++) {
+ const u = 1 - j / Math.max(1, height - 1);
+ const cur = Math.round(heights[j]);
+ const reps = Math.max(0, cur - prev);
+ prev = cur;
+ if (reps === 0) continue;
+ const g = gain(u, depthX); // 가로 성분 — 독립 진폭 (depth_x)
+ if (reps !== 1) deformed = true; // 행 복제/삭제 = 세로 변형이 실재
+ let rowMap;
+ if (g === 0) {
+ // 변형 없음 = 원본 위치 그대로 (축 고정점 사상의 g->0 극한과 동일)
+ rowMap = Array.from({ length: width }, (_, i) => [bx0 + i, i]);
+ } else {
+ deformed = true; // 가로 사상 변형이 실재
+ const edge = [0];
+ for (let i = 0; i < width; i++) edge.push(edge[i] + Math.max(0.05, 1 + g * (1 - pOf(i))));
+ const origin = edge[anat.axis_x]; // 축이 고정점 — 여기가 anchorX 에 박힌다
+ const lo = Math.round(edge[0] - origin);
+ const hi = Math.round(edge[width] - origin);
+ rowMap = [];
+ let i = 0;
+ for (let ox = lo; ox < hi; ox++) {
+ while (i < width - 1 && edge[i + 1] - origin <= ox) i += 1;
+ rowMap.push([anchorX + ox, i]);
+ }
+ // 외곽선 보존 (파이썬 _warp 미러) — 가로 축소 위상에서 실루엣 양끝 열이 떨어져
+ // 1px 외곽선이 사라지는 것을 막는다. 이 행의 최말단 불투명 소스 열(= 외곽선)을
+ // 출력 양끝 불투명 픽셀에 그대로 실어 항상 1px 외곽선을 남긴다.
+ const rowOpaque = (si) => src[((by0 + j) * w + (bx0 + si)) * 4 + 3];
+ let opLo = -1, opHi = -1;
+ for (let k = 0; k < width; k++) if (rowOpaque(k)) { if (opLo < 0) opLo = k; opHi = k; }
+ if (opHi >= 0 && rowMap.length) {
+ for (let k = rowMap.length - 1; k >= 0; k--) {
+ if (rowOpaque(rowMap[k][1])) { rowMap[k] = [rowMap[k][0], opHi]; break; }
+ }
+ for (let k = 0; k < rowMap.length; k++) {
+ if (rowOpaque(rowMap[k][1])) { rowMap[k] = [rowMap[k][0], opLo]; break; }
+ }
+ }
+ }
+ for (let r = 0; r < reps; r++) {
+ const yy = yCursor + r;
+ for (const [ox, si] of rowMap) {
+ const s4 = ((by0 + j) * w + (bx0 + si)) * 4;
+ if (!src[s4 + 3]) continue;
+ if (yy < 0 || yy >= h || ox < 0 || ox >= w) { clipped += 1; continue; }
+ const d4 = (yy * w + ox) * 4;
+ od[d4] = src[s4];
+ od[d4 + 1] = src[s4 + 1];
+ od[d4 + 2] = src[s4 + 2];
+ od[d4 + 3] = src[s4 + 3];
+ }
+ }
+ yCursor += reps;
+ }
+ if (clipped) {
+ throw new BreatheRefused(
+ `늘어난 프레임이 셀 밖으로 나가 불투명 픽셀 ${clipped}개가 잘린다 `
+ + `(셀 ${w}x${h}). 셀 여백을 늘리거나 depth 를 낮춰라.`);
+ }
+ if (deformed) breatheThinOutline(od, w, h);
+ ctx.putImageData(outImg, 0, 0);
+ return out;
+}
+
+// 워프된 실루엣 외곽선 2px 를 **안쪽점 기준** 1px 로 정규화 — 파이썬 `_thin_outline_1px`
+// 의 바이트 동일 미러 (고정점 반복: 한 패스의 제거가 새 돌출점을 만들 수 있다).
+// 패턴1: 끝 '어두움-어두움-내부색' → 바깥 픽셀 제거(알파 0). 패턴2: 어두운 끝점이
+// 위아래 행 끝보다 정확히 1px 바깥으로 튄 단독 돌출점 → 제거하고 안쪽 자리에 그 색을
+// 그린다(가로 한정 — 세로 1px 계단은 작가 의도와 구분 불가). 안전 필터: 제거로 내부색
+// 노출·어두운 선 중간 구멍이 생기는 후보는 제외, 고정점까지 재평가.
+function breatheThinOutline(od, w, h) {
+ while (breatheThinOutlinePass(od, w, h) > 0) { /* 불투명 픽셀 단조 감소 — 종료 보장 */ }
+}
+
+function breatheThinOutlinePass(od, w, h) {
+ const snap = Uint8ClampedArray.from(od);
+ const op = (x, y) => x >= 0 && x < w && y >= 0 && y < h && snap[(y * w + x) * 4 + 3] !== 0;
+ const dk = (x, y) => {
+ if (!op(x, y)) return false;
+ const i = (y * w + x) * 4;
+ return (0.299 * snap[i] + 0.587 * snap[i + 1] + 0.114 * snap[i + 2]) < 60;
+ };
+ // 후보: "x,y" -> 'v'|'h' (같은 픽셀이 양축 후보면 먼저 등록된 세로가 이긴다 — 파이썬 setdefault)
+ const cand = new Map();
+ const put = (x, y, ax) => { const k = x + "," + y; if (!cand.has(k)) cand.set(k, ax); };
+ for (let x = 0; x < w; x++) {
+ let t0 = -1, b0 = -1;
+ for (let y = 0; y < h; y++) if (op(x, y)) { if (t0 < 0) t0 = y; b0 = y; }
+ if (t0 < 0) continue;
+ if (t0 + 2 <= b0 && dk(x, t0) && dk(x, t0 + 1) && op(x, t0 + 2) && !dk(x, t0 + 2)) put(x, t0, "v");
+ if (b0 - 2 >= t0 && dk(x, b0) && dk(x, b0 - 1) && op(x, b0 - 2) && !dk(x, b0 - 2)) put(x, b0, "v");
+ }
+ const rowLo = new Map();
+ const rowHi = new Map();
+ for (let y = 0; y < h; y++) {
+ let l0 = -1, r0 = -1;
+ for (let x = 0; x < w; x++) if (op(x, y)) { if (l0 < 0) l0 = x; r0 = x; }
+ if (l0 < 0) continue;
+ rowLo.set(y, l0); rowHi.set(y, r0);
+ if (l0 + 2 <= r0 && dk(l0, y) && dk(l0 + 1, y) && op(l0 + 2, y) && !dk(l0 + 2, y)) put(l0, y, "h");
+ if (r0 - 2 >= l0 && dk(r0, y) && dk(r0 - 1, y) && op(r0 - 2, y) && !dk(r0 - 2, y)) put(r0, y, "h");
+ }
+ const moves = new Map(); // "x,y"(안쪽) -> 스냅샷 색 인덱스
+ for (const y of [...rowLo.keys()].sort((a, b) => a - b)) {
+ const m = rowLo.get(y);
+ const upLo = rowLo.get(y - 1), dnLo = rowLo.get(y + 1);
+ if (upLo !== undefined && dnLo !== undefined && Math.min(upLo, dnLo) - m === 1
+ && dk(m, y) && op(m + 1, y)) {
+ put(m, y, "h");
+ if (!dk(m + 1, y)) moves.set((m + 1) + "," + y, (y * w + m) * 4);
+ }
+ const r = rowHi.get(y);
+ const upHi = rowHi.get(y - 1), dnHi = rowHi.get(y + 1);
+ if (upHi !== undefined && dnHi !== undefined && r - Math.max(upHi, dnHi) === 1
+ && dk(r, y) && op(r - 1, y)) {
+ put(r, y, "h");
+ if (!dk(r - 1, y)) moves.set((r - 1) + "," + y, (y * w + r) * 4);
+ }
+ }
+ // 안전 필터 고정점 (파이썬과 동일한 정렬 순회·재시작)
+ const drop = new Set(cand.keys());
+ const keyCmp = (a, b) => {
+ const [ax, ay] = a.split(",").map(Number);
+ const [bx, by] = b.split(",").map(Number);
+ return ax !== bx ? ax - bx : ay - by;
+ };
+ let changed = true;
+ while (changed) {
+ changed = false;
+ for (const k of [...drop].sort(keyCmp)) {
+ const [x, y] = k.split(",").map(Number);
+ const neigh = cand.get(k) === "h" ? [[x, y - 1], [x, y + 1]] : [[x - 1, y], [x + 1, y]];
+ let keptDark = 0;
+ let ok = true;
+ for (const [nx, ny] of neigh) {
+ if (!op(nx, ny) || drop.has(nx + "," + ny)) continue;
+ if (dk(nx, ny)) keptDark += 1;
+ else { ok = false; break; }
+ }
+ if (!ok || keptDark >= 2) { drop.delete(k); changed = true; break; }
+ }
+ }
+ for (const k of drop) {
+ const [x, y] = k.split(",").map(Number);
+ const d = (y * w + x) * 4;
+ od[d] = 0; od[d + 1] = 0; od[d + 2] = 0; od[d + 3] = 0;
+ }
+ let applied = drop.size;
+ for (const [k, s] of moves) {
+ if (drop.has(k)) continue;
+ const [x, y] = k.split(",").map(Number);
+ const d = (y * w + x) * 4;
+ od[d] = snap[s]; od[d + 1] = snap[s + 1]; od[d + 2] = snap[s + 2]; od[d + 3] = snap[s + 3];
+ applied += 1;
+ }
+ return applied;
+}
+
+// 첫 활성화 기본값: 서버에 해부를 물어본다 (검출 SSoT = 서버).
+// 예전엔 여기서 JS 가 어깨/허리선을 직접 추정했지만, 그 추정이 굽기 쪽 검출과 달라
+// 미리보기와 결과가 갈라졌다. 이제 숫자는 한 곳에서만 나온다.
+async function fetchBreatheAnatomy(stateName, rigidRow, axisX, torsoHalf) {
+ const q = new URLSearchParams({ state: stateName });
+ if (rigidRow != null) q.set("rigid_row", String(rigidRow));
+ if (axisX != null) q.set("axis_x", String(axisX));
+ if (torsoHalf != null) q.set("torso_half", String(torsoHalf));
+ const res = await fetch(`/api/breathe-anatomy?${q}`);
+ const body = await res.json();
+ if (!res.ok || body.error) throw new Error(body.error || `HTTP ${res.status}`);
+ return body;
+}
+
+async function defaultBreatheConfig(stateName) {
+ // 같은 런에서 사람이 이미 튜닝한 세기를 물려받는다 (사람 판단 > 기본값).
+ const sibling = run.states
+ .map((s) => (s.name !== stateName && entries[s.name] ? entries[s.name].breathe : null))
+ .find((b) => b && typeof b.depth === "number");
+ const { anatomy, defaults } = await fetchBreatheAnatomy(stateName);
+ return {
+ depth: sibling ? sibling.depth : defaults.depth,
+ depth_x: sibling && sibling.depth_x != null ? sibling.depth_x : null,
+ breaths: sibling ? sibling.breaths : defaults.breaths,
+ lag: sibling ? sibling.lag : defaults.lag,
+ rigid_row: null,
+ anatomy,
+ };
+}
+
+// 사이드카에서 breathe 가 켜진 채 로드됐지만 anatomy 캐시가 비어 있으면(뷰 없이
+// 에이전트/CLI 가 breathe 만 쓴 런, 레거시 이전 직후) 미리보기 미러는 해부를 로컬로 못
+// 재 조용히 정지 그림을 그린다 (breatheComposite: !anat → base 원본). 굽기는 서버가
+// 매번 재서 숨쉬는데 미리보기만 죽어 "체크됐는데 안 쉰다" 가 된다. 로드 시 서버에 한 번
+// 물어 캐시를 채운다 — 토글 ON(defaultBreatheConfig) 과 같은 검출 경로다(SSoT = 서버).
+async function ensureBreatheAnatomy(stateName) {
+ const e = entries[stateName];
+ const cfg = e && e.breathe;
+ if (!cfg || cfg.anatomy) return false;
+ const { anatomy } = await fetchBreatheAnatomy(stateName, cfg.rigid_row, cfg.axis_x, cfg.torso_half);
+ // 재진입/경쟁 사이 다른 경로가 이미 채웠으면 덮지 않는다.
+ if (e.breathe && !e.breathe.anatomy) {
+ e.breathe.anatomy = anatomy;
+ return true;
+ }
+ return false;
+}
+
+// 레거시 자가 이전 (self-heal): 구 테이크 방식이 시퀀스에 끼워둔 breathe 위상
+// 프레임들을 시퀀스에서 걷어내고, 테이크에 기록된 파라미터를 레이어 설정으로 옮긴다.
+// (테이크 원본/추출 프레임은 그대로 — 풀에서는 숨겨진다. 재추출 불필요.)
+function migrateLegacyBreathe(stateName) {
+ const e = entries[stateName];
+ const st = run.states.find((s) => s.name === stateName);
+ if (!e || !st || e.breathe) return false;
+ const legacy = st.frames.filter((f) => (f.label || "").startsWith("breathe")).map((f) => f.index);
+ const legacySet = new Set(legacy);
+ const inSeq = [...e.sel].some((i) => {
+ const src = cloneSrc(stateName, i);
+ return legacySet.has(src === null ? i : src);
+ });
+ if (!inSeq) return false;
+ for (const [ci, src] of Object.entries(e.clones || {})) {
+ if (!legacySet.has(src)) continue;
+ const idx = Number(ci);
+ e.sel.delete(idx);
+ e.order = e.order.filter((i) => i !== idx);
+ delete e.clones[idx];
+ delete e.transforms[idx];
+ delete e.pixels[idx];
+ }
+ for (const i of legacySet) e.sel.delete(i);
+ const take = (st.takes || []).find((tk) => (tk.label || "") === "breathe");
+ const saved = take && take.breathe;
+ // 구 테이크의 분할선 파라미터는 봉투 경계로 옮길 수 없다 (반대 개념 — 서버
+ // migrate_breathe.py 와 같은 판단). 시퀀스에서 걷어내는 일만 하고 설정은 기본값으로
+ // 두며, 해부 숫자는 다음 토글/저장에서 서버가 채운다.
+ e.breathe = { depth: 0.06, breaths: 1, lag: 0.1, rigid_row: null, anatomy: null };
+ return true;
+}
+
+function makeBreatheToggle(stateName) {
+ const wrap = document.createElement("span");
+ wrap.className = "unfake-apply row-toggle breathe-toggle";
+ wrap.title = t("tRowBreathe");
+ const input = document.createElement("input");
+ input.type = "checkbox";
+ input.checked = !!stateBreathe(stateName);
+ input.addEventListener("change", async () => {
+ const e = entries[stateName];
+ if (!input.checked) {
+ if (e.breathe) e.lastBreathe = e.breathe; // 재체크 시 마지막 설정 복원
+ e.breathe = null;
+ scheduleSave();
+ rebuildState(stateName);
+ setStatus(STR[lang].breatheOff(stateName));
+ return;
+ }
+ input.disabled = true;
+ try {
+ e.breathe = e.lastBreathe || await defaultBreatheConfig(stateName);
+ scheduleSave();
+ rebuildState(stateName);
+ setStatus(STR[lang].breatheOn(stateName));
+ } catch (err) {
+ setStatus(t("breatheFail") + err.message, "err");
+ input.checked = false;
+ }
+ input.disabled = false;
+ });
+ const lbl = document.createElement("span");
+ lbl.className = "breathe-open";
+ lbl.title = t("tRowBreatheEdit");
+ lbl.innerHTML =
+ '<svg viewBox="0 0 16 16" width="12" height="12" aria-hidden="true">' +
+ '<path d="M2 11c2.5 0 2.5-3 5-3s2.5 3 5 3 2-2 2-2" fill="none" stroke="currentColor" ' +
+ 'stroke-width="1.4" stroke-linecap="round"/></svg>' +
+ `<span>${t("rowBreathe")}</span>`;
+ lbl.addEventListener("click", (ev) => {
+ ev.preventDefault();
+ const st = run.states.find((s) => s.name === stateName);
+ const srcIdx = ((st && st.frames.find((f) => f.present)) || { index: 0 }).index;
+ pendingBreathe = true;
+ openZoom(stateName, srcIdx);
+ });
+ wrap.appendChild(input);
+ wrap.appendChild(lbl);
+ return wrap;
+}
diff --git a/sprite_gen/serve/curator/src/cards.js b/sprite_gen/serve/curator/src/cards.js
new file mode 100644
index 0000000..1776dfe
--- /dev/null
+++ b/sprite_gen/serve/curator/src/cards.js
@@ -0,0 +1,529 @@
+// SPDX-License-Identifier: Apache-2.0
+// curator/cards.js — 상태 줄/카드/미리보기 렌더링
+// 로드 순서 SSoT = index.html (classic script 전역 어휘 공유; 빌드 스텝 없음)
+
+// 넣기/빼기 SVG (이모지·유니코드 마크 금지 — 라인 아이콘). 시퀀스=위, 풀=아래라
+// 넣기=위 화살표, 빼기=아래 화살표로 공간적으로 직관화.
+const SEL_ICON = {
+ add: '<svg viewBox="0 0 16 16" width="11" height="11" aria-hidden="true"><path d="M8 12.5V4.2M4.6 7.4 8 4l3.4 3.4" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>',
+ remove: '<svg viewBox="0 0 16 16" width="11" height="11" aria-hidden="true"><path d="M8 3.5v8.3M4.6 8.6 8 12l3.4-3.4" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>',
+};
+
+// 반전·초기화 라인 아이콘 (maintainer 2026-07-26: 유니코드 ↔/↺ 글리프는 폭이 폰트마다
+// 제각각이라 카드 푸터가 168px 밖으로 넘쳤다 — 다른 카드 버튼과 같은 12px SVG 로 통일).
+// 확대 모달 툴바(zoom-editor.js)도 같은 상수를 쓴다 — 같은 액션은 같은 그림.
+const FLIP_X_ICON =
+ '<svg viewBox="0 0 16 16" width="12" height="12" aria-hidden="true">' +
+ '<path d="M8 2.1v11.8" fill="none" stroke="currentColor" stroke-width="1.2" stroke-linecap="round" stroke-dasharray="1.9 1.8"/>' +
+ '<path d="M6 5.4 3.1 8l2.9 2.6M10 5.4 12.9 8l-2.9 2.6" fill="none" stroke="currentColor" ' +
+ 'stroke-width="1.3" stroke-linecap="round" stroke-linejoin="round"/></svg>';
+const RESET_ICON =
+ '<svg viewBox="0 0 16 16" width="12" height="12" aria-hidden="true">' +
+ '<path d="M4.85 4.25A4.9 4.9 0 1 0 8 3.1" fill="none" stroke="currentColor" stroke-width="1.3" stroke-linecap="round"/>' +
+ '<path d="M9.7 1.9 8 3.1 9.7 4.3" fill="none" stroke="currentColor" stroke-width="1.3" ' +
+ 'stroke-linecap="round" stroke-linejoin="round"/></svg>';
+
+function renderState(state, replaceEl) {
+ const wrap = document.createElement("section");
+ wrap.className = "state";
+ wrap.dataset.state = state.name;
+
+ const head = document.createElement("div");
+ head.className = "state-head";
+ head.innerHTML =
+ `<span class="name">${escapeHtml(state.name)}</span>` +
+ `<span class="meta">${state.requestFrames} ${t("frames")} · ${state.fps}fps · ${state.loop ? t("loop") : t("nonLoop")} · ${t("cellPx")} ${run.cell.width}x${run.cell.height}px</span>` +
+ (state.action ? `<span class="action">${escapeHtml(state.action)}</span>` : "") +
+ (state.extractOk ? "" : `<span class="state-warn">${t("extractFail")}</span>`) +
+ (anchorStates.has(state.name) ? `<span class="anchor-badge" data-tip="${t("tDirAnchorBadge")}">${t("dirAnchorBadge")}</span>` : "");
+ wrap.appendChild(head);
+
+ // 이 줄을 "무엇으로 생성했는가" — run dir 실재 파일 기준 ref 체인 (앵커/basis/가이드).
+ // 같은 줄 우측 = 줄별 표시/굽기 컨트롤(픽셀 격자 · 픽셀 언페이크 체크박스) — 이미지 바로 위.
+ const hasRefs = state.refs && state.refs.length;
+ const showGridToggle = true; // 격자는 모든 줄이 가진다 (display.js 계약)
+ const showUnfakeToggle = true; // 퍼펙 토글은 모든 줄 (트윈=소스 전환, 그 외=측정 k 렌즈)
+ const showGifBtn = state.frames && state.frames.some((f) => f.present);
+ if (hasRefs || showGridToggle || showUnfakeToggle || showGifBtn) {
+ const refs = document.createElement("div");
+ refs.className = "state-refs";
+ refs.innerHTML = hasRefs
+ ? `<span class="refs-label">${t("refsLabel")}</span>` +
+ state.refs
+ .map((r) => {
+ // 앵커 칩은 서버 라이브 베이크(/api/anchor)라 사이드카가 바뀌면 다시 받아야
+ // 한다 (지정 변경뿐 아니라 앵커 프레임의 픽셀 편집·변형도 그림을 바꾼다).
+ // 저장이 디스크에 닿은 뒤 refreshAnchorChips 가 src 를 갈아준다.
+ const url = r.anchorFrame ? `${r.url}&t=${anchorCacheBust}` : r.url;
+ const mark = r.anchorFrame ? ` data-anchor="1" data-base-url="${escapeHtml(r.url)}"` : "";
+ return `<a class="ref-chip" href="${escapeHtml(url)}" target="_blank" title="${escapeHtml(r.name)}">` +
+ `<img src="${escapeHtml(url)}" alt="${escapeHtml(r.role)}" loading="lazy"${mark} />` +
+ `<span>${t("ref_" + r.role)}</span></a>`;
+ })
+ .join("")
+ : "";
+ const controls = document.createElement("span");
+ controls.className = "row-controls";
+ controls.appendChild(makeFpsStepper(state.name));
+ if (showGridToggle) controls.appendChild(makeGridToggle(state.name));
+ if (showUnfakeToggle) controls.appendChild(makeUnfakeToggle(state.name));
+ controls.appendChild(makeTweenButton(state.name));
+ controls.appendChild(makeRerollButton(state.name));
+ controls.appendChild(makeBreatheToggle(state.name));
+ // 저장은 맨 우측 (maintainer 2026-07-19)
+ if (showGifBtn) controls.appendChild(makeGifButton(state.name));
+ refs.appendChild(controls);
+ wrap.appendChild(refs);
+ }
+
+ const body = document.createElement("div");
+ body.className = "state-body";
+
+ // two rows: sequence (selected, in play order) on top, candidate pool below.
+ const zones = document.createElement("div");
+ zones.className = "zones";
+ zones.innerHTML =
+ `<div class="zone zone-seq"><div class="zone-label">${t("zoneSeq")}</div>` +
+ `<div class="frames seq-frames"></div></div>` +
+ `<div class="zone zone-pool"><div class="zone-label">${t("zonePool")}</div>` +
+ `<div class="frames pool-frames"></div></div>`;
+ const seqFrames = zones.querySelector(".seq-frames");
+ const poolFrames = zones.querySelector(".pool-frames");
+
+ const e = entries[state.name];
+ // frameOf 는 복제 인스턴스(order 의 물리 범위 밖 인덱스)도 원본 frame 객체를
+ // 빌려 해석한다 — 카드 하나 = 인스턴스 하나.
+ for (const idx of e.order) {
+ if (!e.sel.has(idx)) continue;
+ const frame = frameOf(state.name, idx);
+ if (frame) seqFrames.appendChild(renderCard(state, frame));
+ }
+ // pool = everything not in the sequence. `order` already contains every
+ // index (present + missing), so this single loop covers missing frames too
+ // — do NOT also iterate state.frames here or missing cards render twice.
+ for (const idx of e.order) {
+ if (e.sel.has(idx)) continue;
+ const frame = frameOf(state.name, idx);
+ if (!frame) continue;
+ // 호흡 위상 프레임은 큐레이션 후보가 아니라 파생 사이클 재료다 (maintainer 지적
+ // 2026-07-17 "토글할 때 후보 풀이 달라진다") — 토글 OFF 상태에선 풀에
+ // 노출하지 않는다. 토글 체크박스가 유일한 표면이고, 풀 구성은 호흡
+ // on/off 와 무관하게 불변이다.
+ if ((frame.label || "").startsWith("breathe")) continue;
+ poolFrames.appendChild(renderCard(state, frame));
+ }
+
+ // 보관함: 후보 풀에서도 완전히 뺀 프레임. 접힌 칩 → 클릭하면 팝오버(쇽),
+ // 카드를 칩에 끌어다 놓으면 보관, 팝오버의 미니카드를 끌어내면 복구.
+ zones.appendChild(renderArchive(state));
+
+ body.appendChild(zones);
+ body.appendChild(renderPreview(state));
+ wrap.appendChild(body);
+
+ if (replaceEl) replaceEl.replaceWith(wrap);
+ else document.getElementById("states").appendChild(wrap);
+
+ // wire stages + reorder grips after they are in the DOM (need clientWidth).
+ // order 를 돌아야 복제 인스턴스 카드도 와이어링된다 (물리 프레임 목록엔 없다).
+ for (const idx of e.order) {
+ const frame = frameOf(state.name, idx);
+ if (!frame || !frame.present) continue;
+ const card = wrap.querySelector(`.card[data-idx="${idx}"]`);
+ if (!card) continue; // 보관된 프레임은 행에 카드가 없다
+ const stage = card.querySelector(".stage");
+ wireStage(stage, state.name, idx);
+ applyCardTransform(stage, state.name, idx);
+ if (run.iso) drawGroundGrid(stage);
+ // the whole header strip is the drag handle (grip + label + ✗/✓ button),
+ // not just the ⠿ glyph — see wireReorder.
+ const cardTop = card.querySelector(".card-top");
+ if (cardTop) wireReorder(cardTop, card, wrap, state.name);
+ }
+ renderSelectionState(state.name);
+ startPreview(state);
+ // 새로 만든 표시면은 판정을 받아야 한다. load 위임 훅은 <img> 전용이라
+ // 여기서 만든 캔버스(미리보기·스냅)를 못 덮고, rebuildState 경로 11곳
+ // (보관·복구·복제·삭제·호흡 적용·줌 닫기…)이 전부 이 함수를 지난다.
+ // 빠뜨리면 리사이즈가 올 때까지 뭉갠 채로 남는다 (validator R2, 2026-07-24).
+ syncPixelScaling(wrap);
+}
+
+// 앵커 칩(라이브 베이크) 재요청 — 저장이 디스크에 닿은 뒤 호출된다 (persistence.save).
+// 앵커 프레임의 픽셀 편집/변형도 앵커 그림을 바꾸므로, 지정 변경만으로는 부족하다.
+// 페인팅 중 autosave 가 연달아 터지므로 트레일링 디바운스로 묶는다.
+let anchorChipTimer = null;
+
+function refreshAnchorChips() {
+ clearTimeout(anchorChipTimer);
+ anchorChipTimer = setTimeout(() => {
+ for (const img of document.querySelectorAll('#states .ref-chip img[data-anchor]')) {
+ const base = img.getAttribute("data-base-url");
+ if (!base) continue;
+ const url = `${base}&t=${anchorCacheBust}`;
+ img.src = url;
+ const link = img.closest("a.ref-chip");
+ if (link) link.href = url;
+ }
+ }, 500);
+}
+
+function renderCard(state, frame) {
+ const card = document.createElement("div");
+ card.className = "card";
+ card.dataset.state = state.name;
+ card.dataset.idx = frame.index;
+ if (!frame.present) card.classList.add("missing");
+ card.style.setProperty("--cell-aspect", run.cell.width / run.cell.height);
+
+ const stageInner = frame.present
+ ? (run.iso ? `<canvas class="grid-overlay"></canvas>` : "") +
+ `<div class="pxgrid"></div>` +
+ `<canvas class="ingrid"></canvas>` +
+ `<img src="${escapeHtml(frameUrl(state.name, frame))}" alt="frame ${frame.index}" draggable="false" />` +
+ `<canvas class="snap-canvas"></canvas>` +
+ `<div class="rotate-handle" data-tip="${t("tRotate")}"></div>` +
+ `<div class="shear-handle" data-tip="${t("tShear")}"></div>`
+ : `<div class="missing-label">${state.rawPresent ? t("missingRawWait") : t("missingPending")}</div>`;
+
+ const isClone = frame.clone !== undefined;
+ const srcName = isClone ? frameDisplayName(state.name, frame.clone) : null;
+ const customName = (entries[state.name].names || {})[frame.index];
+ const shortLabel = customName || (isClone ? STR[lang].cloneBadge(srcName) : (frame.label ? frame.label : `#${frame.index}`));
+ // 풀네임(복사 대상) — 에이전트가 그대로 집어가도록 런-상대 파일 경로 + 라벨.
+ const relPath = (frame.url || "").replace(/^\/run\//, "");
+ const fullName = (customName ? `${customName} · ` : "") + (isClone ? `${srcName} 복제 · ${relPath}` : [frame.label, relPath].filter(Boolean).join(" · ") || shortLabel) + " · " + t("tRenameHint");
+ const titleCls = isClone ? "idx clone-badge" : "idx";
+ const linkBtn = !isClone ? "" : (isLinkedClone(state.name, frame.index)
+ ? `<button type="button" class="ghost link-state-btn unlink-btn" data-tip="${t("tUnlink")}" aria-label="unlink">` +
+ '<svg viewBox="0 0 16 16" width="11" height="11" aria-hidden="true">' +
+ '<path d="M6.5 9.5 3.8 12.2a2.2 2.2 0 0 0 3.1 3.1l2.7-2.7M9.5 6.5l2.7-2.7a2.2 2.2 0 0 0-3.1-3.1L6.4 3.4M2.5 2.5l2 2M13.5 13.5l-2-2" transform="translate(0,-1)" fill="none" stroke="currentColor" stroke-width="1.3" stroke-linecap="round"/></svg></button>'
+ : `<button type="button" class="ghost link-state-btn relink-btn" data-tip="${t("tRelink")}" aria-label="relink">` +
+ '<svg viewBox="0 0 16 16" width="11" height="11" aria-hidden="true">' +
+ '<path d="M6.8 9.2 4 12a2.3 2.3 0 0 0 3.2 3.2l2.8-2.8M9.2 6.8 12 4a2.3 2.3 0 0 1 3.2 3.2l-2.8 2.8M6.2 9.8l3.6-3.6" transform="translate(-1.5,-1.5)" fill="none" stroke="currentColor" stroke-width="1.3" stroke-linecap="round"/></svg></button>');
+ const title = `<span class="${titleCls}" data-tip="${escapeHtml(fullName)}" data-tip-copy>${escapeHtml(shortLabel)}</span>${linkBtn}`;
+ // 아이콘 SVG — 이모지 대신 라인 아이콘 (플랫폼별 렌더 편차·저품질 방지)
+ const dupIcon =
+ '<svg viewBox="0 0 16 16" width="12" height="12" aria-hidden="true">' +
+ '<rect x="5.5" y="5.5" width="8.2" height="8.2" rx="1.6" fill="none" stroke="currentColor" stroke-width="1.3"/>' +
+ '<path d="M3.4 10.4H2.9A1 1 0 0 1 1.9 9.4V3A1.1 1.1 0 0 1 3 1.9h6.4a1 1 0 0 1 1 1v0.5" ' +
+ 'fill="none" stroke="currentColor" stroke-width="1.3" stroke-linecap="round"/></svg>';
+ const zoomIcon =
+ '<svg viewBox="0 0 16 16" width="12" height="12" aria-hidden="true">' +
+ '<circle cx="6.8" cy="6.8" r="4.3" fill="none" stroke="currentColor" stroke-width="1.3"/>' +
+ '<path d="M10 10 14 14M5 6.8h3.6M6.8 5v3.6" fill="none" stroke="currentColor" stroke-width="1.3" stroke-linecap="round"/></svg>';
+ const archIcon =
+ '<svg viewBox="0 0 16 16" width="12" height="12" aria-hidden="true">' +
+ '<path d="M1.8 3.2h12.4v3H1.8zM2.9 6.2v6.4A1 1 0 0 0 3.9 13.6h8.2a1 1 0 0 0 1-1V6.2M6.2 8.6h3.6" ' +
+ 'fill="none" stroke="currentColor" stroke-width="1.25" stroke-linejoin="round"/></svg>';
+ const psize = frame.present && frame.contentSize
+ ? `<span class="psize" data-tip="${t("tContentPx")}">${frame.contentSize[0]}×${frame.contentSize[1]}</span>` : "";
+ // 방향 앵커 지정 (maintainer 2026-07-25): 방향 런의 프레임만 앵커가 될 수 있다.
+ // 앵커 = 이 방향의 다른 자세를 생성할 때 붙는 identity 한 장 — 큐레이션된 모습 그대로.
+ const anchorDir = frame.present ? directionOfState(state.name) : null;
+ const isAnchor = !!anchorDir && isAnchorFrame(state.name, frame.index);
+ const isPinned = !!anchorDir && isPinnedAnchorFrame(state.name, frame.index);
+ const isStalePin = !!anchorDir && isStaleAnchorFrame(state.name, frame.index);
+ const pinIcon =
+ '<svg viewBox="0 0 16 16" width="12" height="12" aria-hidden="true">' +
+ '<path d="M8 1.9a3.4 3.4 0 0 1 3.4 3.4c0 2.4-3.4 6.4-3.4 6.4S4.6 7.7 4.6 5.3A3.4 3.4 0 0 1 8 1.9Z" ' +
+ 'fill="none" stroke="currentColor" stroke-width="1.3" stroke-linejoin="round"/>' +
+ '<circle cx="8" cy="5.2" r="1.3" fill="none" stroke="currentColor" stroke-width="1.2"/>' +
+ '<path d="M5.6 14.1h4.8" fill="none" stroke="currentColor" stroke-width="1.2" stroke-linecap="round"/></svg>';
+ const anchorBtn = anchorDir
+ ? `<button type="button" class="ghost anchor-btn${isPinned ? " on" : ""}${isStalePin ? " stale" : ""}" ` +
+ `data-tip="${isStalePin ? t("tRepinAnchorFrame") : isPinned ? t("tUnsetAnchorFrame") : t("tSetAnchorFrame")}" ` +
+ `aria-label="anchor">${pinIcon}</button>`
+ : "";
+ if (isAnchor) card.classList.add("is-anchor");
+ card.innerHTML =
+ // 헤더: 복제 | 타이틀(드래그 핸들, 호버 시 풀네임 복사) | 확대 —
+ // 복제를 좌측으로 분리 (maintainer 지시 2026-07-17: 확대 옆에 붙어 있어 오클릭).
+ `<div class="card-top"${frame.present ? ` data-tip="${t("tReorder")}"` : ""}>` +
+ `<span class="ct-left">` +
+ (frame.present
+ ? `<button type="button" class="ghost dup-btn" data-tip="${t("tDupBtn")}" aria-label="duplicate">${dupIcon}</button>`
+ : "") +
+ `${title}</span>` +
+ (frame.present
+ ? `<span class="ct-right">` +
+ (isAnchor || isStalePin
+ ? `<span class="anchor-frame-badge${isPinned ? " pinned" : ""}${isStalePin ? " stale" : ""}" ` +
+ `data-tip="${isStalePin ? t("tAnchorFrameStale") : isPinned ? t("tAnchorFramePinned") : t("tAnchorFrameBadge")}">` +
+ `${isStalePin ? t("anchorFrameStaleBadge") : t("anchorFrameBadge")}</span>`
+ : "") +
+ `<button type="button" class="ghost zoom-btn" data-tip="${t("tZoomOpen")}" aria-label="zoom">${zoomIcon}</button>` +
+ `</span>`
+ : "") +
+ `</div>` +
+ `<div class="stage">${stageInner}</div>` +
+ // 푸터 2층: (1) 정보 — 크기·변형값 / (2) 버튼 — 반전·초기화 · 넣기빼기·보관
+ (frame.present
+ ? `<div class="card-info">${psize}<span class="tvals"></span></div>` +
+ `<div class="card-controls">` +
+ `<button type="button" class="ghost flip-btn" data-tip="${t("tFlipX")}" aria-label="flip-x">${FLIP_X_ICON}</button>` +
+ `<button type="button" class="ghost reset-btn" data-tip="${t("tReset")}" aria-label="reset">${RESET_ICON}</button>` +
+ anchorBtn +
+ `<span class="ctrl-group">` +
+ `<button type="button" class="sel-btn"></button>` +
+ `<button type="button" class="ghost arch-btn" data-tip="${t("tArchiveBtn")}" aria-label="archive">${archIcon}</button>` +
+ `</span>` +
+ `</div>`
+ : "") +
+ "";
+
+ if (frame.present) {
+ // 표시 샘플링 판정은 display.js 가 소유한다 — 로드는 위임 훅
+ // (installPixelScalingLoadHook), 기하 변화는 sizePxGrids/resize 가 재평가한다.
+ // 여기서 따로 부르지 않는다 (판정 재확산 금지).
+ const idxEl = card.querySelector(".card-top .idx");
+ if (idxEl) idxEl.addEventListener("dblclick", (ev) => {
+ ev.preventDefault();
+ ev.stopPropagation();
+ const e2 = entries[state.name];
+ const cur = (e2.names || {})[frame.index] || "";
+ const next = window.prompt(t("renamePrompt"), cur);
+ if (next === null) return;
+ e2.names = e2.names || {};
+ const trimmed = next.trim().slice(0, 24);
+ if (trimmed) e2.names[frame.index] = trimmed;
+ else delete e2.names[frame.index];
+ scheduleSave();
+ rebuildState(state.name);
+ });
+ const relinkBtn = card.querySelector(".relink-btn");
+ if (relinkBtn) relinkBtn.addEventListener("click", () => {
+ // 재링크: 자기 편집을 버리고 원본 truth 재채택 (명시적 사용자 액션)
+ const e2 = entries[state.name];
+ delete e2.transforms[frame.index];
+ delete e2.pixels[frame.index];
+ if (e2.unlinked) e2.unlinked.delete(frame.index);
+ scheduleSave();
+ rebuildState(state.name);
+ setStatus(STR[lang].relinked(frameDisplayName(state.name, e2.clones[frame.index])));
+ });
+ const unlinkBtn = card.querySelector(".unlink-btn");
+ if (unlinkBtn) unlinkBtn.addEventListener("click", () => {
+ // 링크 끊기: 현재 원본 편집을 복사해 독립 프레임으로 (이후 편집은 각자)
+ const e2 = entries[state.name];
+ const srcIdx = e2.clones[frame.index];
+ if (e2.transforms[srcIdx]) e2.transforms[frame.index] = { ...e2.transforms[srcIdx] };
+ if (e2.pixels[srcIdx]) e2.pixels[frame.index] = JSON.parse(JSON.stringify(e2.pixels[srcIdx]));
+ e2.unlinked = e2.unlinked || new Set();
+ e2.unlinked.add(frame.index);
+ scheduleSave();
+ rebuildState(state.name);
+ setStatus(STR[lang].unlinked(frameDisplayName(state.name, srcIdx)));
+ });
+ card.querySelector(".reset-btn").addEventListener("click", () =>
+ resetTransform(state.name, frame.index)
+ );
+ card.querySelector(".flip-btn").addEventListener("click", () =>
+ toggleFlipX(state.name, frame.index)
+ );
+ // 확대 모달 진입: 헤더의 ⛶ 버튼 (pointerdown 전파를 끊어 헤더 드래그/클릭 토글과
+ // 충돌하지 않게) + 스테이지 더블클릭.
+ const zoomBtn = card.querySelector(".zoom-btn");
+ if (zoomBtn) {
+ zoomBtn.addEventListener("pointerdown", (ev) => ev.stopPropagation());
+ zoomBtn.addEventListener("click", () => openZoom(state.name, frame.index));
+ }
+ card.querySelector(".stage").addEventListener("dblclick", () => openZoom(state.name, frame.index));
+ const dupBtn = card.querySelector(".dup-btn");
+ if (dupBtn) {
+ dupBtn.addEventListener("pointerdown", (ev) => ev.stopPropagation());
+ dupBtn.addEventListener("click", () => duplicateFrame(state.name, frame.index));
+ }
+ const cloneBadge = card.querySelector(".clone-badge");
+ if (cloneBadge && frame.clone !== undefined) {
+ // 복제 배지 클릭 = 원본 카드로 이동 + 반짝 — "어떤 프레임의 복제인지" 시각 연결
+ cloneBadge.addEventListener("pointerdown", (ev) => ev.stopPropagation());
+ cloneBadge.addEventListener("click", (ev) => {
+ ev.stopPropagation();
+ const srcCard = document.querySelector(
+ `#states .card[data-state="${cssEscape(state.name)}"][data-idx="${frame.clone}"]`);
+ if (!srcCard) return;
+ srcCard.scrollIntoView({ behavior: "smooth", block: "center" });
+ srcCard.classList.remove("flash-target");
+ void srcCard.offsetWidth;
+ srcCard.classList.add("flash-target");
+ srcCard.addEventListener("animationend", () => srcCard.classList.remove("flash-target"), { once: true });
+ });
+ }
+ const anchorBtnEl = card.querySelector(".anchor-btn");
+ if (anchorBtnEl) {
+ anchorBtnEl.addEventListener("pointerdown", (ev) => ev.stopPropagation());
+ anchorBtnEl.addEventListener("click", async (ev) => {
+ ev.currentTarget.disabled = true;
+ try {
+ await setAnchorFrame(state.name, frame.index);
+ } finally {
+ // rebuildState 가 카드를 교체하므로 살아있을 때만 되살린다
+ if (ev.currentTarget.isConnected) ev.currentTarget.disabled = false;
+ }
+ });
+ }
+ const archBtn = card.querySelector(".arch-btn");
+ archBtn.addEventListener("pointerdown", (ev) => ev.stopPropagation());
+ archBtn.addEventListener("click", () => archiveFrame(state.name, frame.index));
+ // 넣기/빼기 = 시퀀스⇄풀 토글의 유일한 버튼 (드래그 외). 푸터에 있어 헤더 드래그와
+ // 무관하지만, 실수 드래그 시작을 막으려 pointerdown 전파를 끊는다.
+ const selBtn = card.querySelector(".sel-btn");
+ selBtn.addEventListener("pointerdown", (ev) => ev.stopPropagation());
+ selBtn.addEventListener("click", () => moveCardToOtherZone(card, state.name));
+ card.querySelector(".stage").appendChild(makeScaleScrub(state.name, frame.index));
+ }
+ return card;
+}
+
+/** Toggle horizontal flip for a single frame (maintainer 2026-05-28). */
+
+function renderPreview(state) {
+ const box = document.createElement("div");
+ box.className = "preview";
+ box.dataset.state = state.name;
+ const aspect = run.cell.height / run.cell.width;
+ const speedOpts = [0.25, 0.5, 1, 2, 4]
+ .map((v) => `<option value="${v}"${v === 1 ? " selected" : ""}>×${v}</option>`)
+ .join("");
+ // 위치 표시(pv-pos)를 캔버스·프레임수 바로 밑(컨트롤 위)으로 — 재생 컨트롤 아래
+ // 뚝 떨어져 있어 캔버스와 멀고 헷갈렸다 (maintainer 2026-07-15, 쿠마피커 pv-pos 지정).
+ box.innerHTML =
+ `<h4>${t("preview")}</h4>` +
+ `<canvas width="${run.cell.width}" height="${run.cell.height}" style="height:${(160 * aspect).toFixed(0)}px"></canvas>` +
+ `<div class="count"></div>` +
+ `<div class="pv-pos"></div>` +
+ `<div class="pv-controls">` +
+ `<button type="button" class="ghost pv-prev" data-tip="${t("tPrev")}">⏮</button>` +
+ `<button type="button" class="ghost pv-play" data-tip="${t("tPause")}">⏸</button>` +
+ `<button type="button" class="ghost pv-next" data-tip="${t("tNext")}">⏭</button>` +
+ `<select class="pv-speed" name="speed-${escapeHtml(state.name)}" aria-label="${t("tSpeed")}" data-tip="${t("tSpeed")}">${speedOpts}</select>` +
+ `</div>`;
+ return box;
+}
+
+function startPreview(state) {
+ const root = document.querySelector(`.preview[data-state="${cssEscape(state.name)}"]`);
+ const canvas = root.querySelector("canvas");
+ const ctx = canvas.getContext("2d");
+ const cw = run.cell.width;
+ const ch = run.cell.height;
+ const playBtn = root.querySelector(".pv-play");
+ const posEl = root.querySelector(".pv-pos");
+ const pv = (previews[state.name] = { playing: true, speed: 1, cursor: 0, shown: -1, tick: 0 });
+ let last = 0;
+
+ const syncPlayBtn = () => {
+ playBtn.textContent = pv.playing ? "⏸" : "▶";
+ playBtn.setAttribute("data-tip", pv.playing ? t("tPause") : t("tPlay"));
+ };
+
+ // draw the frame at the current cursor; runs every rAF so live transform
+ // edits show even while paused. The matrix matches CSS + the compose bake.
+ const draw = () => {
+ const play = playList(state.name);
+ ctx.clearRect(0, 0, cw, ch);
+ if (!play.length) {
+ posEl.textContent = "0/0";
+ return;
+ }
+ pv.cursor = ((pv.cursor % play.length) + play.length) % play.length;
+ const idx = play[pv.cursor];
+ pv.shown = idx; // remember which frame is on screen (for reanchoring on edits)
+ const f = frameOf(state.name, idx); // 복제 인스턴스 → 원본 이미지
+ const image = f ? img(frameUrl(state.name, f)) : null;
+ if (image && image.complete && image.naturalWidth) {
+ const tr = getTransform(state.name, idx);
+ const bcfg = stateBreathe(state.name);
+ if (bcfg) {
+ // 호흡 합성은 캐노니컬 픽셀 기준 (표시 변형은 풋프린트 상이 — 이음새 흔들림)
+ // 호흡 후처리 레이어 (maintainer 2026-07-18): 프레임 선택과 직교하는 변조 —
+ // 재생 틱 기준 위상을 프레임 위에 얹는다 (깜빡임 프레임도 그대로 숨쉰다).
+ const base = document.createElement("canvas");
+ base.width = cw;
+ base.height = ch;
+ const baseCtx = base.getContext("2d");
+ baseCtx.imageSmoothingEnabled = false;
+ // 워프 base 도 신선도 기준과 **같은 변형**이어야 한다 (굽기가 쓰는 그 파일).
+ const canonSrc = f && bakeFrameUrl(state.name, f);
+ const canonical = canonSrc ? img(canonSrc) : null;
+ if (!(canonical && canonical.complete && canonical.naturalWidth)) {
+ // 굽기 파일이 아직 로드 전이면 **워프하지 않는다.** 표시 파일로 폴백해 워프하면
+ // (pp OFF 트윈 줄은 `orig/` 고해상본이다) 굽기와 다른 그림을 알림 없이 보여준다.
+ // 로드되면 다음 틱에 자가 교정되므로, 그때까지는 호흡 없는 원본을 그린다 —
+ // 조용히 **틀린 그림**을 그리는 것보다 조용히 **안 그리는** 쪽이 맞다
+ // (validator note 2026-07-26).
+ drawFrameInto(ctx, image, tr, cw, ch, snapScaleFor(state.name), getPixelOps(state.name, idx));
+ } else {
+ drawFrameInto(baseCtx, canonical,
+ tr, cw, ch, snapScaleFor(state.name), getPixelOps(state.name, idx));
+ const pattern = breathePattern(bcfg, play.length);
+ // 신선도 기준 = 재생 첫 슬롯의 **키** (굽기가 해부를 확정하는 프레임). 그림을 다시
+ // 그려 지문을 찍던 옛 방식은 리샘플러가 굽기와 달라 영구 불일치였다.
+ const refKey = breatheReferenceKey(state.name);
+ ctx.drawImage(bcfg ? breatheComposeForPreview(base, bcfg, pattern[pv.cursor] || 0, refKey) : base, 0, 0);
+ }
+ } else {
+ // 픽셀 언페이크 줄은 카드와 동일하게 격자 재양자화로 그린다 (프리뷰 = 굽기)
+ drawFrameInto(ctx, image, tr, cw, ch, snapScaleFor(state.name), getPixelOps(state.name, idx));
+ }
+ }
+ posEl.textContent = `${pv.cursor + 1}/${play.length} · #${idx}`;
+ };
+
+ const step = (delta) => {
+ pv.playing = false;
+ syncPlayBtn();
+ const play = playList(state.name);
+ if (play.length) pv.cursor = (pv.cursor + delta + play.length) % play.length;
+ pv.tick += 1;
+ draw();
+ };
+ root.querySelector(".pv-prev").addEventListener("click", () => step(-1));
+ root.querySelector(".pv-next").addEventListener("click", () => step(1));
+ playBtn.addEventListener("click", () => {
+ pv.playing = !pv.playing;
+ syncPlayBtn();
+ });
+ root.querySelector(".pv-speed").addEventListener("change", (e) => {
+ pv.speed = parseFloat(e.target.value) || 1;
+ });
+
+ // Called after the selection/order changes (move between rows, reorder). Keeps
+ // the on-screen frame in view instead of jumping (re-anchor by frame index),
+ // and disables the transport when the sequence is empty (nothing to play).
+ const prevBtn = root.querySelector(".pv-prev");
+ const nextBtn = root.querySelector(".pv-next");
+ pv.refresh = () => {
+ const play = playList(state.name);
+ if (!play.length) {
+ pv.cursor = 0;
+ } else {
+ const p = play.indexOf(pv.shown);
+ pv.cursor = p >= 0 ? p : ((pv.cursor % play.length) + play.length) % play.length;
+ }
+ const empty = play.length === 0;
+ prevBtn.disabled = empty;
+ nextBtn.disabled = empty;
+ playBtn.disabled = empty;
+ draw();
+ };
+ pv.refresh();
+
+ function frame(ts) {
+ if (!root.isConnected) return; // 섹션이 교체/제거되면 이 루프는 은퇴
+ const play = playList(state.name);
+ if (pv.playing && play.length) {
+ const interval = 1000 / Math.max(0.1, state.fps * pv.speed);
+ if (ts - last >= interval) {
+ last = ts;
+ pv.cursor = (pv.cursor + 1) % play.length;
+ pv.tick += 1; // 호흡 위상 진행 (프레임 주기와 독립 — LCM 으로 재정합)
+ }
+ }
+ draw();
+ requestAnimationFrame(frame);
+ }
+ syncPlayBtn();
+ requestAnimationFrame(frame);
+}
diff --git a/sprite_gen/serve/curator/src/chrome.js b/sprite_gen/serve/curator/src/chrome.js
new file mode 100644
index 0000000..cb650d4
--- /dev/null
+++ b/sprite_gen/serve/curator/src/chrome.js
@@ -0,0 +1,59 @@
+// SPDX-License-Identifier: Apache-2.0
+// curator/chrome.js — 페이지 크롬 — 사이드바 접기, 상단 토글 버튼
+// 로드 순서 SSoT = index.html (classic script 전역 어휘 공유; 빌드 스텝 없음)
+
+const sidebarToggle = document.getElementById("sidebar-toggle");
+// topbar 실측 높이 → 사이드바 sticky 오프셋/전체높이 계산에 주입.
+// 라벨/폰트가 늦게 차면서 높이가 변하므로 ResizeObserver 로 추적한다 (일회 측정 금지).
+{
+ const topbar = document.querySelector(".topbar");
+ if (topbar) {
+ const sync = () =>
+ document.documentElement.style.setProperty("--topbar-h", `${topbar.offsetHeight}px`);
+ sync();
+ new ResizeObserver(sync).observe(topbar);
+ }
+}
+
+function applySidebarCollapsed(collapsed) {
+ document.body.classList.toggle("sidebar-collapsed", collapsed);
+ try { localStorage.setItem("curator-sidebar-collapsed", collapsed ? "1" : ""); } catch { /* private mode */ }
+}
+if (sidebarToggle) {
+ sidebarToggle.addEventListener("click", () =>
+ applySidebarCollapsed(!document.body.classList.contains("sidebar-collapsed")));
+ let saved = "";
+ try { saved = localStorage.getItem("curator-sidebar-collapsed") || ""; } catch { /* private mode */ }
+ applySidebarCollapsed(saved === "1");
+}
+
+const gridToggle = document.getElementById("grid-toggle");
+
+const langToggle = document.getElementById("lang-toggle");
+gridToggle.addEventListener("click", () => {
+ const on = document.body.classList.toggle("show-grid");
+ gridToggle.textContent = `${t("groundGrid")} ${on ? "▣" : "▢"}`;
+ if (on) document.querySelectorAll(".stage").forEach(drawGroundGrid);
+});
+
+// language toggle reloads with ?lang= so preview rAF loops are not duplicated
+langToggle.addEventListener("click", () => {
+ const next = lang === "en" ? "ko" : "en";
+ const u = new URL(location.href);
+ u.searchParams.set("lang", next);
+ location.href = u.toString();
+});
+
+// 상단 저장 팝오버 (maintainer 2026-07-19 "다운로드 버튼 하나로 통일"): 아틀라스/PNG/GIF
+// 버튼은 ID·핸들러 그대로 메뉴 안으로 — 토글만 여기서 배선한다.
+(() => {
+ const btn = document.getElementById("dl-main");
+ const menu = document.getElementById("dl-main-menu");
+ if (!btn || !menu) return;
+ btn.addEventListener("click", (ev) => {
+ ev.stopPropagation();
+ menu.hidden = !menu.hidden;
+ });
+ menu.addEventListener("click", () => { menu.hidden = true; }); // 항목 실행 후 닫힘
+ document.addEventListener("click", () => { menu.hidden = true; });
+})();
diff --git a/sprite_gen/serve/curator/src/compare.js b/sprite_gen/serve/curator/src/compare.js
new file mode 100644
index 0000000..72e9d0a
--- /dev/null
+++ b/sprite_gen/serve/curator/src/compare.js
@@ -0,0 +1,632 @@
+// SPDX-License-Identifier: Apache-2.0
+// curator/compare.js — 완성본 비교 캔버스 v2 (maintainer 2026-07-18)
+// 로드 순서 SSoT = index.html (classic script 전역 어휘 공유; 빌드 스텝 없음)
+//
+// - 정렬 모드(디폴트 배치): 수평(바닥 공유) / 수직(가로 중심 공유) / 겹침(오니언스킨)
+// - 좌측 목록: 모든 상태의 완성본을 체크박스로 켜고 끔 (많아져도 스크롤)
+// - 스프라이트를 직접 잡고 드래그해 자유 배치 (오프셋은 세션 로컬)
+// - 가이드선: 캔버스 클릭 = 가로선, Shift+클릭 = 세로선. 클릭 = 포커스,
+// 드래그 = 이동, Delete/Backspace = 포커스된 선 삭제.
+// - 배율: 스테이지 위에서 휠.
+
+function openCompare() {
+ document.getElementById("compare-modal")?.remove();
+ const all = [];
+ for (const st of run.states) {
+ const f = st.frames.find((fr) => fr.present && fr.contentBox);
+ if (f) all.push({ state: st.name, frame: f });
+ }
+ if (!all.length) {
+ setStatus(t("cmpNone"), "err");
+ return;
+ }
+ // 비교 상태는 캐릭터별로 영속 (maintainer 2026-07-18: 선 그어놓고 보면서 작업 —
+ // 닫거나 새로고침해도 유지). truth = localStorage sg-compare:<characterId>.
+ const persistKey = `sg-compare:${run.characterId || "run"}`;
+ let savedCmp = null;
+ try { savedCmp = JSON.parse(localStorage.getItem(persistKey) || "null"); } catch { /* 무시 */ }
+ const state = {
+ mode: (savedCmp && savedCmp.mode) || "h",
+ zoom: (savedCmp && savedCmp.zoom) || 8,
+ guides: (savedCmp && Array.isArray(savedCmp.guides)) ? savedCmp.guides : [],
+ guidesShow: !savedCmp || savedCmp.guidesShow !== false, // 선 보이기/감추기 (영속)
+ focus: -1,
+ include: new Set(
+ savedCmp && Array.isArray(savedCmp.include) && savedCmp.include.length
+ ? savedCmp.include.filter((n) => all.some((tg) => tg.state === n))
+ : all.filter((tg) => /_idle$/.test(tg.state)).map((tg) => tg.state)),
+ offsets: (savedCmp && savedCmp.offsets) || {},
+ };
+ if (!state.include.size) state.include.add(all[0].state);
+ const persistCompare = () => {
+ try {
+ localStorage.setItem(persistKey, JSON.stringify({
+ mode: state.mode, zoom: state.zoom, guides: state.guides,
+ guidesShow: state.guidesShow, include: [...state.include], offsets: state.offsets,
+ }));
+ } catch { /* 무시 */ }
+ };
+ // 조작 히스토리 (Cmd/Ctrl+Z ↔ Cmd/Ctrl+Shift+Z): 가이드 추가/이동/삭제, 스프라이트 이동, 정렬 리셋
+ const hist = { list: [], pos: -1 };
+ const snapshot = () => JSON.parse(JSON.stringify({ guides: state.guides, offsets: state.offsets, focus: state.focus }));
+ const pushHist = () => {
+ hist.list = hist.list.slice(0, hist.pos + 1);
+ hist.list.push(snapshot());
+ hist.pos = hist.list.length - 1;
+ persistCompare();
+ };
+ const restoreHist = (pos) => {
+ if (pos < 0 || pos >= hist.list.length || pos === hist.pos) return;
+ hist.pos = pos;
+ const s = JSON.parse(JSON.stringify(hist.list[pos]));
+ state.guides = s.guides;
+ state.offsets = s.offsets;
+ state.focus = s.focus;
+ render();
+ persistCompare();
+ };
+
+ const anim = { playing: false, cursors: {}, last: {} };
+ const modal = document.createElement("div");
+ modal.id = "compare-modal";
+ modal.innerHTML =
+ `<div class="zoom-backdrop"></div>` +
+ `<div class="card cmp-card">` +
+ `<div class="zoom-head"><span class="zoom-title">${t("cmpTitle")}</span>` +
+ `<span class="cmp-controls">` +
+ `<label class="unfake-apply"><input type="radio" name="cmp-mode" value="h" checked /><span>${t("cmpH")}</span></label>` +
+ `<label class="unfake-apply"><input type="radio" name="cmp-mode" value="v" /><span>${t("cmpV")}</span></label>` +
+ `<label class="unfake-apply"><input type="radio" name="cmp-mode" value="overlay" /><span>${t("cmpOverlay")}</span></label>` +
+ `<button type="button" class="ghost cmp-play" data-tip="${t("tCmpPlay")}">▶</button>` +
+ `<button type="button" class="ghost cmp-hand" data-tip="${t("tHandTool")} (H)">${TOOL_ICONS.hand}</button>` +
+ `<span class="cmp-dl-wrap"><button type="button" class="ghost cmp-dl" data-tip="${t("tCmpDl")}">${t("cmpDl")} ▾</button>` +
+ `<div class="cmp-dl-menu" hidden>` +
+ `<button type="button" data-fmt="gif">GIF</button>` +
+ `<button type="button" data-fmt="webm">WebM · ${t("cmpDlAlpha")}</button>` +
+ `<button type="button" data-fmt="mp4">MP4 · ${t("cmpDlWhite")}</button>` +
+ `</div></span>` +
+ `<button type="button" class="ghost cmp-marks" data-tip="${t("tCmpMarks")}">${t("cmpMarks")}</button>` +
+ `<button type="button" class="ghost cmp-guides-toggle" data-tip="${t("tCmpGuidesToggle")}"></button>` +
+ `<button type="button" class="ghost cmp-guides-clear" data-tip="${t("tCmpGuidesClear")}">${t("cmpGuidesClear")}</button>` +
+ `<span class="cmp-zoom-label">×8</span>` +
+ `</span>` +
+ `<button type="button" class="ghost zoom-close">${t("zoomClose")}</button></div>` +
+ `<div class="cmp-hint">${t("cmpHint")}</div>` +
+ `<div class="cmp-body">` +
+ `<div class="cmp-list"></div>` +
+ `<div class="cmp-viewwrap"><div class="cmp-scroll"><div class="stage-pad">` +
+ `<div class="cmp-stage"><canvas class="cmp-canvas"></canvas><div class="cmp-guides"></div></div>` +
+ `</div></div></div>` +
+ `</div>` +
+ `<div class="cmp-legend"></div>` +
+ `</div>`;
+ document.body.appendChild(modal);
+ // 오프너 버튼에 남은 포커스 해제 — Space 홀드 팬이 버튼 가드에 걸리지 않게
+ if (document.activeElement instanceof HTMLElement) document.activeElement.blur();
+ const canvas = modal.querySelector(".cmp-canvas");
+ const guidesEl = modal.querySelector(".cmp-guides");
+ const listEl = modal.querySelector(".cmp-list");
+ const legend = modal.querySelector(".cmp-legend");
+ const zoomLabel = modal.querySelector(".cmp-zoom-label");
+
+ const imgs = new Map();
+ for (const tg of all) {
+ const im = new Image();
+ im.src = tg.frame.url;
+ im.onload = () => render();
+ imgs.set(tg.state, im);
+ }
+
+ // 큐레이션 완성 상태 합성 (maintainer 2026-07-18: 편집·조정된 모습이 비교본):
+ // 시퀀스의 cursor 번째 인스턴스를 캐노니컬+변형+픽셀편집+호흡 위상으로 굽는다.
+ const compositeFor = (name, cursor) => {
+ const play = playList(name);
+ const st = run.states.find((s) => s.name === name);
+ let idx;
+ let phase = 0;
+ if (play.length) {
+ const cur = ((cursor % play.length) + play.length) % play.length;
+ idx = play[cur];
+ const bcfg = stateBreathe(name);
+ if (bcfg) phase = breathePattern(bcfg, play.length)[cur] || 0;
+ } else {
+ const f0 = st && st.frames.find((fr) => fr.present);
+ if (!f0) return null;
+ idx = f0.index;
+ }
+ const f = frameOf(name, idx);
+ // 굽기가 읽는 파일로 그린다 — 신선도 기준과 같은 파일이어야 검사가 의미를 갖는다
+ const bakeSrc = f && bakeFrameUrl(name, f);
+ const image = bakeSrc ? img(bakeSrc) : null;
+ if (!(image && image.complete && image.naturalWidth)) return null;
+ const base = document.createElement("canvas");
+ base.width = run.cell.width;
+ base.height = run.cell.height;
+ const bx = base.getContext("2d");
+ bx.imageSmoothingEnabled = false;
+ drawFrameInto(bx, image, getTransform(name, idx), base.width, base.height,
+ snapScaleFor(name), getPixelOps(name, idx));
+ const bcfg = stateBreathe(name);
+ // 신선도 기준 = 재생 첫 슬롯의 키 (굽기가 해부를 확정하는 프레임).
+ const refKey = breatheReferenceKey(name);
+ // 위상 0 도 워프한다 — 진행파 지연 때문에 t=0 이 항등이 아니다 (굽기와 동일 계약)
+ const out = bcfg ? breatheComposeForPreview(base, bcfg, phase || 0, refKey) : base;
+ // 콘텐츠 bbox (합성 결과 기준 — 변형으로 옮겨진 위치 반영)
+ const d = out.getContext("2d").getImageData(0, 0, out.width, out.height).data;
+ let x0 = out.width, y0 = out.height, x1 = 0, y1 = 0;
+ for (let y = 0; y < out.height; y++) {
+ for (let x = 0; x < out.width; x++) {
+ if (d[(y * out.width + x) * 4 + 3] >= 40) {
+ if (x < x0) x0 = x;
+ if (y < y0) y0 = y;
+ if (x + 1 > x1) x1 = x + 1;
+ if (y + 1 > y1) y1 = y + 1;
+ }
+ }
+ }
+ if (x1 <= x0 || y1 <= y0) return null;
+ return { canvas: out, box: [x0, y0, x1, y1] };
+ };
+
+ // 좌측 목록 (토글)
+ const buildList = () => {
+ listEl.innerHTML = "";
+ for (const tg of all) {
+ const label = document.createElement("label");
+ label.className = "cmp-item";
+ const cb = document.createElement("input");
+ cb.type = "checkbox";
+ cb.checked = state.include.has(tg.state);
+ cb.addEventListener("change", () => {
+ if (cb.checked) state.include.add(tg.state);
+ else state.include.delete(tg.state);
+ render();
+ persistCompare();
+ });
+ const thumb = document.createElement("img");
+ thumb.src = tg.frame.url;
+ label.appendChild(cb);
+ label.appendChild(thumb);
+ label.appendChild(Object.assign(document.createElement("span"), { textContent: tg.state }));
+ listEl.appendChild(label);
+ }
+ };
+ buildList();
+
+ // 배치 계산: 디폴트 정렬 + 사용자 오프셋
+ const layout = () => {
+ const z = state.zoom;
+ const cells = [];
+ for (const tg of all) {
+ if (!state.include.has(tg.state)) continue;
+ // 배치(슬롯)는 항상 정지 상태(cursor 0) 기준 — 재생 중 높이가 숨쉬어도
+ // 캔버스 크기/슬롯이 흔들리지 않는다 (maintainer 2026-07-18). 그리기는 현재 프레임.
+ const still = compositeFor(tg.state, 0);
+ if (!still) continue;
+ const comp = anim.playing ? (compositeFor(tg.state, anim.cursors[tg.state] || 0) || still) : still;
+ const [x0, y0, x1, y1] = still.box;
+ cells.push({ tg, comp, still, box: still.box, w: x1 - x0, h: y1 - y0 });
+ }
+ const gap = 6;
+ const pad = 12;
+ const maxW = Math.max(1, ...cells.map((c) => c.w));
+ const maxH = Math.max(1, ...cells.map((c) => c.h));
+ let W;
+ let H;
+ if (state.mode === "h") {
+ W = pad * 2 + cells.reduce((a, c) => a + c.w, 0) + gap * Math.max(0, cells.length - 1);
+ H = pad * 2 + maxH;
+ let x = pad;
+ for (const c of cells) {
+ c.bx = x;
+ c.by = (H - pad) - c.h; // 공유 바닥
+ x += c.w + gap;
+ }
+ } else if (state.mode === "v") {
+ W = pad * 2 + maxW;
+ H = pad * 2 + cells.reduce((a, c) => a + c.h, 0) + gap * Math.max(0, cells.length - 1);
+ let y = pad;
+ for (const c of cells) {
+ c.bx = Math.round((W - c.w) / 2); // 공유 가로 중심
+ c.by = y;
+ y += c.h + gap;
+ }
+ } else {
+ W = pad * 2 + maxW;
+ H = pad * 2 + maxH;
+ for (const c of cells) {
+ c.bx = Math.round((W - c.w) / 2);
+ c.by = (H - pad) - c.h;
+ }
+ }
+ // 자유 배치 오프셋
+ for (const c of cells) {
+ const off = state.offsets[c.tg.state] || { dx: 0, dy: 0 };
+ c.dx = c.bx + off.dx;
+ c.dy = c.by + off.dy;
+ }
+ return { cells, W, H, z, pad };
+ };
+
+ const render = () => {
+ const { cells, W, H, z, pad } = layout();
+ zoomLabel.textContent = `×${state.zoom}`;
+ modal.querySelectorAll(".view-nav .vn-label").forEach((el) => { el.textContent = `×${state.zoom}`; });
+ // 첫 유효 렌더에서 한 번 중앙 정렬 — 사방 패딩 뷰포트는 auto-margin 센터링이
+ // 없어 스크롤을 직접 놓아야 한다 (이미지 로드 후 콘텐츠가 커진 시점 기준).
+ if (!state._centered && cells.length) {
+ state._centered = true;
+ requestAnimationFrame(() => centerView(scrollEl, stageEl));
+ }
+ canvas.width = W * z;
+ canvas.height = H * z;
+ canvas.style.width = `${W * z}px`;
+ canvas.style.height = `${H * z}px`;
+ const ctx = canvas.getContext("2d");
+ ctx.imageSmoothingEnabled = false;
+ ctx.clearRect(0, 0, canvas.width, canvas.height);
+ cells.forEach((c, i) => {
+ ctx.globalAlpha = state.mode === "overlay" && i > 0 ? 0.45 : 1;
+ const [x0, y0] = c.box;
+ // 셀 원점 정렬: 정지 슬롯 좌표계에 현재 프레임 전체 셀을 얹는다 —
+ // 호흡/모션은 슬롯 안에서만 움직이고 캔버스는 고정된다.
+ ctx.drawImage(c.comp.canvas, 0, 0, c.comp.canvas.width, c.comp.canvas.height,
+ (c.dx - x0) * z, (c.dy - y0) * z, c.comp.canvas.width * z, c.comp.canvas.height * z);
+ });
+ ctx.globalAlpha = 1;
+ // 디폴트 정렬 기준선 (희미하게): 수평 = 바닥, 수직 = 가로 중심
+ ctx.lineWidth = 1;
+ ctx.strokeStyle = "rgba(37, 99, 235, 0.55)";
+ if (state.mode !== "v") {
+ const gy = (H - pad) * z + 0.5;
+ ctx.beginPath(); ctx.moveTo(0, gy); ctx.lineTo(canvas.width, gy); ctx.stroke();
+ } else {
+ const gx = Math.round(W / 2) * z + 0.5;
+ ctx.beginPath(); ctx.moveTo(gx, 0); ctx.lineTo(gx, canvas.height); ctx.stroke();
+ }
+ // 가이드선 DOM
+ guidesEl.innerHTML = "";
+ guidesEl.style.width = `${canvas.width}px`;
+ guidesEl.style.height = `${canvas.height}px`;
+ guidesEl.style.display = state.guidesShow ? "" : "none";
+ const tgBtn = modal.querySelector(".cmp-guides-toggle");
+ if (tgBtn) tgBtn.textContent = state.guidesShow ? t("cmpGuidesHide") : t("cmpGuidesShow");
+ state.guides.forEach((g, gi) => {
+ const ln = document.createElement("div");
+ ln.className = `cmp-guide ${g.axis === "h" ? "gh" : "gv"}${gi === state.focus ? " focused" : ""}`;
+ if (g.axis === "h") ln.style.top = `${g.pos * z}px`;
+ else ln.style.left = `${g.pos * z}px`;
+ const tag = document.createElement("span");
+ tag.textContent = `${Math.round(g.pos)}px`;
+ ln.appendChild(tag);
+ ln.addEventListener("pointerdown", (ev) => {
+ ev.preventDefault();
+ ev.stopPropagation();
+ state.focus = gi;
+ ln.setPointerCapture(ev.pointerId);
+ let moved = false;
+ const onMove = (e2) => {
+ const r = canvas.getBoundingClientRect();
+ moved = true;
+ g.pos = g.axis === "h"
+ ? Math.max(0, Math.min(H, (e2.clientY - r.top) / z))
+ : Math.max(0, Math.min(W, (e2.clientX - r.left) / z));
+ // 드래그 중 render() 금지 — 가이드 DOM 재구축이 잡고 있는 요소를 파괴해
+ // 드래그가 끊긴다 (maintainer "잘 안 움직여"). 제자리 갱신만.
+ if (g.axis === "h") ln.style.top = `${g.pos * z}px`;
+ else ln.style.left = `${g.pos * z}px`;
+ tag.textContent = `${Math.round(g.pos)}px`;
+ };
+ const onUp = () => {
+ ln.removeEventListener("pointermove", onMove);
+ ln.removeEventListener("pointerup", onUp);
+ render(); // 드롭 후 전체 동기화 (라벨/포커스)
+ if (moved) pushHist();
+ };
+ ln.addEventListener("pointermove", onMove);
+ ln.addEventListener("pointerup", onUp);
+ });
+ guidesEl.appendChild(ln);
+ });
+ legend.innerHTML = cells.map((c) =>
+ `<span class="cmp-key"><span class="cmp-name">${escapeHtml(c.tg.state)}</span> ${c.w}×${c.h}px</span>`
+ ).join("");
+ };
+
+ // 스프라이트 드래그 / 빈 곳 클릭 = 가이드 추가 (Shift = 세로선)
+ canvas.addEventListener("pointerdown", (ev) => {
+ ev.preventDefault();
+ const r = canvas.getBoundingClientRect();
+ const { cells, z } = layout();
+ const lx = (ev.clientX - r.left) / z;
+ const ly = (ev.clientY - r.top) / z;
+ const hit = [...cells].reverse().find((c) =>
+ lx >= c.dx && lx < c.dx + c.w && ly >= c.dy && ly < c.dy + c.h);
+ if (hit) {
+ canvas.setPointerCapture(ev.pointerId);
+ const off = state.offsets[hit.tg.state] || (state.offsets[hit.tg.state] = { dx: 0, dy: 0 });
+ const sx = lx - off.dx;
+ const sy = ly - off.dy;
+ let moved = false;
+ const onMove = (e2) => {
+ moved = true;
+ off.dx = Math.round((e2.clientX - r.left) / z - sx);
+ off.dy = Math.round((e2.clientY - r.top) / z - sy);
+ render();
+ };
+ const onUp = () => {
+ canvas.removeEventListener("pointermove", onMove);
+ canvas.removeEventListener("pointerup", onUp);
+ if (moved) pushHist();
+ };
+ canvas.addEventListener("pointermove", onMove);
+ canvas.addEventListener("pointerup", onUp);
+ return;
+ }
+ // 빈 곳: 가이드 추가 + 포커스 (감춰져 있으면 자동으로 보이기)
+ state.guidesShow = true;
+ state.guides.push(ev.shiftKey ? { axis: "v", pos: lx } : { axis: "h", pos: ly });
+ state.focus = state.guides.length - 1;
+ render();
+ pushHist();
+ });
+
+ // 손 툴(토글) + Space 홀드 = 캔버스 팬 — 스크롤 컨테이너를 끈다 (maintainer 2026-07-19).
+ // wirePan 은 capture 라 스프라이트 드래그/가이드 추가보다 먼저 가로챈다.
+ // 2026-07-20 maintainer: 3계층 계약 통일 — 뷰포트(.cmp-scroll) + 사방 패딩(자유 팬) +
+ // 커서 앵커 줌 + 돋보기 위젯. 공용 배선 = view-nav.js.
+ let panTool = false;
+ const stageEl = modal.querySelector(".cmp-stage");
+ const scrollEl = modal.querySelector(".cmp-scroll");
+ const viewwrapEl = modal.querySelector(".cmp-viewwrap");
+ const handBtn = modal.querySelector(".cmp-hand");
+ handBtn.addEventListener("click", () => {
+ panTool = !panTool;
+ handBtn.classList.toggle("active", panTool);
+ scrollEl.classList.toggle("pan-tool", panTool);
+ });
+ wirePan(scrollEl, scrollEl, () => panTool);
+
+ // 배율: 휠(커서 앵커) + 돋보기 −/+/맞춤. 상한은 캔버스 물리 한계로 동적 클램프
+ // (W·H 는 콘텐츠 공간이라 줌과 무관 — canvas 픽셀 치수 = W×z 가 한계 대상).
+ const zoomMax = () => {
+ const { W, H } = layout();
+ return Math.max(2, Math.min(48, Math.floor(14000 / Math.max(1, W, H))));
+ };
+ const setZoom = (z, anchorX, anchorY) => {
+ z = Math.max(1, Math.min(zoomMax(), Math.round(z)));
+ if (z === state.zoom) return;
+ keepViewAnchor(scrollEl, stageEl, anchorX, anchorY, () => {
+ state.zoom = z;
+ render();
+ });
+ persistCompare();
+ };
+ const fitZoom = () => {
+ const { W, H } = layout();
+ const vr = scrollEl.getBoundingClientRect();
+ setZoom(Math.floor(Math.min((vr.width - 40) / Math.max(1, W), (vr.height - 40) / Math.max(1, H))));
+ centerView(scrollEl, stageEl);
+ };
+ viewwrapEl.appendChild(makeViewNavWidget({
+ zoomOut: () => setZoom(state.zoom - 1),
+ zoomIn: () => setZoom(state.zoom + 1),
+ fit: fitZoom,
+ }, { corner: true }));
+ scrollEl.addEventListener("wheel", (ev) => {
+ ev.preventDefault();
+ setZoom(state.zoom + (ev.deltaY < 0 ? 1 : -1), ev.clientX, ev.clientY);
+ }, { passive: false });
+
+ const onKey = (ev) => {
+ if (ev.key === "Escape") { close(); return; }
+ if (ev.code === "KeyH" && !(ev.metaKey || ev.ctrlKey || ev.altKey)) {
+ const a = document.activeElement;
+ if (!(a && (a.tagName === "INPUT" || a.tagName === "TEXTAREA" || a.isContentEditable))) {
+ ev.preventDefault();
+ handBtn.click();
+ return;
+ }
+ }
+ if (ev.code === "KeyZ" && (ev.metaKey || ev.ctrlKey)) { // code 기준 — 한글 IME 무관
+ ev.preventDefault();
+ ev.stopImmediatePropagation(); // 픽셀 편집 전역 라우터보다 비교 모달이 우선
+ restoreHist(ev.shiftKey ? hist.pos + 1 : hist.pos - 1);
+ return;
+ }
+ if ((ev.key === "Delete" || ev.key === "Backspace") && state.focus >= 0 && state.focus < state.guides.length) {
+ ev.preventDefault();
+ state.guides.splice(state.focus, 1);
+ state.focus = -1;
+ render();
+ pushHist();
+ }
+ };
+ const close = () => {
+ modal.remove();
+ document.removeEventListener("keydown", onKey, true);
+ };
+ modal.querySelectorAll('input[name="cmp-mode"]').forEach((el) =>
+ el.addEventListener("change", () => {
+ state.mode = el.value;
+ state.offsets = {}; // 정렬 버튼 = 디폴트 배치로 리셋 (maintainer 2026-07-18)
+ render();
+ pushHist();
+ }));
+ modal.querySelector(".zoom-close").addEventListener("click", close);
+ modal.querySelector(".zoom-backdrop").addEventListener("click", close);
+ // ── 자동 랜드마크 (maintainer 2026-07-18): 팔레트 신호로 신체 기준선을 감지해 가로
+ // 가이드로 추가. 첫 번째 켜진 스프라이트의 정지 합성본에서 행별 색 구성으로
+ // 정수리·턱선(위쪽 피부 밴드 끝)·망토 시작(파랑 첫 행)·벨트(파랑 구간 내
+ // 금색 버클 중심)·치맛단(파랑 끝)·발끝을 뽑는다. 뒷면처럼 신호가 없는
+ // 랜드마크는 조용히 생략 (감지 안 된 선을 지어내지 않는다).
+ const detectLandmarkRows = (cell) => {
+ const cv = cell.still.canvas;
+ const [x0, y0, x1, y1] = cell.still.box;
+ const d = cv.getContext("2d").getImageData(0, 0, cv.width, cv.height).data;
+ const rows = [];
+ for (let y = y0; y < y1; y++) {
+ const c = { skin: 0, blue: 0, gold: 0 };
+ for (let x = x0; x < x1; x++) {
+ const i = (y * cv.width + x) * 4;
+ if (d[i + 3] < 40) continue;
+ const r = d[i], g = d[i + 1], b = d[i + 2];
+ if (b > r + 20 && b > g + 20) c.blue++;
+ else if (r > 200 && g > 150 && b < 110 && r > b + 100) c.gold++;
+ else if (r > 195 && g > 155 && b > 120 && r - b > 30) c.skin++;
+ }
+ rows.push(c);
+ }
+ const marks = new Set([y0, y1]); // 정수리 · 발끝(바닥)
+ const skinIdx = rows.map((c, i) => (c.skin >= 2 ? i : -1)).filter((i) => i >= 0);
+ if (skinIdx.length) {
+ let chin = skinIdx[0];
+ for (const i of skinIdx.slice(1)) { if (i - chin <= 2) chin = i; else break; }
+ marks.add(y0 + chin + 1);
+ }
+ const blueIdx = rows.map((c, i) => (c.blue >= 2 ? i : -1)).filter((i) => i >= 0);
+ if (blueIdx.length) {
+ marks.add(y0 + blueIdx[0]);
+ marks.add(y0 + blueIdx[blueIdx.length - 1] + 1);
+ const belt = rows.map((c, i) => (c.gold >= 1 && i > blueIdx[0] ? i : -1)).filter((i) => i >= 0);
+ if (belt.length) marks.add(y0 + Math.round((belt[0] + belt[belt.length - 1]) / 2));
+ }
+ return [...marks].sort((a, b) => a - b);
+ };
+ modal.querySelector(".cmp-marks").addEventListener("click", () => {
+ const { cells } = layout();
+ if (!cells.length) { setStatus(t("cmpMarksNone"), "err"); return; }
+ const cell = cells[0];
+ const marksY = detectLandmarkRows(cell).map((y) => cell.dy + (y - cell.still.box[1]));
+ let added = 0;
+ for (const pos of marksY) {
+ if (state.guides.some((g) => g.axis === "h" && Math.abs(g.pos - pos) < 0.5)) continue;
+ state.guides.push({ axis: "h", pos });
+ added++;
+ }
+ if (added) { render(); pushHist(); }
+ setStatus(STR[lang].cmpMarksDone(added), "ok");
+ });
+ modal.querySelector(".cmp-guides-toggle").addEventListener("click", () => {
+ state.guidesShow = !state.guidesShow;
+ render();
+ persistCompare();
+ });
+ modal.querySelector(".cmp-guides-clear").addEventListener("click", () => {
+ if (!state.guides.length) return;
+ state.guides = [];
+ state.focus = -1;
+ state.guidesShow = true; // 다음에 긋는 선이 바로 보이게
+ render();
+ pushHist(); // Cmd/Ctrl+Z 로 전부 지우기 되돌리기 가능
+ });
+ // 비교 내보내기 (maintainer 2026-07-19 "다운로드 버튼 하나 + 팝오버"): 가상 시간
+ // 결정론 샘플 → 서버 조립. GIF / WebM(VP9 알파) / MP4(x264 화이트 배경).
+ const dlBtn = modal.querySelector(".cmp-dl");
+ const dlMenu = modal.querySelector(".cmp-dl-menu");
+ dlBtn.addEventListener("click", (ev) => {
+ ev.stopPropagation();
+ dlMenu.hidden = !dlMenu.hidden;
+ });
+ document.addEventListener("click", () => { dlMenu.hidden = true; });
+ const downloadCompare = async (fmt) => {
+ dlBtn.disabled = true;
+ dlBtn.textContent = "…";
+ const wasPlaying = anim.playing;
+ try {
+ const included = [...state.include];
+ // **파일을 만들기 전에** 멈춘다. `render()` 는 프리뷰 래퍼를 쓰는데, 그 래퍼는
+ // 거부를 잡아 워프하지 않은 원본을 돌려준다 — 화면에선 옳은 행동(알림 + 원본)이지만
+ // 여기서는 그 결과가 그대로 `toDataURL` 되어 **호흡이 빠진 파일**이 사용자 손에
+ // 들어가고 마지막에 "다운로드 완료" 초록 알림까지 떴다 (validator 실측 2026-07-26).
+ // row-export 는 같은 조건에서 이미 예외를 올려 멈춘다 — 두 내보내기가 정반대였다.
+ const resampled = [];
+ for (const name of included) {
+ const bcfg = stateBreathe(name);
+ if (!bcfg) continue;
+ breatheAssertFresh(breatheReferenceKey(name), bcfg);
+ if (breatheResamplesDifferently(name)) resampled.push(name);
+ }
+ if (resampled.length) setStatus(STR[lang].breatheResample(resampled.join(", ")), "warn");
+ const gcd = (a, b) => (b ? gcd(b, a % b) : a);
+ const cycles = included.map((name) => {
+ const st = run.states.find((s) => s.name === name);
+ const len = playList(name).length || 1;
+ return Math.max(100, Math.round(len * 1000 / Math.max(1, (st && st.fps) || 6)));
+ });
+ let total = cycles.reduce((a, b) => (a * b) / gcd(a, b), 100);
+ if (!isFinite(total) || total > 8000) total = Math.max(...cycles); // 관측 가능 컷
+ const step = 100;
+ const frames = [];
+ anim.playing = true; // 재생 합성 경로 사용
+ for (let ts = 0; ts < total; ts += step) {
+ for (const name of included) {
+ const st = run.states.find((s) => s.name === name);
+ anim.cursors[name] = Math.floor(ts * ((st && st.fps) || 6) / 1000);
+ }
+ render();
+ frames.push(canvas.toDataURL("image/png"));
+ }
+ anim.playing = wasPlaying;
+ render();
+ const res = await fetch("/api/compare-gif", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ frames, duration_ms: step, format: fmt }),
+ });
+ if (!res.ok) {
+ const data = await res.json().catch(() => ({}));
+ throw new Error(data.error || res.status);
+ }
+ const blob = await res.blob();
+ const link = document.createElement("a");
+ link.href = URL.createObjectURL(blob);
+ link.download = res.headers.get("X-Filename") || `compare.${fmt}`;
+ link.click();
+ URL.revokeObjectURL(link.href);
+ setStatus(STR[lang].cmpDlDone(fmt.toUpperCase()), "ok");
+ } catch (e) {
+ anim.playing = wasPlaying;
+ setStatus(t("cmpGifFail") + e.message, "err");
+ }
+ dlBtn.disabled = false;
+ dlBtn.textContent = `${t("cmpDl")} ▾`;
+ };
+ dlMenu.querySelectorAll("button[data-fmt]").forEach((b) =>
+ b.addEventListener("click", (ev) => {
+ ev.stopPropagation();
+ dlMenu.hidden = true;
+ downloadCompare(b.dataset.fmt);
+ }));
+
+ const modeInput = modal.querySelector(`input[name="cmp-mode"][value="${state.mode}"]`);
+ if (modeInput) modeInput.checked = true;
+ const playBtn = modal.querySelector(".cmp-play");
+ const animFrame = (ts) => {
+ if (!document.body.contains(modal)) return;
+ if (anim.playing) {
+ let dirty = false;
+ for (const name of state.include) {
+ const st = run.states.find((s) => s.name === name);
+ const fps = (st && st.fps) || 6;
+ if (!anim.last[name]) anim.last[name] = ts;
+ if (ts - anim.last[name] >= 1000 / Math.max(0.1, fps)) {
+ anim.last[name] = ts;
+ anim.cursors[name] = (anim.cursors[name] || 0) + 1;
+ dirty = true;
+ }
+ }
+ if (dirty) render();
+ }
+ requestAnimationFrame(animFrame);
+ };
+ playBtn.addEventListener("click", () => {
+ anim.playing = !anim.playing;
+ playBtn.textContent = anim.playing ? "⏸" : "▶";
+ render();
+ });
+ requestAnimationFrame(animFrame);
+ document.addEventListener("keydown", onKey, true); // capture — 전역 undo 라우터보다 먼저
+ render();
+ pushHist(); // 히스토리 바닥 = 초기 배치
+}
diff --git a/sprite_gen/serve/curator/src/display.js b/sprite_gen/serve/curator/src/display.js
new file mode 100644
index 0000000..c3f9f97
--- /dev/null
+++ b/sprite_gen/serve/curator/src/display.js
@@ -0,0 +1,445 @@
+// SPDX-License-Identifier: Apache-2.0
+// curator/display.js — 프레임 그리기 + 픽셀 언페이크/격자 표시 변형 동기화
+// 로드 순서 SSoT = index.html (classic script 전역 어휘 공유; 빌드 스텝 없음)
+
+// ── 프레임 공간 변환 SSoT (maintainer 지시 2026-07-19 "코드 좀 체계적으로") ──
+// 소스↔표시 좌표 수학과 "화면에 보이는 색" 샘플링은 여기 한 곳만 소유한다.
+// 다른 파일은 이 함수들을 쓰기만 한다 — 툴별 복붙 좌표 수학 금지.
+// 순변환: T(p) = M(p−c) + c + d (drawFrameInto 의 렌더 수학과 동일)
+
+function frameFwdXY(stateName, idx, x, y) {
+ const [cw, ch] = cellDims(stateName);
+ const tr = getTransform(stateName, idx);
+ const m = matrixOf(tr);
+ return [m.m00 * (x - cw / 2) + m.m01 * (y - ch / 2) + cw / 2 + tr.dx,
+ m.m10 * (x - cw / 2) + m.m11 * (y - ch / 2) + ch / 2 + tr.dy];
+}
+
+function frameInvXY(stateName, idx, x, y) {
+ const [cw, ch] = cellDims(stateName);
+ const tr = getTransform(stateName, idx);
+ const m = matrixOf(tr);
+ const det = m.m00 * m.m11 - m.m01 * m.m10 || 1;
+ const ux = x - cw / 2 - tr.dx;
+ const uy = y - ch / 2 - tr.dy;
+ return [(m.m11 * ux - m.m01 * uy) / det + cw / 2,
+ (-m.m10 * ux + m.m00 * uy) / det + ch / 2];
+}
+
+// 포인터 이벤트 → 소스(저장) 공간 좌표. 표시가 어떤 모드든 저장은 항상 소스 공간.
+// 양자화 표시(비트맵 = 표시 공간)에선 포인터 원좌표가 아니라 커서가 가리키는
+// "표시된 픽셀(블록)"의 샘플 중심을 역변환한다 — 래스터라이즈가 색을 집어온 바로
+// 그 소스 픽셀이 편집 대상이 된다. 원좌표를 그대로 역변환하면 소수 스케일/이동
+// (예: scale 0.907, dy 1.53)에서 블록 경계마다 이웃 소스 픽셀로 샌다
+// (회귀 2026-07-19 maintainer "포인터랑 위치가 완벽하게 안 맞는데").
+function pointerSrcXY(stage, stateName, idx, e2) {
+ const [cw, ch] = cellDims(stateName);
+ const r = stage.getBoundingClientRect();
+ let dx0 = ((e2.clientX - r.left) / r.width) * cw;
+ let dy0 = ((e2.clientY - r.top) / r.height) * ch;
+ const canvas = stage.querySelector(".snap-canvas");
+ if (canvas && canvas.style.display === "block" && !canvas.style.transform) {
+ const s = snapScaleFor(stateName) || 1;
+ dx0 = (Math.floor(dx0 / s) + 0.5) * s;
+ dy0 = (Math.floor(dy0 / s) + 0.5) * s;
+ }
+ return frameInvXY(stateName, idx, dx0, dy0);
+}
+
+// 스포이드 진실 = "화면에 보이는 그 색". 표시 파이프라인이 양자화 캔버스든
+// (비트맵 = 표시 공간) CSS 변형 캔버스든 (비트맵 = 소스 공간), 실제 렌더된
+// 비트맵에서 집는다 — 소스 픽셀을 따로 재계산하면 픽셀 언페이크 재양자화와
+// 어긋난 색이 잡힌다 (회귀 2026-07-19 maintainer "스포이드가 다른 색을 잡음").
+function sampleDisplayedColor(stage, stateName, idx, e2) {
+ const canvas = stage.querySelector(".snap-canvas");
+ if (!(canvas && canvas.style.display === "block" && canvas.width)) return null;
+ const r = stage.getBoundingClientRect();
+ // 좌표는 셀 공간에서 다룬다 — frameInvXY 가 셀 공간 계약이라 슈퍼샘플 배율(ss)을
+ // 섞으면 역변환이 어긋난다. 비트맵 인덱싱 직전에만 ss 를 곱한다.
+ const [cw, ch] = cellDims(stateName);
+ const ss = canvas.width / cw;
+ let x = ((e2.clientX - r.left) / r.width) * cw;
+ let y = ((e2.clientY - r.top) / r.height) * ch;
+ if (canvas.style.transform) [x, y] = frameInvXY(stateName, idx, x, y);
+ x = Math.floor(x * ss);
+ y = Math.floor(y * ss);
+ if (!(x >= 0 && x < canvas.width && y >= 0 && y < canvas.height)) return null;
+ const d = canvas.getContext("2d").getImageData(x, y, 1, 1).data;
+ if (d[3] < 40) return null; // 투명 픽셀은 집을 색이 없다
+ return "#" + [d[0], d[1], d[2]].map((v) => v.toString(16).padStart(2, "0")).join("");
+}
+
+// 변형을 셀 캔버스에 NEAREST 로 그리고, 논리 격자(snap px/논리픽셀)로 재양자화한다.
+// curation.apply_transform 의 snap_scale 경로를 캔버스로 미러링 — 드래그/회전 중에도
+// 스프라이트가 셀 고정 격자에 실시간으로 스냅되어 보인다 (격자는 그대로, 그림이 스냅).
+// `ss` = 슈퍼샘플 배율 (기본 1). 저장·입력 좌표는 **항상 셀 공간**(cw×ch)이고 ss 는
+// 렌더 해상도만 올린다 — 소스 표시 모드에서 고해상 원본 트윈(700~900px)을 셀 크기
+// 캔버스에 그리면 64px 로 파괴되기 때문이다 (maintainer 2026-07-24 발견: img 는 숨겨지고
+// 64×64 snap-canvas 가 실제 표시면이었다). 양자화 모드(snap)는 결과 격자를 보여주는
+// 것이 목적이라 ss=1 이며, 이 둘은 배타적이다(quantize 이면 ss 를 올리지 않는다).
+function drawFrameInto(ctx, image, t, cw, ch, snap, edits, ss = 1) {
+ ctx.imageSmoothingEnabled = false; // 항상 NEAREST — 베이스(raw→논리) 표시도 픽셀 유지
+ // 사이드카 픽셀 편집은 변형 이전(소스) 공간이다 — 굽기(apply_pixel_edits →
+ // apply_transform, compose_atlas.py)와 같은 순서로 편집을 먼저 소스에 합성한 뒤
+ // 함께 변형한다. (회귀 2026-07-17: 변형 후에 고정 좌표로 덧그려서, 캐릭터를
+ // 옮기면 편집 픽셀만 제자리에 남았다 — maintainer 발견.)
+ let source = image;
+ if (edits) {
+ const src = drawFrameInto._src || (drawFrameInto._src = document.createElement("canvas"));
+ src.width = cw * ss;
+ src.height = ch * ss;
+ const sctx = src.getContext("2d");
+ sctx.imageSmoothingEnabled = false;
+ sctx.clearRect(0, 0, src.width, src.height);
+ sctx.drawImage(image, 0, 0, src.width, src.height);
+ // 편집 좌표는 셀 공간 — 렌더 해상도에서는 한 칸이 ss×ss 블록이다.
+ for (const [key, val] of Object.entries(edits)) {
+ const [x, y] = key.split(",").map(Number);
+ if (!(x >= 0 && x < cw && y >= 0 && y < ch)) continue;
+ if (val) {
+ sctx.fillStyle = val;
+ sctx.fillRect(x * ss, y * ss, ss, ss);
+ } else {
+ sctx.clearRect(x * ss, y * ss, ss, ss);
+ }
+ }
+ source = src;
+ }
+ const m = matrixOf(t);
+ ctx.save();
+ ctx.translate((cw / 2 + t.dx) * ss, (ch / 2 + t.dy) * ss);
+ ctx.transform(m.m00, m.m10, m.m01, m.m11, 0, 0);
+ ctx.drawImage(source, (-cw / 2) * ss, (-ch / 2) * ss, cw * ss, ch * ss);
+ ctx.restore();
+ if (snap && snap > 1) {
+ const lw = Math.max(1, Math.floor(cw / snap));
+ const lh = Math.max(1, Math.floor(ch / snap));
+ const tmp = drawFrameInto._tmp || (drawFrameInto._tmp = document.createElement("canvas"));
+ tmp.width = lw;
+ tmp.height = lh;
+ const tctx = tmp.getContext("2d");
+ tctx.imageSmoothingEnabled = false;
+ tctx.clearRect(0, 0, lw, lh);
+ tctx.drawImage(ctx.canvas, 0, 0, cw, ch, 0, 0, lw, lh);
+ ctx.clearRect(0, 0, cw, ch);
+ ctx.imageSmoothingEnabled = false;
+ ctx.drawImage(tmp, 0, 0, lw, lh, 0, 0, lw * snap, lh * snap);
+ }
+}
+
+// 픽셀 언페이크 격자 오버레이: 픽셀 언페이크가 실제로 스냅한 논리 픽셀 간격을 그린다.
+// run.pixelUnfake.scale = 논리 픽셀 1칸이 차지하는 셀 픽셀 수 (extract 의 pp_scale).
+// 예전엔 셀 픽셀마다(scale 무시) 그어서, logical_height < cell 인 런에서 실제 스냅
+// 격자보다 촘촘한 거짓 격자를 보여줬다. 픽셀 언페이크가 아닌 런은 격자 자체가 없다.
+function sizePxGrids() {
+ document.querySelectorAll(".card").forEach(updateCardGrid);
+ syncPixelScaling();
+}
+
+// ── 표시 샘플링 판정 SSoT (maintainer 2026-07-24: "절대 원본 아님") ──
+// "이 이미지를 nearest 로 그릴 것인가" 는 하나의 사실로만 답한다:
+// **표시 크기가 원본 크기보다 큰가.** 확대면 nearest(픽셀아트 블록 보존),
+// 축소면 브라우저 기본 보간(전 픽셀 기여).
+//
+// 예전엔 이 판정이 여섯 군데로 흩어져 서로 다르게 답했고, 그중 무조건 규칙
+// (`.stage img { image-rendering: pixelated }`)이 나머지를 전부 덮어써서
+// 조건 판정이 죽은 코드가 돼 있었다. 그 결과 고해상 orig 트윈(896px)이
+// 카드(~130px)에서 nearest 데시메이션을 겪어 전체 픽셀의 2.1% 만 표본으로
+// 남았고(경계 하드점프 346 vs 보간 117), 화면이 "양자화된 형태"로 보였다.
+// 트윈 해상도 수리(v1.56.84)가 증상을 키운 것도 같은 뿌리다 — 파일이 커질수록
+// 버리는 픽셀이 늘어난다.
+//
+// 기하가 바뀌면(zoom·resize·패널 토글) 답도 바뀌므로 1회성 부여가 아니라
+// 기하 갱신 지점(sizePxGrids)에서 매번 재평가하고, 조건이 깨지면 해제한다.
+// 대상 = 사용자가 "그림" 으로 보는 표시면 **전부**. 판정 기준은 엘리먼트 종류가
+// 아니라 "버퍼 해상도와 표시 해상도가 다를 수 있는가" 다.
+//
+// `snap-canvas` 는 한때 "표시 해상도로 직접 그리므로 대상 아님" 으로 제외돼 있었는데,
+// 소스 표시 모드를 소스 해상도로 올리면서(v1.56.87) 그 전제가 깨졌다. 제외는 그대로
+// 뒀더니 이 플랜이 없애려던 병(무조건 규칙이 기하 판정을 덮어씀)이 새 표시면으로
+// 이사했다 — 896 버퍼를 152 에 nearest 로 떨궈 2.9% 만 살아남았다 (validator R1).
+// 교훈: 버퍼 해상도를 올린 것과 표시 샘플링을 지킨 것은 다른 일이다.
+//
+// 진짜 예외는 `cmp-canvas` 하나뿐이다 — 그건 JS 가 표시 크기에 맞춰 직접 래스터를
+// 그리므로 버퍼=표시이고, 그 nearest 는 "무엇을 그리는가" 의 일부다.
+const PIXEL_SCALE_TARGETS = [
+ ".stage img", // 프레임 카드 · 줌 모달 · 아카이브 카드
+ ".stage canvas.snap-canvas", // 편집·변형 프레임의 실제 표시면
+ ".base-row .base-stage img", // 베이스 아이덴티티
+ ".preview canvas", // 줄 재생 미리보기
+ ".breathe-strip .bs-cell canvas", // 호흡 필름스트립
+ ".tree-node img", // 파이프라인 트리 썸네일
+ ".ap-card img", // 후보 풀 썸네일
+ "#compare-modal .cmp-item img", // 비교 모달 썸네일
+ ".final-atlas .atlas-sheet img", // 최종 아틀라스 시트
+ ".recolor-variants .rc-stage img", // 컬러웨이 비교 스테이지
+ ".recolor-variants .rc-swatch img", // 컬러웨이 프레임 썸네일
+].join(", ");
+
+function syncPixelScaling(root) {
+ (root || document).querySelectorAll(PIXEL_SCALE_TARGETS).forEach(applyPixelScaling);
+}
+
+// 소스 표시 캔버스의 렌더 배율 — 소스가 셀보다 크면 그만큼 올려 원본 해상도를 보존한다.
+// 상한 16 은 메모리 바운드일 뿐 화질 정책이 아니다 (64셀 × 16 = 1024px).
+function superSampleFor(source, cellWidth) {
+ const natural = source && (source.naturalWidth || source.width);
+ if (!natural || !cellWidth) return 1;
+ // 상한은 배율이 아니라 **캔버스 픽셀 바운드**다 (엔진 트윈 캡 2048//cell 과 동형).
+ // 고정 ×16 은 논리셀이 작은 베이스(cols≈28, raw≈958)에서 448px 로 눌러
+ // NEAREST 데시메이션을 만들었다 — 배율 상한을 셀에 비례시키면 그 병이 없다.
+ const cap = Math.max(1, Math.floor(2048 / cellWidth));
+ return Math.max(1, Math.min(cap, Math.round(natural / cellWidth)));
+}
+
+// 원본 기하: <img> 는 naturalWidth, <canvas> 는 그리기 버퍼 width.
+// 표시 기하는 clientWidth (레이아웃 후 실제 CSS 픽셀).
+//
+// **원본 기하는 src 가 바뀌면 같이 바뀐다** — 픽셀 언페이크 토글은 레이아웃을 안 건드리고
+// 이미지 소스만 64px 출력 ↔ 700~900px 원본 트윈으로 갈아끼운다. 그래서 판정 재평가는
+// 레이아웃 이벤트만으로 부족하고 **이미지 로드**에도 걸려야 한다 — 안 그러면 확대용
+// nearest 가 축소된 원본 위에 stale 로 남아, 토글을 끄면 원본이 2% 표본으로
+// 데시메이션돼 보인다 (maintainer 2026-07-24 "달리기 시퀀스... 절대 원본 아님").
+function applyPixelScaling(el) {
+ const natural = el.tagName === "CANVAS" ? el.width : el.naturalWidth;
+ const shown = el.clientWidth;
+ if (!natural || !shown) return; // 아직 로드/레이아웃 전 — load 위임 훅과 sizePxGrids 가 다시 부른다
+ el.classList.toggle("px-upscale", shown > natural);
+}
+
+// 재평가 트리거 ③ — 이미지 로드 (최초 렌더 + 모든 src 교체를 한 훅으로 덮는다).
+// load 는 버블링하지 않아 capture 로 받는다. 호출부마다 손으로 부르면 판정이 다시
+// 흩어지므로(이 플랜이 없앤 바로 그 병) 위임 훅 하나로 둔다.
+function installPixelScalingLoadHook() {
+ document.addEventListener("load", (ev) => {
+ const el = ev.target;
+ if (el instanceof HTMLImageElement && el.matches(PIXEL_SCALE_TARGETS)) applyPixelScaling(el);
+ }, true);
+}
+
+// 줄 단위 격자: 그 줄의 격자 체크박스가 켜져 있을 때만 그린다.
+// - 픽셀 언페이크 표시 줄: 출력 격자(빨/파, 셀 픽셀 눈금) — 결과가 앉은 격자 그 자체.
+// 셀에 고정이다: 이동/회전 변형은 스프라이트가 이 고정 래스터에 재양자화되는 것이지
+// 래스터가 따라 움직이는 게 아니다 (maintainer 확정 2026-07-14 실시간 스냅 동작).
+// - 원본(plain) 표시 줄: 최종 대응 격자(초록) — 최종 픽셀 콘텐츠 bbox 를 픽셀 수만큼
+// 균등 분할해 원본 위에 겹친다. 칸 하나 = 최종 픽셀 하나 (칸 수 = 픽셀 수 보장).
+// 콘텐츠 기준 격자이므로 이동(dx/dy)·좌우반전은 따라간다 (maintainer 지적 2026-07-15).
+// 회전/기울임/배율 변형은 소스↔결과 대응이 더 이상 직사각 격자가 아니라 숨긴다 —
+// 비축정렬 상태로 가짜 격자를 겹치지 않는다 (결과 픽셀은 픽셀 언페이크 뷰가 보여준다).
+// 절단선(manifest input_grids)은 conform 축소 폐지(v1.56.22) 이후 1차 절단이 곧 최종
+// 대응이라 표시 격자로 쓴다 — 아래 updateZoomGrid 주석 참조 (구 서술: "축소가 칸을
+// 합칠 수 있어 진단 기록으로만" 은 그 폐지 전 이야기다).
+// 측정/계약이 없는 줄은 오버레이를 숨긴다 — 가짜 격자 금지.
+function updateCardGrid(card) {
+ const overlay = card.querySelector(".pxgrid");
+ const ingrid = card.querySelector(".ingrid");
+ if (!overlay && !ingrid) return;
+ const stage = card.querySelector(".stage");
+ const cardState = card.dataset.state;
+ const isBaseCard = cardState === BASE_STATE;
+ const st = run.states.find((s) => s.name === cardState);
+ const frame = isBaseCard ? frameOf(BASE_STATE, 0) : (st && st.frames[Number(card.dataset.idx)]);
+ const on = !!gridStates[cardState];
+ const plainShown = (isBaseCard || unfakeTwinStates.has(cardState)) && !unfakeOn(cardState);
+ const scale = isBaseCard ? 1
+ // 격자 간격은 항상 정해진다: 줄별 실측 > 런 계약 > 항등 1. null 이 되는
+ // 경로가 없어야 오버레이가 조건부로 사라지지 않는다 (maintainer 2026-07-24).
+ : ((st && st.pixelScale) || (run.pixelUnfake && run.pixelUnfake.scale) || 1);
+ const t = frame ? getTransform(card.dataset.state, frame.index) : null;
+ const axisAligned = !t || (!t.rotate && t.scale === 1 && !t.shx && !t.shy);
+ const useFinal = on && plainShown && frame && frame.contentBox && scale && stage && axisAligned;
+ if (ingrid) {
+ if (useFinal) {
+ drawFinalGrid(ingrid, stage, frame.contentBox, scale, t, frame.inputGrid || null);
+ ingrid.style.display = "block";
+ } else {
+ ingrid.style.display = "none";
+ }
+ }
+ const step = on && !useFinal && !plainShown ? scale : null;
+ if (!overlay) return;
+ if (!step || !stage) { overlay.style.display = "none"; return; }
+ overlay.style.display = "block";
+ const ds = (stage.clientWidth / cellDims(cardState)[0]) * step;
+ overlay.style.backgroundSize = `${ds}px ${ds}px`;
+}
+
+// 최종 대응 격자: 최종 픽셀 콘텐츠 bbox(셀 좌표)를 논리 픽셀 수만큼 균등 분할해
+// 원본 쌍둥이 위에 그린다 — 초록 칸 하나가 결과 픽셀 하나에 정확히 대응한다.
+// 축정렬 변형(이동 dx/dy, 좌우반전)은 bbox 를 같은 규칙(CSS: 중심 기준 반전 후 이동)으로
+// 옮겨 콘텐츠를 따라간다. 비축정렬 변형은 호출 전에 걸러진다 (updateCardGrid).
+function drawFinalGrid(canvas, stage, box, scale, t, inputGrid) {
+ const w = Math.max(1, Math.round(stage.clientWidth));
+ const h = Math.max(1, Math.round(stage.clientHeight));
+ canvas.width = w;
+ canvas.height = h;
+ const ctx = canvas.getContext("2d");
+ ctx.clearRect(0, 0, w, h);
+ ctx.strokeStyle = "rgba(21, 128, 61, 0.6)";
+ ctx.lineWidth = 1;
+ const sx = w / run.cell.width;
+ const sy = h / run.cell.height;
+ const dx = t ? t.dx : 0;
+ const dy = t ? t.dy : 0;
+ const cw = run.cell.width;
+ // 추출이 검출한 실제 절단선(input_grids, 쌍둥이 셀 좌표)이 있으면 그것을 그린다 —
+ // 균등 분할은 끝점만 맞고 중간이 어긋난다 (maintainer 발견 2026-07-18 down_lie:
+ // "머리끝발끝은 맞는데 중간 픽셀이 하나도 안 맞아"). conform 축소 폐지(v1.56.22)로
+ // 1차 절단선이 곧 최종 대응이 됐다. 없는 프레임(구세대 캐시·테이크)만 균등 근사.
+ // 기록 격자 신뢰 게이트 (회귀 2026-07-18 side_idle: 최종 31칸인데 기록은 45칸 —
+ // 반피치 하모닉 오검출): 칸수가 최종 픽셀 수와 ±1 이상 어긋나면 그 기록은 버린다.
+ // 균등 격자는 "칸 수 = 최종 픽셀 수" 를 보장한다 (가짜 격자 금지).
+ //
+ // **층위 주의 — 이 가드는 엔진측 단정의 대체물이 아니다** (plan grid-record-exactness):
+ // · 여기(표시측)는 **가드**다: 기록이 거짓이어도 화면에 가짜 격자를 그리지 않는 게 임무라
+ // 실패 방향이 "격자를 접는다" 이고, 그래서 ±1 관용이 맞다 (구세대 캐시·테이크 프레임처럼
+ // 기록이 없거나 근사인 정상 경우도 통과시켜야 한다).
+ // · 엔진측(`tests/test_grid_record_exactness.py`)은 **단정**이다: 기록 칸수 == 최종 픽셀 수
+ // 정확 일치를 요구하고, 반피치 하모닉 mutant 로 그 단정이 실제로 잡는지까지 고정한다.
+ // 이 가드를 "이제 기록이 참이니 완화/제거" 하면 안 된다 — 그러면 엔진 회귀가 조용히
+ // 화면으로 새어나온다. 두 층위는 함께 있어야 한다 (실측 2026-07-25: 10조합 delta 0).
+ if (inputGrid && Array.isArray(inputGrid.x) && Array.isArray(inputGrid.y)) {
+ const expCols = Math.max(1, Math.round((box[2] - box[0]) / scale));
+ const expRows = Math.max(1, Math.round((box[3] - box[1]) / scale));
+ if (Math.abs((inputGrid.x.length - 1) - expCols) > 1 || Math.abs((inputGrid.y.length - 1) - expRows) > 1) {
+ inputGrid = null;
+ }
+ }
+ if (inputGrid && Array.isArray(inputGrid.x) && Array.isArray(inputGrid.y) && inputGrid.x.length > 1 && inputGrid.y.length > 1) {
+ // 검출 절단선의 매핑 비율 오차가 중간에서 누적된다 (회귀 2026-07-18 down_lie:
+ // 28칸이 27.2px 로 눌려 끝만 맞고 중간 전부 어긋남) — 끝점을 최종 콘텐츠
+ // 박스에 앵커하고 검출 비례만 유지하도록 정규화한다.
+ const norm = (edges, lo, hi) => {
+ const e0 = edges[0];
+ const e1 = edges[edges.length - 1];
+ if (e1 - e0 <= 0) return edges;
+ return edges.map((e) => lo + ((e - e0) * (hi - lo)) / (e1 - e0));
+ };
+ inputGrid = { x: norm(inputGrid.x, box[0], box[2]), y: norm(inputGrid.y, box[1], box[3]) };
+ const xs = t && t.flipX ? inputGrid.x.map((e) => cw - e).reverse() : inputGrid.x;
+ const yTop = (inputGrid.y[0] + dy) * sy;
+ const yBot = (inputGrid.y[inputGrid.y.length - 1] + dy) * sy;
+ const xLeft = (xs[0] + dx) * sx;
+ const xRight = (xs[xs.length - 1] + dx) * sx;
+ for (const e of xs) {
+ const px = Math.round((e + dx) * sx) + 0.5;
+ ctx.beginPath(); ctx.moveTo(px, yTop); ctx.lineTo(px, yBot); ctx.stroke();
+ }
+ for (const e of inputGrid.y) {
+ const py = Math.round((e + dy) * sy) + 0.5;
+ ctx.beginPath(); ctx.moveTo(xLeft, py); ctx.lineTo(xRight, py); ctx.stroke();
+ }
+ return;
+ }
+ const cellsX = Math.max(1, Math.round((box[2] - box[0]) / scale));
+ const cellsY = Math.max(1, Math.round((box[3] - box[1]) / scale));
+ let bx0 = box[0], bx1 = box[2];
+ if (t && t.flipX) { [bx0, bx1] = [cw - box[2], cw - box[0]]; }
+ const x0 = (bx0 + dx) * sx, x1 = (bx1 + dx) * sx;
+ const y0 = (box[1] + dy) * sy, y1 = (box[3] + dy) * sy;
+ for (let k = 0; k <= cellsX; k++) {
+ const px = Math.round(x0 + ((x1 - x0) * k) / cellsX) + 0.5;
+ ctx.beginPath(); ctx.moveTo(px, y0); ctx.lineTo(px, y1); ctx.stroke();
+ }
+ for (let k = 0; k <= cellsY; k++) {
+ const py = Math.round(y0 + ((y1 - y0) * k) / cellsY) + 0.5;
+ ctx.beginPath(); ctx.moveTo(x0, py); ctx.lineTo(x1, py); ctx.stroke();
+ }
+}
+
+function refreshVariantImages() {
+ document.querySelectorAll(".card").forEach((card) => {
+ if (!card.dataset.state) return;
+ const idx = Number(card.dataset.idx);
+ const f = frameOf(card.dataset.state, idx); // 복제 인스턴스도 원본 이미지로 해석
+ const el = card.querySelector(".stage img");
+ if (f && el) {
+ el.src = frameUrl(card.dataset.state, f);
+ // src 가 바뀌면 원본 기하가 바뀐다. 새 이미지 로드는 위임 훅이 받지만,
+ // 같은 src 재대입(캐시·pp 무변)은 load 가 안 뜨므로 여기서 한 번 더 답한다.
+ applyPixelScaling(el);
+ // 변형 표시 모드(캔버스 스냅 ↔ CSS)도 pp 상태에 맞게 다시 결정
+ if (f.present) applyCardTransform(card.querySelector(".stage"), card.dataset.state, idx);
+ }
+ });
+ sizePxGrids();
+}
+
+// aggregate checkbox state: checked = all on, unchecked = all off, else indeterminate
+function syncAggregate(checkbox, names, isOn) {
+ if (!checkbox || !names.size) return;
+ const vals = [...names].map(isOn);
+ const allOn = vals.every(Boolean);
+ checkbox.checked = allOn;
+ checkbox.indeterminate = !allOn && !vals.every((v) => !v);
+}
+
+// per-state row checkboxes + the header toggle-all checkboxes reflect unfakeStates/gridStates
+function syncUnfakeControls() {
+ document.querySelectorAll(".pp-state-check").forEach((el) => {
+ el.checked = unfakeOn(el.dataset.state);
+ });
+ syncAggregate(document.getElementById("unfake-apply"),
+ new Set(run.states.map((s) => s.name)), unfakeOn);
+}
+
+function syncGridControls() {
+ document.querySelectorAll(".grid-state-check").forEach((el) => {
+ el.checked = !!gridStates[el.dataset.state];
+ });
+ syncAggregate(document.getElementById("pxgrid-check"),
+ new Set(run.states.map((s) => s.name)), (n) => !!gridStates[n]);
+}
+
+function drawGroundGrid(stage) {
+ const canvas = stage.querySelector(".grid-overlay");
+ if (!canvas || !run.iso) return;
+ const rect = stage.getBoundingClientRect();
+ const W = Math.round(rect.width);
+ const H = Math.round(rect.height);
+ if (!W || !H) return;
+ canvas.width = W;
+ canvas.height = H;
+ const ctx = canvas.getContext("2d");
+ ctx.clearRect(0, 0, W, H);
+
+ // cell pixels -> displayed pixels
+ const ds = W / run.cell.width;
+ const tw = run.iso.tile.width * ds; // diamond full width (2:1 -> width = 2*height)
+ const th = run.iso.tile.height * ds; // diamond full height
+ const [ax, ay] = run.iso.anchor_pixel;
+ const ox = ax * ds; // anchor in displayed px
+ const oy = ay * ds;
+
+ // grid-(gx,gy) center on screen, 2:1 dimetric, anchored at the meta anchor
+ const center = (gx, gy) => [ox + (gx - gy) * (tw / 2), oy + (gx + gy) * (th / 2)];
+ const diamond = (cx, cy) => {
+ ctx.beginPath();
+ ctx.moveTo(cx, cy - th / 2);
+ ctx.lineTo(cx + tw / 2, cy);
+ ctx.lineTo(cx, cy + th / 2);
+ ctx.lineTo(cx - tw / 2, cy);
+ ctx.closePath();
+ };
+
+ const R = 4;
+ ctx.lineWidth = 1;
+ for (let gx = -R; gx <= R; gx++) {
+ for (let gy = -R; gy <= R; gy++) {
+ const [cx, cy] = center(gx, gy);
+ diamond(cx, cy);
+ const anchorTile = gx === 0 && gy === 0;
+ ctx.strokeStyle = anchorTile ? "rgba(37,99,235,0.9)" : "rgba(37,99,235,0.25)";
+ ctx.stroke();
+ }
+ }
+ // axis guide lines through the anchor (the true 2:1 slopes)
+ ctx.strokeStyle = "rgba(217,119,6,0.9)";
+ ctx.lineWidth = 1.5;
+ for (const [sx, sy] of [[1, 1], [1, -1]]) {
+ ctx.beginPath();
+ ctx.moveTo(ox - sx * tw * 3, oy - sy * th * 3);
+ ctx.lineTo(ox + sx * tw * 3, oy + sy * th * 3);
+ ctx.stroke();
+ }
+}
diff --git a/sprite_gen/serve/curator/src/gen-trigger.js b/sprite_gen/serve/curator/src/gen-trigger.js
new file mode 100644
index 0000000..c373834
--- /dev/null
+++ b/sprite_gen/serve/curator/src/gen-trigger.js
@@ -0,0 +1,56 @@
+// SPDX-License-Identifier: Apache-2.0
+// curator/gen-trigger.js — 서버측 생성 트리거의 단일 관용구 (표면 계약 SSoT)
+// 로드 순서 SSoT = index.html (classic script 전역 어휘 공유; 빌드 스텝 없음)
+//
+// 모든 "서버에서 생성이 도는 버튼"(보간/리롤, 이후 추가되는 것 포함)은 같은 계약을 탄다:
+// 버튼 클릭 = 파라미터 팝오버(.gen-pop) 토글 → 팝오버 안 공용 모델 select → 실행 버튼
+// 실행 = 스피너(.gen-spin) + 진행도 워치 + POST + 에러 언랩 + 완료 시 뷰 새로고침
+// 모델 표기(GPT/Grok ↔ codex/grok)와 실행 시퀀스는 이 파일만 소유한다. 트리거마다
+// 다른 제스처(Alt클릭 모델 선택 등)를 만들지 않는다 — 회귀 2026-07-19 maintainer
+// "보간은 클릭하면 모델선택이고 리롤은 alt클릭이고 다 지멋대로".
+
+const GEN_PROVIDERS = [
+ { value: "codex", label: "GPT" },
+ { value: "grok", label: "Grok" },
+];
+
+// 공용 모델 선택 위젯 — 표기/순서/기본값(codex)의 유일한 자리
+function makeProviderSelect() {
+ const sel = document.createElement("select");
+ for (const p of GEN_PROVIDERS) {
+ const opt = document.createElement("option");
+ opt.value = p.value;
+ opt.textContent = p.label;
+ sel.appendChild(opt);
+ }
+ return sel;
+}
+
+// 공용 실행 시퀀스 — 성공 시 run 세대가 바뀌므로 항상 뷰를 새로고침한다.
+// 실패 시 버튼/라벨을 복구하고 진행도 워치를 멈춘다 (조용한 부분 성공 없음).
+async function runServerGeneration({ url, body, goBtn, buttons, busyMsg, doneMsg, failPrefix }) {
+ const goLabel = goBtn.textContent;
+ const all = [goBtn, ...(buttons || [])];
+ for (const b of all) b.disabled = true;
+ goBtn.innerHTML = '<span class="gen-spin" aria-label="generating"></span>';
+ setStatus(busyMsg);
+ try {
+ startOpProgressWatch(); // 생성 후 전체 배치 재추출 — 진행도 퍼센트 표시
+ const res = await fetch(url, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(body),
+ });
+ const data = await res.json();
+ if (!res.ok || !data.ok) {
+ throw new Error(data.error || (data.stderr || "").trim().split("\n").pop() || res.status);
+ }
+ setStatus(doneMsg, "ok");
+ setTimeout(() => window.location.reload(), 800);
+ } catch (e) {
+ stopOpProgressWatch();
+ setStatus(failPrefix + e.message, "err");
+ goBtn.textContent = goLabel;
+ for (const b of all) b.disabled = false;
+ }
+}
diff --git a/sprite_gen/serve/curator/src/i18n.js b/sprite_gen/serve/curator/src/i18n.js
new file mode 100644
index 0000000..1a37092
--- /dev/null
+++ b/sprite_gen/serve/curator/src/i18n.js
@@ -0,0 +1,376 @@
+// SPDX-License-Identifier: Apache-2.0
+// curator/i18n.js — 문자열 사전(en/ko) + 언어 상태 + 정적 라벨 적용
+// 로드 순서 SSoT = index.html (classic script 전역 어휘 공유; 빌드 스텝 없음)
+
+const STR = {
+ en: {
+ title: "curation", compose: "Download atlas", export: "Download PNGs", exportGif: "Download GIFs",
+ groundGrid: "Ground grid", langOther: "한국어",
+ unfakeApply: "Pixel unfake (all)", baseNote: "identity reference — not baked",
+ unfakeState: "Pixel unfake",
+ tUnfakeState: "toggle pixel-unfake for THIS row only — what it displays and what compose bakes",
+ pxGrid: "Pixel grid", pxGridAll: "Pixel grid (all)",
+ tGridState: "grid overlay for THIS row — output pixel raster on the pixel-unfake view; on the original view the FINAL correspondence grid (green): one cell = one result pixel (display only)",
+ refsLabel: "generated from", ref_anchor: "direction anchor", ref_basis: "basis row", ref_guide: "layout guide", tPxGrid: "toggle the pixel-grid overlay for ALL rows at once (display only; each row has its own checkbox)",
+ tUnfakeApply: "toggle pixel-unfake for ALL rows at once (each row has its own checkbox)",
+ frames: "frames", loop: "loop", nonLoop: "non-loop", preview: "Preview",
+ excluded: "✗ exclude", selected: "✓ selected", extractFail: "⚠ extraction incomplete",
+ editing: "editing…", saved: "saved", saveFail: "save failed: ",
+ saveLostBanner: "EDITS ARE NOT SAVING — the server may have restarted. Reload this page (your unsaved edits will be lost, but new edits will save again).",
+ rowGif: "GIF", tRowGif: "download this row's current composed sequence as a GIF (4x nearest upscale for crisp viewing — pixel data unchanged)",
+ tRowDl: "download this row's current composed sequence — GIF (server bake, 4x) / WebM (alpha) / MP4 (white background)",
+ rowDlDone: (s, f) => `${s}.${f} downloaded`,
+ tHandTool: "hand — drag to pan the view. Hold Space anywhere for a temporary hand (release to return)",
+ rowReroll: "Reroll", tRowReroll: "reroll this row once more and APPEND it as candidates (rerollN take) — the current frames are kept; the new roll's frames arrive labeled next to them. Click opens the model popover (same idiom as Tween); Generate runs a full-batch re-extract, then the view reloads.",
+ rerollBusy: (s) => `${s}: rerolling… (generation + full re-extract, a few minutes)`,
+ rerollDone: (s) => `${s}: reroll appended to candidates — reloading`,
+ rerollFail: "reroll failed: ",
+ tRenameHint: "double-click the badge to name this instance",
+ renamePrompt: "Instance name (empty to clear):",
+ cmpOpen: "Compare", tCmpOpen: "compare the direction idle anchors on one canvas — side-by-side / overlay, shared ground line, click to add draggable guides",
+ tCmpPlay: "play/stop every sprite (own sequence, fps and breathing layer included)", atlasBake: "bake now", tAtlasBake: "re-bake the atlas from the CURRENT curated state (sequence, transforms, pixel edits, breathing) and refresh this section — no download",
+ atlasBaking: "baking…", atlasBaked: "atlas re-baked from the current curated state",
+ atlasStale: "edits not baked yet", atlasBakeFail: "bake failed: ",
+ tCmpGif: "download the compare canvas as a looping GIF (current layout + playback, deterministic virtual-time sampling)",
+ cmpGifDone: "compare GIF downloaded", cmpGifFail: "compare export failed: ",
+ cmpDl: "Save", tCmpDl: "download the compare canvas as an animation — pick GIF / WebM (alpha) / MP4 (white background) from the popover (current layout + playback, deterministic virtual-time sampling)",
+ cmpDlAlpha: "transparent", cmpDlWhite: "white bg", cmpDlDone: (f) => `compare ${f} downloaded`,
+ cmpMarks: "landmarks", tCmpMarks: "auto-detect body landmarks (head top, chin, cape start, belt, hem, feet) from palette signals of the first visible sprite and add them as horizontal guides",
+ cmpMarksDone: (n) => `${n} landmark guides added`, cmpMarksNone: "no sprite to detect landmarks from",
+ cmpGuidesHide: "hide guides", cmpGuidesShow: "show guides", cmpGuidesClear: "clear guides",
+ tCmpGuidesToggle: "hide/show all guide lines (they are kept, just hidden)",
+ tCmpGuidesClear: "delete ALL guide lines (undo with Cmd/Ctrl+Z)",
+ cmpTitle: "Compare", cmpH: "horizontal", cmpV: "vertical", cmpOverlay: "overlay",
+ cmpHint: "left list toggles sprites · drag a sprite to move it freely · empty click = horizontal guide, Shift+click = vertical · click a guide to focus, drag to move, Delete to remove · wheel = zoom · Cmd/Ctrl+Z undo · alignment buttons reset positions",
+ cmpNone: "no extracted idle anchors to compare",
+ seqCount: (play, src) => `${play} play · ${src} art`,
+ tRelink: "independent duplicate (own edits) — click to RELINK to the source frame: its own edits are DISCARDED and it follows the source again",
+ relinked: (s) => `relinked to ${s} — follows the source edits again`,
+ tUnlink: "linked duplicate — edits sync with the source frame. Click to UNLINK into an independent frame (copies the current edits; further edits are separate)",
+ unlinked: (s) => `unlinked from ${s} — now an independent frame`,
+ tFpsStepper: "whole-row playback speed (state fps, saved to sprite-request) — per-frame hold time is expressed by duplicating frames (atlas cells are shared, so clones cost nothing)",
+ fpsSet: (s, f) => `${s}: ${f}fps`, fpsFail: "fps change failed: ",
+ rowBreathe: "Breathe", tRowBreathe: "breathing is a POST-PROCESS LAYER, orthogonal to frame selection — a blink frame breathes too. Check: turn it on (instant, saved to the sidecar; compose/GIF bake it deterministically). Uncheck: turn it off. Click the label to drag the rigid boundary and tune depth / breaths over the LIVE playing sequence.",
+ tRowBreatheEdit: "open the breathing editor — adjustments apply instantly over the playing sequence; Esc restores the previous setting",
+ breatheAmp: "v depth", breatheAmpX: "h depth", breatheAmpXFollow: "h depth = v",
+ breatheCountLabel: "breaths/loop", breatheFitted: (n) => n === 0 ? "→ no room to breathe" : `→ ${n} applied`,
+ breatheAuto: "auto", tBreatheAuto: "drop the manual boundary and use the detected one (neck bottleneck, or below the face when the face sits on the body)",
+ tBreatheFitted: (len) => `the loop is ${len} frames — add frames to the sequence for a smoother breath`, tBreatheCount: "breath count per loop (1-8) — phases are continuous, so the requested count applies exactly",
+
+ breatheHint: "drag the rigid boundary — everything above it stays bit-identical, the body below squashes and stretches, and the head follows a beat later. Applies instantly; Cmd/Ctrl+Z steps back/forward, Esc restores.",
+ breatheRecalc: "recalculating\u2026",
+ breatheAxisHint: "drag the body axis — the vertical centre column that never moves while breathing. Torso width lines mirror around it.",
+ breatheTorsoHint: "drag the torso half-width — outside these lines counts as appendage (arms/wings): pushed sideways, never stretched. Drag inward to protect more.",
+ breatheFail: "breathe failed: ",
+ breatheResample: (rows) =>
+ `heads-up: ${rows} has a rotate/scale transform. the bake resamples BICUBIC, this canvas `
+ + `NEAREST — the exported file will differ from the GIF by a few edge pixels.`,
+ opProgress: (p, pct) => `re-deriving ${p.done}/${p.total} (${pct}%) — ${p.label} · ${p.phase}`,
+ healTitle: "Updating frames for the new engine",
+ healNote: "Sorry for the wait~ this only happens once per engine update. We'll open right up when it's done!",
+ healWaiting: "getting ready~",
+ breatheStrip: (n, actual) => `final bake: ${n}-frame loop (unchanged) · ${actual} breath(s)`,
+ breatheStripOff: (n) => `final bake: ${n}-frame loop · breathing off`,
+ breatheOn: (s) => `${s}: breathing layer on`,
+ breatheOff: (s) => `${s}: breathing layer off`,
+ rowTween: "Tween", tRowTween: "AI in-between: generate a mid frame between two frames of this row (codex/grok image gen on the server machine's CLI auth) — recorded as a take, then the FULL batch re-extracts. Click cards to pick the pair.",
+ tweenFrom: "from", tweenTo: "to", tweenT: "t", genGo: "Generate",
+ tweenBusy: "interpolating + re-extracting the full batch… (1-2 min)",
+ tweenDone: (s) => `${s}: in-between added — reloading`,
+ tweenFail: "interpolation failed: ",
+ treeAtlas: "final atlas", atlasDoc: "manifest.json (runtime doc)",
+ atlasPending: "not composed yet — created when you download the atlas",
+ atlasStamp: (d) => `computed ${d}`, tTreeAtlas: "scroll to the final atlas section",
+ rcTitle: "colourways", treeRecolor: "variants/", treeRecolorNote: "baked colourways",
+ tTreeRecolor: "scroll to the colourway section",
+ rcBase: "base (no swap)", rcPick: "adopt", rcPicked: "✓ adopted", rcMissing: "sheet missing",
+ rcMeta: (n, match, tol) => `${n} variants · ${match}${match === "tolerance" ? ` ±${tol}` : ""} match · variants/`,
+ rcVariantNote: (sub, pass) => `${sub} px swapped · ${pass} px passed through`,
+ rcUnusedSources: (list) => `map sources that matched nothing: ${list.join(", ")}`,
+ rcPickUnknown: (name) => `adopted colourway "${name}" is not in the current bake — re-bake it or adopt another (the pick is kept, not cleared)`,
+ rcPickSaved: (name) => `adopted colourway: ${name}`, rcPickCleared: "colourway pick cleared",
+ tRcSection: "colour variants baked by `sprite-gen recolor` into <run-dir>/variants — the sheets are what the runtime loads, so what you compare here is what ships",
+ tRcThumb: "hover to swap the big view to this sheet in place (a one-pixel colour difference only shows when the images swap at the same spot) — click to keep it there",
+ tRcPick: "record this colourway as the adopted one in curation.json (click again to clear) — the sheets on disk are untouched",
+ rowGifDone: (s) => `${s}.gif downloaded`,
+ baking: "computing…", composeDone: "atlas downloaded", composeFail: "download failed: ",
+ exporting: "computing…", exportFail: "download failed: ",
+ ready: "ready", loaded: "loaded existing curation", runLoadFail: "failed to load run:",
+ tRotate: "rotate", tShear: "shear — horizontal = shx, vertical = shy", tReset: "reset transform", tFlipX: "flip horizontally — a tool action, not a toggle: each press flips. With a marquee selection it flips ONLY that region's pixels (Cmd/Ctrl+Z undoes per press); without one, the whole frame",
+ tReorder: "grab the title to drag — reorder, or move between sequence ⇄ pool. use 넣기/빼기 to toggle without dragging",
+ tPlay: "play", tPause: "pause", tPrev: "step back", tNext: "step forward", tSpeed: "playback speed",
+ zoneSeq: "Running sequence", zonePool: "Candidate pool — drag a cut up to add it", addToSeq: "add", removeFromSeq: "remove",
+ tSelAdd: "add to the running sequence (move up)", tSelRemove: "remove to the candidate pool (move down)",
+ tTitleCopy: "full name — select to copy (drag the title to reorder)",
+ cellPx: "cell", tContentPx: "actual sprite pixels (transparent padding excluded)",
+ tZoomOpen: "inspect large (double-click the image works too)",
+ tZoomStage: "wheel/pinch = view zoom · Space/middle-drag = pan · drag = move sprite · corner resize control = sprite scale",
+ tViewZoomIn: "view zoom in (magnifier — screen scale only, the sprite itself is untouched)",
+ tViewZoomOut: "view zoom out",
+ tViewZoomFit: "fit the view to the window and re-center",
+ zoomClose: "✕", tZoomPrev: "previous frame", tZoomNext: "next frame",
+ dirAnchorBadge: "direction anchor",
+ tDirAnchorBadge: "canonical facing anchor for this direction — generated from the base; every other row of this direction derives identity from it",
+ anchorFrameBadge: "ANCHOR",
+ anchorFrameStaleBadge: "ANCHOR?",
+ tAnchorFrameStale: "this pin can no longer be proven to point at the frame you approved (its row was regenerated, or it carries no generation stamp). Generation fails loud until you re-pin — click the pin button on the frame you want",
+ tRepinAnchorFrame: "re-pin THIS frame as the direction anchor (clears the stale pin and stamps it for the current generation)",
+ tAnchorFrameBadge: "this exact frame — as curated (pixel edits, transforms) — is the identity attached when generating the other rows of this direction. It follows the sequence head, so reordering or deleting frames can move it; pin it to lock it",
+ tAnchorFramePinned: "pinned as this direction's anchor — it stays this frame even if you reorder or delete other frames",
+ tSetAnchorFrame: "pin this frame as the direction anchor: the other rows of this direction are generated from THIS curated frame, and it stops following the sequence head",
+ tUnsetAnchorFrame: "unpin the anchor frame (back to the anchor row's first sequence frame)",
+ anchorPinned: (d, label) => `direction ${d} anchor = ${label}`,
+ anchorUnpinned: (d, label) => `direction ${d} anchor back to the default (${label})`,
+ anchorError: (d, msg) => `direction ${d} anchor unresolved: ${msg}`,
+ dirGroupLabel: (d) => `direction · ${d}`,
+ dirMirrorLabel: (d, src) => `direction · ${d} — runtime mirror of ${src} (not generated)`,
+ treeTitle: "generation structure",
+ treePipeline: "pipeline",
+ treeFiles: "files",
+ treeBaseNote: "base — first identity truth",
+ treeIdleRow: "idle row",
+ treeAnchorNote: "anchor · single frame-0 crop",
+ treeMirror: (d, src) => `${d} — runtime mirror of ${src} (not generated)`,
+ treePending: "not generated yet",
+ treeRawNote: "raw · awaiting extract",
+ missingPending: "not generated",
+ archiveChip: (n) => `archive ${n}`,
+ tArchiveChip: "click to open — drop a card here to archive it",
+ tArchiveBtn: "archive (remove even from the candidate pool)",
+ tScaleScrub: "sprite scale — click arrows to step, drag the resize icon left/right (view zoom is the magnifier widget)",
+ penTool: "pen", eraserTool: "eraser", pickTool: "eyedropper", undoEdit: "undo", redoEdit: "redo", clearEdits: "clear edits",
+ selectTool: "select", tSelectTool: "marquee: drag to select an area (dashed box) - drag inside to MOVE it, Alt+drag to DUPLICATE, Esc to deselect",
+ transformTool: "transform", lassoTool: "lasso",
+ tLassoTool: "lasso: drag a freehand loop to select a non-rectangular area, then it hands off to the transform tool. Esc to deselect",
+ lassoSelected: (n) => `lasso: ${n} px selected - drag to move, Shift+drag to rotate, Alt+drag to skew`,
+ tTransformTool: "transform (default): drag to move - Shift+drag to ROTATE, Alt+drag to SKEW. With a marquee selection it transforms ONLY that area (baked to pixels); with no selection it transforms the whole cell",
+ regionTransformed: "region transformed (baked to pixel edits - undo with Cmd/Ctrl+Z)",
+ tUndoKeys: "undo (Cmd/Ctrl+Z)", tRedoKeys: "redo (Cmd/Ctrl+Shift+Z)",
+ baseEditBtn: "edit", tBaseEdit: "pixel-edit the base image itself — saves into base-source (original backed up once as .orig); affects FUTURE generation, not already-extracted frames",
+ baseEditSave: "save to base", baseEditFail: "base save failed: ",
+ baseUnsaved: "editing base — press 'save to base' to bake into the file",
+ baseEditSaved: (n) => `base updated (${n}px) — affects future generation`,
+ tPick: "eyedropper — click a pixel to sample its color, then it switches to the pen so you can paint that exact color",
+ archiveHint: "drag a card out to restore it into the sequence or pool",
+ archModalTitle: (st, n) => `archive · ${st} (${n})`,
+ restoreToSeq: "to sequence", restoreToPool: "to pool",
+ missingRawWait: "generated · awaiting extract",
+ treeRawFolder: "generated strip originals",
+ treeFramesFolder: "extracted frames",
+ treeAnchorsFolder: "direction anchors — single-frame crops",
+ treeAtlasNote: "final atlas",
+ treeFrameCount: (n) => `${n} frames`,
+ treeAnchorOrigin: (d) => `idle row · ${d} anchor source`,
+ reloadBanner: "run updated — click to reload the view",
+ tDupBtn: "duplicate this frame — a new card with its own transform (bakes the same source image)",
+ cloneBadge: (name) => `${name} copy`,
+ tCloneBadge: "duplicated instance — reads the source frame's image; its transform/pixel edits are its own. The archive button removes the copy entirely.",
+ curationDropped: (states) =>
+ `frames were regenerated — previous curation for ${states.join(", ")} no longer applies and was reset. ` +
+ `curation.json on disk is untouched; the next save preserves it as curation.stale-<hash>.json.`,
+ tTreeNode: "click to scroll to this row",
+ hints: ["drag card header = reorder / move row", "drag pool→sequence to add", "hover a frame -> bottom-right magnifier = scale", "top handle = rotate", "click card = sequence ⇄ pool", "saved automatically"],
+ exportDone: () => "PNGs downloaded",
+ exportGifDone: () => "GIFs downloaded",
+ },
+ ko: {
+ title: "큐레이션", compose: "아틀라스 다운로드", export: "PNG 다운로드", exportGif: "GIF 다운로드",
+ groundGrid: "바닥 그리드", langOther: "EN",
+ unfakeApply: "픽셀 언페이크 전체", baseNote: "원본 베이스 (아이덴티티 참조 — 굽기와 무관)",
+ unfakeState: "픽셀 언페이크",
+ tUnfakeState: "이 줄만 픽셀 언페이크 켜기/끄기 — 표시와 굽기가 같이 바뀐다",
+ pxGrid: "픽셀 격자", pxGridAll: "픽셀 격자 전체",
+ tGridState: "이 줄 격자 오버레이 — 픽셀 언페이크 뷰에선 출력 픽셀 눈금, 원본 뷰에선 최종 대응 격자(초록, 칸 하나 = 결과 픽셀 하나) (표시 전용)",
+ refsLabel: "생성 재료", ref_anchor: "방향 앵커", ref_basis: "basis row", ref_guide: "레이아웃 가이드", tPxGrid: "모든 줄의 격자 오버레이를 한번에 켜기/끄기 (표시 전용; 줄별 체크박스는 각 줄에)",
+ tUnfakeApply: "모든 줄의 픽셀 언페이크를 한번에 켜기/끄기 (줄별 체크박스는 각 줄에)",
+ frames: "프레임", loop: "루프", nonLoop: "비루프", preview: "프리뷰",
+ excluded: "✗ 제외", selected: "✓ 선택됨", extractFail: "⚠ 추출 미완료",
+ editing: "편집 중…", saved: "저장됨", saveFail: "저장 실패: ",
+ saveLostBanner: "편집이 저장되지 않고 있습니다 — 서버가 재기동됐을 수 있어요. 이 페이지를 새로고침하세요 (미저장 편집은 유실되지만, 이후 편집은 다시 저장됩니다).",
+ rowGif: "GIF", tRowGif: "이 줄의 현재 합성 시퀀스를 GIF 로 다운로드 — 선명하게 보이도록 4배 니어리스트로 굽는다 (픽셀 데이터는 그대로)",
+ tRowDl: "이 줄의 현재 합성 시퀀스 다운로드 — GIF(서버 굽기, 4배) / WebM(투명) / MP4(흰 배경)",
+ rowDlDone: (s, f) => `${s}.${f} 다운로드 완료`,
+ tHandTool: "손 — 드래그로 화면 이동. Space 를 누르고 있는 동안은 어디서든 임시 손 (떼면 원래 툴로)",
+ rowReroll: "리롤", tRowReroll: "이 줄을 한 번 더 생성해서 **후보군에 병기** (rerollN 테이크) — 기존 프레임은 그대로, 새 롤 프레임이 라벨 달고 옆에 온다. 클릭 = 모델 팝오버(보간과 같은 관용구), 생성 = 전체 배치 재추출 후 뷰 새로고침.",
+ rerollBusy: (s) => `${s}: 리롤 생성 중… (생성 + 전체 재추출, 수 분)`,
+ rerollDone: (s) => `${s}: 리롤 후보 추가 완료 — 새로고침`,
+ rerollFail: "리롤 실패: ",
+ tRenameHint: "배지를 더블클릭하면 이름을 붙일 수 있어요",
+ renamePrompt: "인스턴스 이름 (비우면 제거):",
+ cmpOpen: "비교", tCmpOpen: "방향 앵커(idle)들을 한 캔버스에서 비교 — 나란히/겹침, 공유 바닥선, 클릭으로 드래그 가이드 추가",
+ tCmpPlay: "모든 스프라이트 재생/정지 (각자 시퀀스·fps·호흡 레이어 포함)", atlasBake: "지금 상태로 굽기", tAtlasBake: "현재 큐레이션 상태(시퀀스·변형·픽셀편집·호흡) 그대로 아틀라스를 다시 구워 이 섹션을 갱신합니다 — 다운로드 없음",
+ atlasBaking: "굽는 중…", atlasBaked: "현재 큐레이션 상태로 아틀라스를 다시 구웠습니다",
+ atlasStale: "편집 반영 안 됨", atlasBakeFail: "굽기 실패: ",
+ tCmpGif: "비교 캔버스를 루프 GIF 로 다운로드 (현재 배치+재생 그대로, 가상 시간 결정론 샘플)",
+ cmpGifDone: "비교 GIF 다운로드 완료", cmpGifFail: "비교 내보내기 실패: ",
+ cmpDl: "저장", tCmpDl: "비교 캔버스를 애니메이션으로 다운로드 — 팝오버에서 GIF / WebM(투명) / MP4(흰 배경) 선택 (현재 배치+재생 그대로, 가상 시간 결정론 샘플)",
+ cmpDlAlpha: "투명", cmpDlWhite: "흰 배경", cmpDlDone: (f) => `비교 ${f} 다운로드 완료`,
+ cmpMarks: "기준선", tCmpMarks: "첫 번째 켜진 스프라이트의 팔레트 신호로 신체 기준선(정수리·턱선·망토 시작·벨트·치맛단·발끝)을 자동 감지해 가로 가이드로 추가",
+ cmpMarksDone: (n) => `기준선 가이드 ${n}개 추가`, cmpMarksNone: "기준선을 감지할 스프라이트가 없습니다",
+ cmpGuidesHide: "선 감추기", cmpGuidesShow: "선 보이기", cmpGuidesClear: "선 전부 지우기",
+ tCmpGuidesToggle: "가이드선 전체 보이기/감추기 (지워지지 않고 잠깐 숨김)",
+ tCmpGuidesClear: "가이드선 전부 삭제 (Cmd/Ctrl+Z 로 되돌리기 가능)",
+ cmpTitle: "비교", cmpH: "수평", cmpV: "수직", cmpOverlay: "겹침",
+ cmpHint: "좌측 목록으로 스프라이트 켜고 끄기 · 스프라이트는 잡고 드래그 · 빈 곳 클릭 = 가로선, Shift+클릭 = 세로선 · 선 클릭 = 포커스, 드래그 = 이동, Delete = 삭제 · 휠 = 배율 · Cmd/Ctrl+Z 되돌리기 · 정렬 버튼 = 배치 리셋",
+ cmpNone: "비교할 추출된 idle 앵커가 없습니다",
+ seqCount: (play, src) => `재생 ${play}컷 · 원본 ${src}장`,
+ tRelink: "독립 복제 (자기 편집 보유) — 클릭하면 원본과 다시 링크합니다: 이 복제의 자체 편집은 버려지고 원본을 따라갑니다",
+ relinked: (s) => `${s} 와 재링크 — 다시 원본 편집을 따라갑니다`,
+ tUnlink: "링크된 복제 — 편집이 원본과 동기화됩니다. 클릭하면 링크를 끊고 독립 프레임이 됩니다 (현재 편집을 복사, 이후 편집은 각자)",
+ unlinked: (s) => `${s} 와 링크 해제 — 독립 프레임이 됐습니다`,
+ tFpsStepper: "줄 전체 재생 속도 (state fps — sprite-request 에 저장). 특정 프레임을 길게 보여주려면 프레임 복제를 쓰세요 (복제는 아틀라스 셀 공유 = 부하 0)",
+ fpsSet: (s, f) => `${s}: ${f}fps`, fpsFail: "fps 변경 실패: ",
+ rowBreathe: "호흡", tRowBreathe: "호흡은 프레임 선택과 직교하는 후처리 레이어입니다 — 깜빡임 프레임도 그대로 숨쉽니다. 체크: 켜기 (즉시, 사이드카 저장 — 아틀라스/GIF 굽기에 결정론 반영), 해제: 끄기. 라벨 클릭: 실제 재생 위에서 강체 경계·진폭·호흡 횟수 조정.",
+ tRowBreatheEdit: "호흡 편집기 열기 — 조정은 재생 중인 시퀀스에 즉시 반영됩니다. Esc = 이전 설정 복원",
+ breatheAmp: "세로 진폭", breatheAmpX: "가로 진폭", breatheAmpXFollow: "가로 진폭 =세로",
+ breatheCountLabel: "호흡/루프", breatheFitted: (n) => n === 0 ? "→ 숨쉴 자리 없음" : `→ 적용 ${n}회`,
+ breatheAuto: "자동", tBreatheAuto: "수동 경계를 버리고 검출값을 쓴다 (목 병목, 얼굴이 몸통에 있으면 얼굴 아래)",
+ tBreatheFitted: (len) => `루프가 ${len}프레임 — 더 부드럽게 하려면 시퀀스에 프레임을 늘리세요`, tBreatheCount: "루프당 호흡 횟수 (1~8) — 위상이 연속값이라 요청한 횟수가 그대로 적용됩니다",
+
+ breatheHint: "강체 경계를 드래그 — 이 위는 도트 단위로 그대로 남고, 아래 몸통이 눌렸다 펴지며 머리가 반 박자 늦게 따라옵니다. 즉시 반영, Cmd/Ctrl+Z 이전/다음, Esc 복원.",
+ breatheRecalc: "재계산 중\u2026",
+ breatheAxisHint: "몸통 축을 드래그 — 숨쉴 때 절대 움직이지 않는 세로 중심 열입니다. 몸통 폭 선이 이 축을 기준으로 대칭 이동합니다.",
+ breatheTorsoHint: "몸통 반폭을 드래그 — 이 선 바깥은 부속(팔·날개)으로 취급되어 늘어나지 않고 밀리기만 합니다. 안쪽으로 끌수록 보호가 넓어집니다.",
+ breatheFail: "호흡 실패: ",
+ breatheResample: (rows) =>
+ `참고: ${rows} 에 회전/확대 변형이 걸려 있다. 굽기는 BICUBIC, 이 캔버스는 NEAREST 로 `
+ + `리샘플하므로 내보낸 파일이 GIF 와 가장자리 몇 px 다르다.`,
+ opProgress: (p, pct) => `재추출 ${p.done}/${p.total} (${pct}%) — ${p.label} · ${p.phase === "components" ? "컴포넌트" : "픽셀 언페이크"}`,
+ healTitle: "엔진 갱신 반영 중 — 프레임 재계산",
+ healNote: "죄송해요~ 조금만 기다려 주세요! 엔진 갱신 반영은 이번 한 번이면 돼요. 끝나면 바로 열어 드릴게요!",
+ healWaiting: "준비하고 있어요~",
+ breatheStrip: (n, actual) => `최종 굽기: 루프 ${n}프레임 그대로 · 호흡 ${actual}회`,
+ breatheStripOff: (n) => `최종 굽기: 루프 ${n}프레임 · 호흡 꺼짐`,
+ breatheOn: (s) => `${s}: 호흡 레이어 켜짐`,
+ breatheOff: (s) => `${s}: 호흡 레이어 꺼짐`,
+ rowTween: "보간", tRowTween: "AI 중간 프레임: 이 줄의 두 프레임 사이를 생성형(codex/grok — 서버 머신의 CLI 인증 사용)으로 그려 테이크로 기록 — 이후 전체 배치 재추출. 카드를 클릭해 쌍을 고르세요.",
+ tweenFrom: "시작", tweenTo: "끝", tweenT: "t", genGo: "생성",
+ tweenBusy: "보간 + 전체 배치 재추출 중… (1~2분)",
+ tweenDone: (s) => `${s}: 중간 프레임 추가됨 — 새로고침합니다`,
+ tweenFail: "보간 실패: ",
+ treeAtlas: "최종 아틀라스", atlasDoc: "manifest.json (런타임 문서)",
+ atlasPending: "아직 합성 전 — 아틀라스 다운로드를 누르면 계산돼 생성됩니다",
+ atlasStamp: (d) => `${d} 계산본`, tTreeAtlas: "최종 아틀라스 섹션으로 스크롤",
+ rcTitle: "컬러웨이", treeRecolor: "variants/", treeRecolorNote: "구운 컬러웨이",
+ tTreeRecolor: "컬러웨이 섹션으로 스크롤",
+ rcBase: "베이스 (치환 없음)", rcPick: "채택", rcPicked: "✓ 채택됨", rcMissing: "시트 없음",
+ rcMeta: (n, match, tol) => `variant ${n}개 · ${match}${match === "tolerance" ? ` ±${tol}` : ""} 매칭 · variants/`,
+ rcVariantNote: (sub, pass) => `치환 ${sub}px · 통과 ${pass}px`,
+ rcUnusedSources: (list) => `아무것도 못 맞춘 소스 색: ${list.join(", ")}`,
+ rcPickUnknown: (name) => `채택된 컬러웨이 "${name}" 가 지금 베이크에 없습니다 — 다시 굽거나 다른 것을 채택하세요 (채택 기록은 지우지 않고 그대로 둡니다)`,
+ rcPickSaved: (name) => `컬러웨이 채택: ${name}`, rcPickCleared: "컬러웨이 채택 해제",
+ tRcSection: "`sprite-gen recolor` 가 <run-dir>/variants 에 구운 색 변형 시트 — 런타임이 읽는 파일 그 자체라, 여기서 비교하는 것이 곧 출시본입니다",
+ tRcThumb: "올려놓기만 하면 큰 화면이 같은 자리에서 이 시트로 갈아끼워집니다 (한 칸짜리 색차는 같은 자리 교체로만 보입니다) — 클릭하면 고정",
+ tRcPick: "이 컬러웨이를 채택으로 curation.json 에 기록합니다 (다시 누르면 해제). 디스크의 시트는 건드리지 않습니다",
+ rowGifDone: (s) => `${s}.gif 다운로드 완료`,
+ baking: "계산 중…", composeDone: "아틀라스 다운로드 완료", composeFail: "다운로드 실패: ",
+ exporting: "계산 중…", exportFail: "다운로드 실패: ",
+ ready: "준비됨", loaded: "기존 큐레이션 로드됨", runLoadFail: "run 로드 실패:",
+ tRotate: "회전", tShear: "기울이기 — 가로=shx, 세로=shy", tReset: "보정 초기화", tFlipX: "좌우 반전 — 토글이 아니라 도구: 누를 때마다 반전. 마키 선택이 있으면 그 영역 픽셀만(누를 때마다 Cmd/Ctrl+Z 되돌림 가능), 없으면 프레임 전체",
+ tReorder: "타이틀을 잡고 드래그 = 순서변경 / 시퀀스↔풀 이동. 드래그 없이 넣고 뺄 땐 넣기·빼기 버튼",
+ tPlay: "재생", tPause: "일시정지", tPrev: "이전 프레임", tNext: "다음 프레임", tSpeed: "재생 속도",
+ zoneSeq: "달리기 시퀀스", zonePool: "후보 풀 — 마음에 드는 컷을 위로 끌어 추가", addToSeq: "넣기", removeFromSeq: "빼기",
+ tSelAdd: "시퀀스에 넣기 (위로 이동)", tSelRemove: "후보 풀로 빼기 (아래로 이동)",
+ tTitleCopy: "풀네임 — 드래그해서 복사 (제목 자체를 잡으면 순서변경)",
+ cellPx: "셀", tContentPx: "실제 스프라이트 픽셀 (투명 여백 제외)",
+ tZoomOpen: "크게 보기 (이미지 더블클릭도 됨)",
+ tZoomStage: "휠/핀치 = 화면 확대 · Space/휠버튼 드래그 = 화면 이동 · 드래그 = 스프라이트 이동 · 모서리 크기 조절 = 스프라이트 크기",
+ tViewZoomIn: "화면 확대 (돋보기 — 보기 배율만 커지고 스프라이트 자체는 그대로)",
+ tViewZoomOut: "화면 축소",
+ tViewZoomFit: "화면에 맞춤 + 중앙 정렬",
+ zoomClose: "✕", tZoomPrev: "이전 프레임", tZoomNext: "다음 프레임",
+ dirAnchorBadge: "방향 앵커",
+ tDirAnchorBadge: "이 방향의 canonical 앵커 — base 에서 생성되고, 이 방향의 다른 모든 행이 여기서 identity 를 가져온다",
+ anchorFrameBadge: "앵커",
+ anchorFrameStaleBadge: "앵커?",
+ tAnchorFrameStale: "이 핀이 네가 승인한 그 프레임을 가리킨다고 더 이상 증명되지 않는다 (그 행이 재생성됐거나 세대 스탬프가 없다). 재지정할 때까지 생성은 fail-loud 다 — 원하는 프레임의 핀 버튼을 눌러라",
+ tRepinAnchorFrame: "이 프레임으로 앵커 재지정 (낡은 핀을 풀고 현재 세대로 도장한다)",
+ tAnchorFrameBadge: "이 프레임이 — 큐레이션(픽셀 편집·변형) 그대로 — 이 방향의 다른 행을 생성할 때 붙는 identity 다. 시퀀스 첫 프레임을 따라가므로 재정렬·삭제하면 옮겨간다 — 고정하려면 핀을 눌러라",
+ tAnchorFramePinned: "이 방향의 앵커로 고정됨 — 다른 프레임을 재정렬·삭제해도 이 프레임이 앵커로 남는다",
+ tSetAnchorFrame: "이 프레임을 방향 앵커로 고정 — 이 방향의 다른 자세들을 바로 이 후처리된 프레임에서 생성하고, 시퀀스 첫 프레임을 따라가지 않는다",
+ tUnsetAnchorFrame: "앵커 지정 해제 (앵커 행의 시퀀스 첫 프레임으로 되돌림)",
+ anchorPinned: (d, label) => `${d} 방향 앵커 = ${label}`,
+ anchorUnpinned: (d, label) => `${d} 방향 앵커를 기본값으로 (${label})`,
+ anchorError: (d, msg) => `${d} 방향 앵커 해석 실패: ${msg}`,
+ dirGroupLabel: (d) => `방향 · ${d}`,
+ dirMirrorLabel: (d, src) => `방향 · ${d} — ${src} 런타임 미러 (생성 없음)`,
+ treeTitle: "생성 구조",
+ treePipeline: "파이프라인",
+ treeFiles: "파일",
+ treeBaseNote: "base — 최초 identity",
+ treeIdleRow: "idle 행",
+ treeAnchorNote: "앵커 · frame-0 크롭 1장",
+ treeMirror: (d, src) => `${d} — ${src} 런타임 미러 (생성 없음)`,
+ treePending: "미생성",
+ treeRawNote: "raw 생성됨 · 추출 전",
+ missingPending: "미생성",
+ archiveChip: (n) => `보관함 ${n}`,
+ tArchiveChip: "클릭 = 열기 · 카드를 여기로 끌어오면 보관",
+ tArchiveBtn: "보관함으로 (후보 풀에서도 제외)",
+ tScaleScrub: "스프라이트 크기 — 화살표 클릭 = 단계 조절, 크기 아이콘 좌우 드래그 = 연속 조절 (화면 배율은 돋보기 위젯)",
+ penTool: "연필", eraserTool: "지우개", pickTool: "스포이드", undoEdit: "되돌리기", redoEdit: "재실행", clearEdits: "편집 비우기",
+ selectTool: "선택", tSelectTool: "영역 선택: 드래그로 점선 박스를 만들고 — 안쪽을 드래그하면 이동, Alt+드래그는 복제, Esc 는 선택 해제",
+ transformTool: "변형", lassoTool: "올가미",
+ tLassoTool: "올가미: 자유곡선으로 감싸 네모가 아닌 영역을 잡는다. 놓으면 변형 툴로 넘어간다. Esc 는 선택 해제",
+ lassoSelected: (n) => `올가미: ${n}px 선택 — 드래그 이동, Shift 회전, Alt 비틀기`,
+ tTransformTool: "변형 (기본): 드래그 = 이동, Shift+드래그 = 회전, Alt+드래그 = 비틀기. 마퀴 선택이 있으면 **그 영역만** 변형해 픽셀로 굽고, 선택이 없으면 셀 전체를 변형한다",
+ regionTransformed: "영역을 변형했다 (픽셀 편집으로 구움 — Cmd/Ctrl+Z 로 되돌리기)",
+ tUndoKeys: "되돌리기 (Cmd/Ctrl+Z)", tRedoKeys: "재실행 (Cmd/Ctrl+Shift+Z)",
+ baseEditBtn: "편집", tBaseEdit: "베이스 이미지 자체를 픽셀 편집 — base-source 파일에 저장 (원본은 .orig 로 1회 백업). 이미 뽑힌 프레임은 안 변하고 이후 생성에 반영됩니다",
+ baseEditSave: "베이스에 저장", baseEditFail: "베이스 저장 실패: ",
+ baseUnsaved: "베이스 편집 중 — '베이스에 저장' 을 눌러야 파일에 반영됩니다",
+ baseEditSaved: (n) => `베이스 갱신됨 (${n}px) — 이후 생성에 반영`,
+ tPick: "스포이드 — 픽셀을 클릭하면 그 색을 집어 연필로 전환, 똑같은 색으로 바로 찍을 수 있어",
+ archiveHint: "카드를 끌어내 시퀀스/후보로 복구",
+ archModalTitle: (st, n) => `보관함 · ${st} (${n})`,
+ restoreToSeq: "시퀀스로", restoreToPool: "후보로",
+ missingRawWait: "생성됨 · 추출 대기",
+ treeRawFolder: "생성 스트립 원본",
+ treeFramesFolder: "추출 프레임",
+ treeAnchorsFolder: "방향 앵커 — 1장 크롭",
+ treeAtlasNote: "최종 아틀라스",
+ treeFrameCount: (n) => `${n}프레임`,
+ treeAnchorOrigin: (d) => `idle 행 · ${d} 앵커 원천`,
+ reloadBanner: "런이 갱신됐어 — 클릭해서 새로고침",
+ tDupBtn: "이 프레임 복제 — 자기 변형을 따로 갖는 새 카드 (같은 원본 이미지를 굽는다)",
+ cloneBadge: (name) => `${name} 복제`,
+ tCloneBadge: "복제 인스턴스 — 원본 프레임 이미지를 읽고, 변형/픽셀편집은 이 카드 것. 보관 버튼은 복제를 완전히 제거한다.",
+ curationDropped: (states) =>
+ `프레임이 재생성돼 ${states.join(", ")} 의 이전 큐레이션이 더 이상 맞지 않아 초기화됐어. ` +
+ `디스크의 curation.json 은 그대로고, 다음 저장 때 curation.stale-<hash>.json 으로 백업돼.`,
+ tTreeNode: "클릭하면 해당 줄로 이동",
+ hints: ["타이틀 드래그 = 순서변경 / 시퀀스↔풀 이동", "넣기·빼기 버튼으로 토글 (클릭만으론 안 빠짐)", "제목 호버 = 풀네임 복사", "우하단 돋보기 = 크기 · 상단 핸들 = 회전", "복제 = 헤더 ⧉ 버튼", "자동 저장"],
+ exportDone: () => "PNG 다운로드 완료",
+ exportGifDone: () => "GIF 다운로드 완료",
+ },
+};
+
+let lang = "en";
+
+function t(key) {
+ const v = (STR[lang] && STR[lang][key]) ?? STR.en[key];
+ return v;
+}
+
+function applyStaticLang() {
+ document.getElementById("t-title").textContent = t("title");
+ document.getElementById("dl-main").textContent = `${t("cmpDl")} ▾`;
+ document.getElementById("compose").textContent = t("compose");
+ document.getElementById("export").textContent = t("export");
+ document.getElementById("export-gif").textContent = t("exportGif");
+ gridToggle.textContent = `${t("groundGrid")} ${document.body.classList.contains("show-grid") ? "▣" : "▢"}`;
+ langToggle.textContent = t("langOther");
+ const ppLabel = document.getElementById("pp-label");
+ if (ppLabel) ppLabel.textContent = t("unfakeApply");
+ const pxLabel = document.getElementById("pxgrid-label");
+ if (pxLabel) pxLabel.textContent = t("pxGridAll") + (run.pixelUnfake && run.pixelUnfake.label ? " \u00b7 " + run.pixelUnfake.label : "");
+ const pxWrap = document.getElementById("pxgrid-wrap");
+ if (pxWrap) pxWrap.title = t("tPxGrid");
+ const unfakeWrap = document.getElementById("unfake-wrap");
+ if (unfakeWrap) unfakeWrap.title = t("tUnfakeApply");
+ document.getElementById("hintbar").innerHTML = t("hints").map((h) => `<span>${h}</span>`).join("");
+}
+
+// 실시간 계약 (maintainer 확정 2026-07-14): 버튼은 '게임에 적용'이 아니다 — 지금
+// 보이는 라이브 상태(프레임 캐시 + 큐레이션)를 서버가 그 자리에서 계산해
+// 파일(zip)로 내려주는 다운로드다. 서버는 계산 전에 캐시를 자가치유한다.
diff --git a/sprite_gen/serve/curator/src/lasso-select.js b/sprite_gen/serve/curator/src/lasso-select.js
new file mode 100644
index 0000000..1b59fb2
--- /dev/null
+++ b/sprite_gen/serve/curator/src/lasso-select.js
@@ -0,0 +1,159 @@
+// SPDX-License-Identifier: Apache-2.0
+// curator/lasso-select.js — 올가미(자유곡선) 선택.
+// 로드 순서 SSoT = index.html (classic script 전역 어휘 공유; 빌드 스텝 없음)
+//
+// **왜 필요한가** (maintainer 2026-07-26 "네모로는 선택을 못한다"): 도트 스프라이트에서 옮기고
+// 싶은 부분(팔 하나, 모자, 기울이고 싶은 상반신)은 사각이 아니다. 사각으로 잡으면 이웃
+// 픽셀이 딸려온다.
+//
+// **`sel` 에 마스크를 더한다 — rect 를 없애지 않는다.** `pixelEdit.sel` 은 지금
+// `{x0,y0,x1,y1}` 이고 소비자가 여럿이다(마퀴 점선, select 툴 이동/복제, 영역 변형).
+// rect 를 마스크로 교체하면 그 소비자를 전부 고쳐야 하고, 하나라도 놓치면 조용히
+// 사각으로 되돌아간 것처럼 동작한다. 그래서 rect 는 **바운딩 박스로 유지**하고
+// `mask`(셀키 Set)를 얹는다 — 마스크를 모르는 소비자는 지금 그대로(퇴화가 아니라 기존 동작),
+// 아는 소비자만 실제 모양을 쓴다.
+
+// 진행 중인 올가미 그리기. { pts: [[x,y]…], canvas }
+let lassoDraw = null;
+
+const LASSO_ICON =
+ '<svg viewBox="0 0 16 16" width="13" height="13" aria-hidden="true">' +
+ '<path d="M8 2.2c3.1 0 5.6 1.7 5.6 3.9 0 2.1-2.5 3.8-5.6 3.8-1 0-2-.2-2.8-.5" ' +
+ 'fill="none" stroke="currentColor" stroke-width="1.2" stroke-linecap="round"/>' +
+ '<path d="M4.6 9.1C3.2 8.4 2.4 7.3 2.4 6.1c0-2.2 2.5-3.9 5.6-3.9" ' +
+ 'fill="none" stroke="currentColor" stroke-width="1.2" stroke-linecap="round" stroke-dasharray="2.2 1.6"/>' +
+ '<path d="M4.9 9.2c-.5 1.4-.3 2.7.5 4" fill="none" stroke="currentColor" ' +
+ 'stroke-width="1.2" stroke-linecap="round"/></svg>';
+
+// 다각형 내부 판정 — even-odd 광선 교차. 폐곡선으로 닫아 센다.
+function lassoContains(pts, x, y) {
+ let inside = false;
+ for (let i = 0, j = pts.length - 1; i < pts.length; j = i, i += 1) {
+ const [xi, yi] = pts[i];
+ const [xj, yj] = pts[j];
+ if ((yi > y) !== (yj > y) && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi) inside = !inside;
+ }
+ return inside;
+}
+
+// 자유곡선을 셀 마스크로 굽는다. 반환 = {x0,y0,x1,y1,mask} 또는 null(면적 0).
+function lassoRasterize(pts, cw, ch) {
+ if (pts.length < 3) return null;
+ let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;
+ for (const [px, py] of pts) {
+ if (px < x0) x0 = px;
+ if (py < y0) y0 = py;
+ if (px > x1) x1 = px;
+ if (py > y1) y1 = py;
+ }
+ x0 = Math.max(0, Math.floor(x0));
+ y0 = Math.max(0, Math.floor(y0));
+ x1 = Math.min(cw, Math.ceil(x1));
+ y1 = Math.min(ch, Math.ceil(y1));
+ const mask = new Set();
+ for (let y = y0; y < y1; y += 1) {
+ for (let x = x0; x < x1; x += 1) {
+ // 셀 중심으로 판정한다 — 모서리로 재면 경계 셀이 들쭉날쭉해진다.
+ if (lassoContains(pts, x + 0.5, y + 0.5)) mask.add(`${x},${y}`);
+ }
+ }
+ if (!mask.size) return null;
+ return { x0, y0, x1, y1, mask };
+}
+
+// 그리는 동안의 윤곽. 확정된 선택의 표시는 `lassoRenderOutline` 이 따로 맡는다.
+function lassoRenderPath(stage, stateName, pts, closed) {
+ const [cw, ch] = cellDims(stateName);
+ let cv = lassoDraw && lassoDraw.canvas;
+ if (!cv) {
+ cv = document.createElement("canvas");
+ cv.className = "lasso-path";
+ stage.appendChild(cv);
+ if (lassoDraw) lassoDraw.canvas = cv;
+ }
+ const ss = 4; // 윤곽은 셀보다 곱게 그려야 곡선이 계단으로 안 보인다
+ cv.width = cw * ss;
+ cv.height = ch * ss;
+ const ctx = cv.getContext("2d");
+ // 버퍼를 정한 자리에서 판정까지 한다 — 바깥 스윕에 맡기면 canvas 기본값을 보고 답한다
+ // (curator 픽셀 스케일링 SSoT 계약).
+ applyPixelScaling(cv);
+ ctx.clearRect(0, 0, cv.width, cv.height);
+ if (pts.length < 2) return;
+ ctx.beginPath();
+ ctx.moveTo(pts[0][0] * ss, pts[0][1] * ss);
+ for (let i = 1; i < pts.length; i += 1) ctx.lineTo(pts[i][0] * ss, pts[i][1] * ss);
+ if (closed) ctx.closePath();
+ ctx.lineWidth = 1.5;
+ ctx.setLineDash([5, 4]);
+ ctx.strokeStyle = "#000";
+ ctx.stroke();
+ ctx.setLineDash([5, 4]);
+ ctx.lineDashOffset = 5;
+ ctx.strokeStyle = "#fff";
+ ctx.stroke();
+}
+
+function lassoClearPath() {
+ if (lassoDraw && lassoDraw.canvas && lassoDraw.canvas.parentNode) {
+ lassoDraw.canvas.parentNode.removeChild(lassoDraw.canvas);
+ }
+ lassoDraw = null;
+}
+
+// 확정된 마스크의 윤곽 — 마스크 경계 셀의 바깥변만 그린다. bbox 점선으로는
+// "어디를 잡았는지" 가 안 보인다(올가미의 존재 이유가 그것이다).
+function lassoRenderMask(stage, stateName, sel) {
+ const old = stage.querySelector(".lasso-mask");
+ if (old) old.parentNode.removeChild(old);
+ if (!sel || !sel.mask) return;
+ const [cw, ch] = cellDims(stateName);
+ const cv = document.createElement("canvas");
+ cv.className = "lasso-mask";
+ cv.width = cw;
+ cv.height = ch;
+ const ctx = cv.getContext("2d");
+ ctx.fillStyle = "rgba(90,160,255,0.28)";
+ for (const key of sel.mask) {
+ const [x, y] = key.split(",").map(Number);
+ ctx.fillRect(x, y, 1, 1);
+ }
+ stage.appendChild(cv);
+ applyPixelScaling(cv);
+}
+
+// 스테이지에 올가미 제스처를 건다. 올가미 툴이 활성일 때만 먹는다.
+function wireLasso(stage, stateName, ctx) {
+ const { isLassoTool, srcXY, onSelection } = ctx;
+ stage.addEventListener("pointerdown", (ev) => {
+ if (!isLassoTool()) return;
+ if (ev.button || !ev.isPrimary) return;
+ ev.preventDefault();
+ ev.stopImmediatePropagation();
+ try { stage.setPointerCapture(ev.pointerId); } catch { /* 합성 포인터 */ }
+ lassoDraw = { pts: [srcXY(ev)], canvas: null };
+ lassoRenderPath(stage, stateName, lassoDraw.pts, false);
+
+ const onMove = (e) => {
+ if (!lassoDraw) return;
+ const p = srcXY(e);
+ const last = lassoDraw.pts[lassoDraw.pts.length - 1];
+ // 점을 너무 촘촘히 쌓지 않는다 — 판정 비용이 점 수에 선형이다.
+ if (Math.abs(p[0] - last[0]) < 0.4 && Math.abs(p[1] - last[1]) < 0.4) return;
+ lassoDraw.pts.push(p);
+ lassoRenderPath(stage, stateName, lassoDraw.pts, false);
+ };
+ const onUp = () => {
+ try { stage.releasePointerCapture(ev.pointerId); } catch { /* no-op */ }
+ stage.removeEventListener("pointermove", onMove);
+ stage.removeEventListener("pointerup", onUp);
+ const pts = lassoDraw ? lassoDraw.pts : [];
+ const [cw, ch] = cellDims(stateName);
+ const sel = lassoRasterize(pts, cw, ch);
+ lassoClearPath();
+ onSelection(sel);
+ };
+ stage.addEventListener("pointermove", onMove);
+ stage.addEventListener("pointerup", onUp);
+ });
+}
diff --git a/sprite_gen/serve/curator/src/persistence.js b/sprite_gen/serve/curator/src/persistence.js
new file mode 100644
index 0000000..6fc4609
--- /dev/null
+++ b/sprite_gen/serve/curator/src/persistence.js
@@ -0,0 +1,184 @@
+// SPDX-License-Identifier: Apache-2.0
+// curator/persistence.js — curation.json 저장 (디바운스 autosave + 유실 배너) / 산출물 다운로드
+// 로드 순서 SSoT = index.html (classic script 전역 어휘 공유; 빌드 스텝 없음)
+
+let saveTimer = null;
+
+function buildPayload() {
+ const states = {};
+ for (const [name, entry] of Object.entries(entries)) {
+ if (name === BASE_STATE) continue; // 가상 상태 — 큐레이션 사이드카에 절대 저장 금지
+ const transforms = {};
+ for (const [idx, t] of Object.entries(entry.transforms)) {
+ if (t.rotate || t.scale !== 1 || t.dx || t.dy || t.shx || t.shy || t.flipX) transforms[idx] = t;
+ }
+ // `selected` is the play order (what compose bakes). `order` is the full
+ // display order (sequence then pool) so the webview can restore the exact
+ // row arrangement on reload — compose/curation.py ignore it.
+ states[name] = {
+ selected: entry.order.filter((idx) => entry.sel.has(idx)),
+ order: entry.order.slice(),
+ transforms,
+ };
+ // 보관함 = 스키마의 deleted (UI 행/굽기 기본값에서 제외 — state_plan SSoT)
+ if (entry.archived && entry.archived.length) states[name].deleted = entry.archived.slice();
+ // 복제 인스턴스 맵 — order 에 남아 있는 복제만 저장 (제거된 복제는 흔적 없이 정리)
+ const liveClones = {};
+ for (const [ci, src] of Object.entries(entry.clones || {})) {
+ if (entry.order.includes(Number(ci))) liveClones[ci] = src;
+ }
+ if (Object.keys(liveClones).length) states[name].clones = liveClones;
+ // 링크 끊은 복제 (독립 편집 소유) — 살아있는 복제만
+ const liveUnlinked = [...(entry.unlinked || [])].filter((ci) => liveClones[ci] !== undefined);
+ if (liveUnlinked.length) states[name].unlinked = liveUnlinked;
+ // 인스턴스 이름 (표시용 별명 — 예: "깜빡임") — 살아있는 인스턴스만
+ const liveNames = {};
+ for (const [i, nm] of Object.entries(entry.names || {})) {
+ if (entry.order.includes(Number(i)) && nm) liveNames[i] = nm;
+ }
+ if (Object.keys(liveNames).length) states[name].names = liveNames;
+ // 픽셀 편집 사이드카 (빈 프레임 엔트리는 정리)
+ const px = {};
+ for (const [i, ops] of Object.entries(entry.pixels || {})) {
+ if (ops && Object.keys(ops).length) px[i] = ops;
+ }
+ if (Object.keys(px).length) states[name].pixels = px;
+ // per-state pixel-unfake — **트윈 줄만 저장** (계약): 트윈 없는 줄의 퍼펙은
+ // 표시 렌즈(측정 k 양자화)라 사이드카에 적으면 굽기 리졸버가 존재하지 않는
+ // .plain 변형을 요구하게 된다. 격자 토글과 같은 표시-전용 상태다.
+ // authoring 규칙의 SSoT 는 `authoredUnfake` 다. **해소 규칙과는 다른 함수**다 —
+ // 뷰가 안 적는 값도 사이드카엔 남아 있을 수 있고(서버 이월), 굽기는 그걸 읽는다.
+ const ownPp = authoredUnfake(name);
+ if (ownPp !== undefined) states[name].pixel_unfake = ownPp;
+ // 호흡 후처리 레이어 (maintainer 2026-07-18) — 켠 상태만 기록 (없음 = off)
+ if (entry.breathe) states[name].breathe = entry.breathe;
+ // 폐기 스키마는 **원본 그대로 되쓴다.** 정규화도 삭제도 하지 않는다 — 웹뷰가 못 읽는
+ // 사이드카를 웹뷰가 파괴하면 굽기의 loud reject 와 migrate-breathe 가 근거를 잃는다.
+ else if (entry.breatheRetired) states[name].breathe = entry.breatheRetired.raw;
+ }
+ const payload = { version: run.schemaVersion || 1, kind: "sprite-gen-curation", states };
+ // 방향 앵커 프레임 지정 — **항상 실어 보낸다** (해제도 의도다). 키가 없으면 서버가
+ // 이전 지정을 이월하므로(엔진 CLI 로 심은 지정 보호), 빈 객체가 "지정 없음" 의 표현이다.
+ payload.anchors = { ...anchorPicks };
+ // 채택 컬러웨이 — **variant 섹션이 있는 런에서만** authoring 한다. 이 런에 베이크
+ // 산출물이 없으면 뷰는 이 필드를 모르는 것이고, 안 싣는 것이 곧 "건드리지 않음" 이다
+ // (서버가 기존 값을 이월한다). 섹션이 있으면 해제도 의도라 빈 객체를 싣는다.
+ if (run.recolor) payload.recolor = recolorPicked ? { picked: recolorPicked } : {};
+ // echo the run generation this view was loaded with; the server rejects the autosave
+ // (409) if the run was re-imported/re-extracted under this session so stale selections
+ // never land on new frames.
+ if (run.runRevision) payload.runRevision = run.runRevision;
+ // run-wide default field: written only when every twin row agrees (uniform),
+ // so a consumer without per-state awareness still bakes the right variant.
+ // Mixed rows -> omitted; the per-state values above are the truth.
+ // `savedRunUnfake` 가 이 필드의 authoring 규칙을 소유한다 (트윈 줄이 전부 같을
+ // 때만 authoring; 아니면 로드된 값을 그대로 둔다 — 서버가 이월한다).
+ const widePp = savedRunUnfake();
+ if (widePp !== undefined) payload.pixel_unfake = widePp;
+ return payload;
+}
+
+let lastEditAt = 0;
+
+function scheduleSave() {
+ if (zoomView && zoomView.stateName === BASE_STATE) {
+ // 베이스 편집은 파일 굽기 대상 — "저장됨" 오해 방지, 명시 버튼으로만 반영
+ setStatus(t("baseUnsaved"));
+ return;
+ }
+ lastEditAt = Date.now();
+ setStatus(t("editing"));
+ if (typeof markAtlasStale === "function") markAtlasStale(); // 아틀라스 스테일 배지
+ clearTimeout(saveTimer);
+ saveTimer = setTimeout(save, 250);
+}
+
+// 대기 중인 디바운스 저장을 즉시 밀어낸다 — 서버가 디스크의 curation.json 을 읽는
+// 작업(아틀라스 굽기, GIF, export) 직전에 호출해 "마지막 250ms 편집 누락" 레이스 제거.
+async function flushSave() {
+ clearTimeout(saveTimer);
+ await save();
+}
+
+async function save() {
+ try {
+ const res = await fetch("/api/curation", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(buildPayload()),
+ });
+ if (!res.ok) throw new Error((await res.json()).error || res.statusText);
+ setStatus(t("saved"), "ok");
+ hideSaveLostBanner();
+ // 디스크 truth 가 바뀌었다 = 앵커 라이브 베이크도 달라졌을 수 있다 (앵커 프레임의
+ // 픽셀 편집·변형·시퀀스 변경). 칩은 서버에서 다시 받아야 최신이다 — 카운터의
+ // 단일 writer 는 여기다.
+ anchorCacheBust += 1;
+ if (typeof refreshAnchorChips === "function") refreshAnchorChips();
+ // 디스크 truth 갱신 후 — 레이지 아틀라스 자동 굽기 (보일 때만 실제 굽기)
+ if (typeof noteAtlasEdit === "function") noteAtlasEdit();
+ } catch (e) {
+ setStatus(t("saveFail") + e.message, "err");
+ // 작은 상태줄만으론 그림 그리는 중에 못 본다 (회귀 2026-07-17: 서버 재기동으로
+ // 죽은 탭에서 픽셀 편집이 조용히 유실, maintainer 발견). 저장이 실패하면 무시할 수
+ // 없는 배너로 알린다 — 편집은 계속 가능하되 "지금 저장 안 되고 있음" 이 보인다.
+ showSaveLostBanner(e.message);
+ }
+}
+
+let saveLostBanner = null;
+
+function showSaveLostBanner(detail) {
+ if (!saveLostBanner) {
+ saveLostBanner = document.createElement("div");
+ saveLostBanner.className = "save-lost-banner";
+ document.body.appendChild(saveLostBanner);
+ }
+ saveLostBanner.textContent = `${t("saveLostBanner")} (${detail})`;
+ saveLostBanner.hidden = false;
+}
+
+function hideSaveLostBanner() {
+ if (saveLostBanner) saveLostBanner.hidden = true;
+}
+
+async function downloadArtifact(kind, doneMsg) {
+ clearTimeout(saveTimer);
+ await save();
+ setStatus(t("baking"));
+ const res = await fetch(`/download/${kind}`);
+ if (!res.ok) {
+ let msg = "download failed";
+ try {
+ const data = await res.json();
+ msg = (data.stderr || data.error || msg).trim();
+ } catch { /* 비 JSON 에러 응답 — 기본 메시지 유지 */ }
+ throw new Error(msg);
+ }
+ const blob = await res.blob();
+ const link = document.createElement("a");
+ link.href = URL.createObjectURL(blob);
+ link.download = res.headers.get("X-Filename") || `${kind}.zip`;
+ link.click();
+ URL.revokeObjectURL(link.href);
+ if (kind === "atlas") await refreshFinalAtlas(); // 방금 재계산된 시트/문서 반영
+ setStatus(doneMsg, "ok");
+}
+
+for (const [id, kind, done] of [
+ ["compose", "atlas", () => t("composeDone")],
+ ["export", "pngs", () => STR[lang].exportDone()],
+ ["export-gif", "gifs", () => STR[lang].exportGifDone()],
+]) {
+ document.getElementById(id).addEventListener("click", async (ev) => {
+ const btn = ev.currentTarget;
+ btn.disabled = true;
+ try {
+ await downloadArtifact(kind, done());
+ } catch (e) {
+ setStatus(t(id === "compose" ? "composeFail" : "exportFail") + e.message, "err");
+ } finally {
+ btn.disabled = false;
+ }
+ });
+}
diff --git a/sprite_gen/serve/curator/src/pipeline-tree.js b/sprite_gen/serve/curator/src/pipeline-tree.js
new file mode 100644
index 0000000..5cd1368
--- /dev/null
+++ b/sprite_gen/serve/curator/src/pipeline-tree.js
@@ -0,0 +1,370 @@
+// SPDX-License-Identifier: Apache-2.0
+// curator/pipeline-tree.js — 생성 구조 트리 (파이프라인 진행 현황판, 폴링)
+// 로드 순서 SSoT = index.html (classic script 전역 어휘 공유; 빌드 스텝 없음)
+
+// base → 방향별 idle 행 → 앵커(frame-0 크롭 1장) → 각 행. 방향 계약 없는 런은
+// base → 행 2단. 미생성 노드는 점선(진행 현황판 겸용), 클릭 = 해당 줄로 스크롤.
+function treeNode(label, note, thumbUrl, targetState, extra) {
+ const rawOnly = thumbUrl && typeof thumbUrl === "object" && thumbUrl.raw;
+ const node = document.createElement("span");
+ node.className = "tree-node" + (thumbUrl === false ? " pending" : "") + (rawOnly ? " raw-only" : "") + (extra ? " " + extra : "");
+ if (rawOnly) {
+ const img = document.createElement("img");
+ img.src = thumbUrl.raw;
+ img.alt = label;
+ node.appendChild(img);
+ } else if (thumbUrl) {
+ const img = document.createElement("img");
+ img.src = thumbUrl;
+ img.alt = label;
+ node.appendChild(img);
+ } else if (thumbUrl === false) {
+ node.appendChild(Object.assign(document.createElement("span"), { className: "thumb-missing" }));
+ }
+ node.appendChild(Object.assign(document.createElement("span"), { className: "tn-label", textContent: label }));
+ if (note) node.appendChild(Object.assign(document.createElement("span"), { className: "tn-note", textContent: note }));
+ if (targetState) {
+ node.setAttribute("data-tip", t("tTreeNode"));
+ node.classList.add("clickable");
+ node.addEventListener("click", () => {
+ const section = targetState === "__base__"
+ ? document.querySelector(".base-row")
+ : targetState === "__atlas__"
+ ? document.getElementById("final-atlas")
+ : targetState === "__recolor__"
+ ? document.getElementById("recolor-variants")
+ : document.querySelector(`.state[data-state="${cssEscape(targetState)}"]`);
+ if (!section) return;
+ section.scrollIntoView({ behavior: "smooth", block: "start" });
+ flashSection(section);
+ });
+ }
+ return node;
+}
+
+// 생성 진행 스냅샷 (트리 실시간 갱신): stateName -> {raw, frames}. 초기값은 /api/run,
+// 이후 /api/progress 3초 폴링이 갱신한다.
+let treeProgress = new Map();
+
+let treeRevision = null;
+
+async function seedTreeProgress() {
+ // 초기값도 /api/progress 로 — 경로(rawUrl/frame0Url/relRaw)는 서버 리졸버가 SSoT
+ // (택소노미/flat 레이아웃을 클라이언트가 패턴 조립하지 않는다).
+ try {
+ const res = await fetch("/api/progress");
+ const next = await res.json();
+ if (next.states) {
+ treeProgress = new Map(next.states.map((p) => [p.name, p]));
+ treeRevision = next.runRevision;
+ return;
+ }
+ } catch { /* 아래 폴백 */ }
+ treeProgress = new Map(run.states.map((s) => [s.name, {
+ raw: !!s.rawPresent,
+ frames: s.frames.filter((f) => f.present).length,
+ }]));
+ treeRevision = run.runRevision;
+}
+
+function renderPipelineTree() {
+ const frameThumb = (name) => {
+ const p = treeProgress.get(name);
+ if (!(p && p.frames > 0)) return false;
+ return `${p.frame0Url || `/frames/${encodeURIComponent(name)}/frame-0.png`}?v=${treeRevision || 0}`;
+ };
+ const rawThumb = (name) => {
+ const p = treeProgress.get(name);
+ if (!(p && p.raw)) return false;
+ return `${p.rawUrl || `/run/raw/${encodeURIComponent(name)}.png`}?v=${treeRevision || 0}`;
+ };
+ const frameCount = (name) => {
+ const p = treeProgress.get(name);
+ return p ? p.frames : 0;
+ };
+ // 생성 진행을 반영한 대표 썸네일: 추출 프레임 > raw 스트립 > 미생성
+ const bestThumb = (name) => {
+ const f = frameThumb(name);
+ if (f) return f;
+ const r = rawThumb(name);
+ return r ? { raw: r } : false;
+ };
+ // 앵커 노드 썸네일 = 칩과 같은 라이브 베이크 (`/api/anchor`). 파일 스냅샷을 이름으로
+ // 찾던 옛 구현은 실제 파일명(`<dir>-idle-x8.png`)과 어긋나 언제나 폴백했고, 맞았더라도
+ // 편집 직후엔 낡은 그림을 보여줬다.
+ const anchorFileThumb = (direction) => {
+ const g = (run.directionGroups || []).find((x) => x.direction === direction && !x.mirrorOf);
+ return g && g.anchorUrl ? `${g.anchorUrl}&t=${anchorCacheBust}` : null;
+ };
+ const chipList = () => {
+ const ul = document.createElement("ul");
+ ul.className = "tree-rows";
+ return ul;
+ };
+ const chipItem = (ul, node) => {
+ const el = document.createElement("li");
+ el.appendChild(node);
+ ul.appendChild(el);
+ };
+ const liWith = (parentUl, ...nodes) => {
+ const el = document.createElement("li");
+ for (const n of nodes) if (n) el.appendChild(n);
+ parentUl.appendChild(el);
+ return el;
+ };
+ // 접을 수 있는 블록 (파이프라인 / 파일) — folderNode 의 접힘 상태 공유
+ const block = (label, ul, kind) => {
+ const div = document.createElement("div");
+ div.className = "tree-block" + (kind ? " " + kind : "");
+ div.appendChild(folderNode(label, null, kind === "pipeline" ? "flow" : "folder"));
+ div.appendChild(ul);
+ if (collapsedFolders.has(label)) div.classList.add("folder-collapsed");
+ return div;
+ };
+ const stateChip = (name, extraNote, extraCls) => {
+ const n = frameCount(name);
+ const note = [n > 0 ? STR[lang].treeFrameCount(n) : t("treePending"), extraNote].filter(Boolean).join(" · ");
+ return treeNode(name, note, bestThumb(name), name, extraCls);
+ };
+
+ // ── 파이프라인 블록: base → <dir>_idle 행 → 방향 앵커 → rows 체인 ──────────
+ const chainUl = document.createElement("ul");
+ let chainHost = chainUl;
+ if (run.baseUrl) {
+ const baseLi = liWith(chainUl, treeNode("base", t("treeBaseNote"), run.baseUrl, "__base__", "tree-root"));
+ chainHost = document.createElement("ul");
+ baseLi.appendChild(chainHost);
+ }
+ if (run.directionGroups && run.directionGroups.length) {
+ for (const group of run.directionGroups) {
+ if (group.mirrorOf) {
+ liWith(chainHost, treeNode(STR[lang].treeMirror(group.direction, group.mirrorOf), null, undefined, null, "mirror"));
+ continue;
+ }
+ if (group.anchor) {
+ const idleLi = liWith(chainHost, stateChip(group.anchor, t("treeIdleRow")));
+ const anchorUl = document.createElement("ul");
+ idleLi.appendChild(anchorUl);
+ const anchorLi = liWith(anchorUl, treeNode(
+ `${group.direction} ${t("dirAnchorBadge")}`, t("treeAnchorNote"),
+ anchorFileThumb(group.direction) || bestThumb(group.anchor), group.anchor, "anchor"));
+ const rows = chipList();
+ for (const name of group.states.filter((n) => n !== group.anchor)) chipItem(rows, stateChip(name));
+ anchorLi.appendChild(rows);
+ } else {
+ const rows = chipList();
+ for (const name of group.states) chipItem(rows, stateChip(name));
+ liWith(chainHost, treeNode(group.direction, null, undefined, null)).appendChild(rows);
+ }
+ }
+ } else {
+ const rows = chipList();
+ for (const st of run.states) chipItem(rows, stateChip(st.name));
+ const holder = liWith(chainHost);
+ holder.appendChild(rows);
+ }
+ // 체인의 종착지 = 최종 아틀라스 (클릭 → 맨 아래 섹션으로 스크롤)
+ liWith(chainUl, treeNode(t("treeAtlas"), run.atlas ? null : t("treePending"),
+ run.atlas ? run.atlas.url : false, "__atlas__", "atlas-node"));
+
+ // ── 파일 블록: 폴더 뼈대 (어디에 저장되는가) ──────────────────────────────
+ const fileUl = document.createElement("ul");
+ if (run.baseUrl) liWith(fileUl, treeNode("base-source", null, run.baseUrl, "__base__"));
+ // 택소노미 중첩: rel 경로가 <root>/<dir>/<leaf> 면 방향 하위 폴더로 묶는다 (legacy flat 은 그대로)
+ const groupedFolder = (rootLabel, rootNote, relKey, chipFor) => {
+ const rootLi = liWith(fileUl, folderNode(rootLabel, rootNote));
+ const dirs = new Map(); // "" = flat
+ for (const st of run.states) {
+ const rel = (treeProgress.get(st.name) || {})[relKey] || "";
+ const segs = rel.split("/");
+ const dir = segs.length >= 3 ? segs[1] : "";
+ const leaf = segs.length >= 3 ? segs.slice(2).join("/") : segs.slice(1).join("/");
+ if (!dirs.has(dir)) dirs.set(dir, []);
+ dirs.get(dir).push({ state: st, leaf: leaf || st.name });
+ }
+ const host = document.createElement("ul");
+ for (const [dir, items] of dirs) {
+ if (dir) {
+ const dli = document.createElement("li");
+ dli.appendChild(folderNode(`${dir}/`, null));
+ const ul = chipList();
+ for (const it of items) chipItem(ul, chipFor(it));
+ dli.appendChild(ul);
+ host.appendChild(dli);
+ } else {
+ for (const it of items) {
+ const li = document.createElement("li");
+ li.appendChild(chipFor(it));
+ host.appendChild(li);
+ }
+ }
+ }
+ rootLi.appendChild(host);
+ };
+ groupedFolder("raw/", t("treeRawFolder"), "relRaw", (it) => {
+ const thumb = rawThumb(it.state.name);
+ const note = thumb && frameCount(it.state.name) === 0 ? t("treeRawNote") : null;
+ return treeNode(it.leaf, note, thumb ? { raw: thumb } : false, it.state.name);
+ });
+ groupedFolder("frames/", t("treeFramesFolder"), "relFrames", (it) => {
+ const n = frameCount(it.state.name);
+ return treeNode(`${it.leaf}/`, n > 0 ? STR[lang].treeFrameCount(n) : t("treePending"), frameThumb(it.state.name), it.state.name);
+ });
+ if (run.anchorFiles && run.anchorFiles.length) {
+ const aLi = liWith(fileUl, folderNode("references/anchors/", t("treeAnchorsFolder")));
+ const aUl = chipList();
+ for (const a of run.anchorFiles) {
+ chipItem(aUl, treeNode(a.name, t("treeAnchorNote"), `${a.url}?v=${treeRevision || 0}`, null, "anchor"));
+ }
+ aLi.appendChild(aUl);
+ }
+ if (run.hasAtlas) {
+ // 파일 트리의 아틀라스 노드도 클릭 = 최종 아틀라스 섹션 스크롤 (maintainer 2026-07-18 —
+ // 파이프라인 트리의 아틀라스 노드와 같은 목적지; "__atlas__" 라우팅 공유)
+ liWith(fileUl, treeNode("sprite-sheet-alpha.png", t("treeAtlasNote"), `/run/sprite-sheet-alpha.png?v=${treeRevision || 0}`, "__atlas__"));
+ }
+ if (run.recolor) {
+ // 구운 컬러웨이 폴더 — 클릭 = 컬러웨이 섹션 스크롤 ("__recolor__" 라우팅)
+ const rcLi = liWith(fileUl, folderNode(`${run.recolor.dir}/`, t("treeRecolorNote")));
+ const rcUl = chipList();
+ for (const v of run.recolor.variants) {
+ // 채택 배지는 **라이브 진실**(recolorPicked)로 그린다 — run.recolor.picked 는
+ // 로드 시점 스냅샷이라, 픽 후 트리 폴링 재렌더가 옛 채택을 되살려 보인다.
+ chipItem(rcUl, treeNode(v.sheet, v.name === recolorPicked ? t("rcPicked") : null,
+ v.url || false, "__recolor__"));
+ }
+ rcLi.appendChild(rcUl);
+ }
+
+ const wrap = document.createElement("section");
+ wrap.className = "state pipeline-tree";
+ wrap.innerHTML =
+ `<div class="state-head"><span class="name">${t("treeTitle")}</span>` +
+ `<span class="meta tree-path" title="${escapeHtml(run.runDir)}">${escapeHtml(run.runDir)}</span></div>`;
+ // 파이프라인 가지 곡선: CSS border 는 대시 애니메이션이 못 타므로 SVG 패스로.
+ // rail(정적 옅은 액센트) 위로 dash 가 곡선을 따라 흘러내린다.
+ const SVG_NS = "http://www.w3.org/2000/svg";
+ const attachBranch = (li) => {
+ const svg = document.createElementNS(SVG_NS, "svg");
+ svg.setAttribute("class", "branch");
+ svg.setAttribute("viewBox", "0 0 15 19");
+ svg.setAttribute("width", "15");
+ svg.setAttribute("height", "19");
+ const d = "M0.5 0 V11.5 Q0.5 18.5 7.5 18.5 H15";
+ for (const cls of ["rail", "dash"]) {
+ const path = document.createElementNS(SVG_NS, "path");
+ path.setAttribute("d", d);
+ path.setAttribute("class", cls);
+ svg.appendChild(path);
+ }
+ li.insertBefore(svg, li.firstChild);
+ };
+ for (const li of chainUl.querySelectorAll("li")) attachBranch(li);
+
+ const root = document.createElement("div");
+ root.className = "tree";
+ root.appendChild(block(t("treePipeline"), chainUl, "pipeline"));
+ root.appendChild(block(t("treeFiles"), fileUl));
+ wrap.appendChild(root);
+ const existing = document.querySelector(".pipeline-tree");
+ if (existing) existing.replaceWith(wrap);
+ else document.getElementById("sidebar").appendChild(wrap);
+}
+
+// 폴더 노드 — SVG 폴더 아이콘 + 경로 라벨 (이모지 금지 규칙).
+// 클릭 = 접기/펴기. 트리는 진행 폴링으로 재렌더되므로 접힘 상태를 라벨 키로 유지한다.
+const collapsedFolders = new Set();
+
+const FOLDER_ICON =
+ '<svg viewBox="0 0 16 16" width="14" height="14" aria-hidden="true">' +
+ '<path d="M1.5 4A1.5 1.5 0 0 1 3 2.5h2.6a1 1 0 0 1 .8.4l.9 1.1H13A1.5 1.5 0 0 1 14.5 5.5v6A1.5 1.5 0 0 1 13 13H3a1.5 1.5 0 0 1-1.5-1.5V4z" fill="none" stroke="currentColor" stroke-width="1.2"/></svg>';
+
+// 파이프라인(흐름) 아이콘 — 위 노드에서 아래 노드로 흘러 내려가는 모양 (폴더와 구분)
+const FLOW_ICON =
+ '<svg viewBox="0 0 16 16" width="14" height="14" aria-hidden="true">' +
+ '<circle cx="8" cy="3" r="1.7" fill="none" stroke="currentColor" stroke-width="1.2"/>' +
+ '<path d="M8 4.7v4.1M5.6 8.9 8 11.3l2.4-2.4" fill="none" stroke="currentColor" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/>' +
+ '<circle cx="8" cy="13" r="1.7" fill="none" stroke="currentColor" stroke-width="1.2"/></svg>';
+
+function folderNode(label, note, icon) {
+ const node = document.createElement("span");
+ node.className = "tree-node folder clickable";
+ node.innerHTML =
+ '<svg class="caret" viewBox="0 0 16 16" width="10" height="10" aria-hidden="true">' +
+ '<path d="M5 3.5 10.5 8 5 12.5" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/></svg>' +
+ (icon === "flow" ? FLOW_ICON : FOLDER_ICON);
+ node.appendChild(Object.assign(document.createElement("span"), { className: "tn-label", textContent: label }));
+ if (note) node.appendChild(Object.assign(document.createElement("span"), { className: "tn-note", textContent: note }));
+ node.addEventListener("click", () => {
+ const li = node.parentElement;
+ const collapsed = !li.classList.contains("folder-collapsed");
+ li.classList.toggle("folder-collapsed", collapsed);
+ if (collapsed) collapsedFolders.add(label);
+ else {
+ collapsedFolders.delete(label);
+ for (const ul of li.querySelectorAll(":scope > ul")) {
+ ul.animate(
+ [{ opacity: 0, transform: "translateY(-5px)" }, { opacity: 1, transform: "none" }],
+ { duration: 190, easing: "ease" });
+ }
+ }
+ });
+ return node;
+}
+
+// 3초 폴링: 생성/추출 진행을 트리에 실시간 반영. 프레임 세대(runRevision)가 바뀌면
+// 아래 상태 줄들은 구세대라 새로고침 배너를 띄운다 (편집 중 강제 리로드는 하지 않는다).
+async function pollTreeProgress() {
+ try {
+ const res = await fetch("/api/progress");
+ if (!res.ok) return;
+ const next = await res.json();
+ if (!next.states) return;
+ const sig = JSON.stringify(next.states.map((p) => [p.name, p.raw, p.frames]));
+ const prev = JSON.stringify([...treeProgress.entries()].map(([n, p]) => [n, p.raw, p.frames]));
+ const revChanged = next.runRevision !== treeRevision;
+ if (sig !== prev || revChanged) {
+ treeProgress = new Map(next.states.map((p) => [p.name, p]));
+ treeRevision = next.runRevision;
+ renderPipelineTree();
+ // 우측 상태 패널은 로드 시점 스냅샷이라 새 raw/프레임을 모른다 — 생성을
+ // 지켜보는 중(최근 편집 없음 + 모달 안 열림)이면 통째로 새로고침해 동기화.
+ // 편집 중이면 강제 리로드 대신 배너만 (자동저장이 보존하지만 흐름을 끊지 않게).
+ const editing = Date.now() - lastEditAt < 15000 || document.getElementById("zoom-modal");
+ if (!editing) {
+ location.reload();
+ return;
+ }
+ }
+ if (next.runRevision !== run.runRevision) showReloadBanner();
+ } catch {
+ /* 서버 일시 중단은 조용히 재시도 */
+ }
+}
+
+function showReloadBanner() {
+ if (document.getElementById("reload-banner")) return;
+ const banner = document.createElement("button");
+ banner.id = "reload-banner";
+ banner.type = "button";
+ banner.textContent = t("reloadBanner");
+ banner.addEventListener("click", () => location.reload());
+ document.body.appendChild(banner);
+}
+
+// 이동한 대상 패널 하이라이트: 스크롤이 끝난 뒤 따닥 두 번 깜빡이고 사라진다.
+// scrollend 지원 브라우저는 도착 즉시, 아니면 짧은 타임아웃 폴백.
+function flashSection(el) {
+ let fired = false;
+ const fire = () => {
+ if (fired) return;
+ fired = true;
+ window.removeEventListener("scrollend", fire);
+ el.classList.remove("flash-target");
+ void el.offsetWidth; // 연속 클릭 시 애니메이션 재시작
+ el.classList.add("flash-target");
+ el.addEventListener("animationend", () => el.classList.remove("flash-target"), { once: true });
+ };
+ window.addEventListener("scrollend", fire, { once: true });
+ setTimeout(fire, 750); // 스크롤이 필요 없거나 scrollend 미지원일 때
+}
diff --git a/sprite_gen/serve/curator/src/progress.js b/sprite_gen/serve/curator/src/progress.js
new file mode 100644
index 0000000..3b45297
--- /dev/null
+++ b/sprite_gen/serve/curator/src/progress.js
@@ -0,0 +1,99 @@
+// SPDX-License-Identifier: Apache-2.0
+// curator/progress.js — 오래 걸리는 파이프라인(추출 등)의 퍼센트 진행도 표시
+// 로드 순서 SSoT = index.html (classic script 전역 어휘 공유; 빌드 스텝 없음)
+//
+// 엔진이 .sprite-gen.progress.json 에 상태×단계 단위로 기록한 진행을
+// /api/op-progress 로 폴링해 상단 바 + 상태줄 퍼센트로 보여준다
+// (maintainer 요청 2026-07-18 "잘게잘게 퍼센트로"). 표시 전용 — truth 는 엔진 파일.
+
+let opPollTimer = null;
+
+function topProgressBar() {
+ let bar = document.getElementById("op-progress");
+ if (!bar) {
+ bar = document.createElement("div");
+ bar.id = "op-progress";
+ bar.innerHTML = '<div class="op-progress-fill"></div>';
+ document.body.appendChild(bar);
+ }
+ return bar;
+}
+
+function setTopProgress(pct) {
+ const bar = topProgressBar();
+ const fill = bar.querySelector(".op-progress-fill");
+ if (pct === null) { // busy 인데 진행 미기록 — 불확정 표시
+ bar.hidden = false;
+ fill.classList.add("indeterminate");
+ fill.style.width = "100%";
+ return;
+ }
+ fill.classList.remove("indeterminate");
+ if (pct <= 0 || pct >= 100) {
+ bar.hidden = true;
+ fill.style.width = "0%";
+ return;
+ }
+ bar.hidden = false;
+ fill.style.width = `${pct}%`;
+}
+
+function stopOpProgressWatch() {
+ if (opPollTimer) {
+ clearInterval(opPollTimer);
+ opPollTimer = null;
+ }
+ setTopProgress(0);
+}
+
+// onIdle: busy 가 풀렸을 때 1회 호출 (예: 리로드) — 폴링은 자동 중단
+function startOpProgressWatch(onIdle) {
+ if (opPollTimer) return;
+ const tick = async () => {
+ let data = null;
+ try {
+ const res = await fetch("/api/op-progress");
+ data = await res.json();
+ } catch {
+ return; // 서버 재시작 등 일시 오류 — 다음 틱에 재시도
+ }
+ if (!data || !data.busy) {
+ stopOpProgressWatch();
+ if (onIdle) onIdle();
+ return;
+ }
+ const p = data.progress;
+ const live = document.getElementById("op-loading-live");
+ const panelFill = document.querySelector(".op-loading-fill");
+ if (p && p.total) {
+ const pct = Math.min(99, Math.round((p.done / p.total) * 100));
+ setStatus(STR[lang].opProgress(p, pct));
+ setTopProgress(pct);
+ if (live) live.textContent = STR[lang].opProgress(p, pct);
+ if (panelFill) {
+ panelFill.classList.remove("indeterminate");
+ panelFill.style.width = `${Math.max(2, pct)}%`;
+ }
+ } else {
+ setTopProgress(null);
+ if (live) live.textContent = t("healWaiting");
+ if (panelFill) panelFill.classList.add("indeterminate");
+ }
+ };
+ opPollTimer = setInterval(tick, 800);
+ tick();
+}
+
+// 장기 heal/추출 중 첫 로드용 정식 로딩 패널 — fatal 에러 박스가 아니라
+// 진행 바·퍼센트·현재 행·안내 문구를 보여준다 (plan long-op-loading-ux:
+// 엔진 갱신 후 첫 탭이 빈 화면으로 수십 분 멈추던 회귀의 클라 반쪽).
+function renderLoadingPanel() {
+ const host = document.getElementById("states");
+ host.innerHTML =
+ '<div class="op-loading">' +
+ `<div class="op-loading-title">${t("healTitle")}</div>` +
+ '<div class="op-loading-bar"><div class="op-loading-fill indeterminate" style="width:100%"></div></div>' +
+ `<div id="op-loading-live" class="op-loading-live">${t("healWaiting")}</div>` +
+ `<div class="op-loading-note">${t("healNote")}</div>` +
+ "</div>";
+}
diff --git a/sprite_gen/serve/curator/src/recolor.js b/sprite_gen/serve/curator/src/recolor.js
new file mode 100644
index 0000000..d77587c
--- /dev/null
+++ b/sprite_gen/serve/curator/src/recolor.js
@@ -0,0 +1,158 @@
+// SPDX-License-Identifier: Apache-2.0
+// curator/recolor.js — 컬러웨이(recolor variant) 비교·픽 섹션
+// 로드 순서 SSoT = index.html (classic script 전역 어휘 공유; 빌드 스텝 없음)
+
+// 색 변형은 **같은 자리에서 갈아끼워야** 보인다. 두 시트를 나란히 놓고 눈을 좌우로
+// 옮기면 도트 한 칸짜리 색차는 그냥 안 보인다 — 그래서 이 섹션은 큰 스테이지 하나에
+// 모든 시트를 겹쳐 쌓아두고(전부 미리 로드) 목록 위를 지나갈 때 즉시 교체한다.
+// 깜빡임 비교가 기본이고, 목록은 그 자체로 나란히 비교(썸네일)도 겸한다.
+//
+// 채택(픽)은 큐레이션 사이드카의 `recolor.picked` 하나다 — 이름으로만 기록한다
+// (curation.py `recolor_pick` 계약: 컬러웨이는 프레임 세대가 아니라 색 결정이라
+// 재베이크로 낡지 않는다). 베이크 리포트에 없는 이름은 조용히 지우지 않고
+// 서버가 `pickedKnown: false` 로 알려주며, 여기서 경고로 보인다.
+
+const RECOLOR_BASE_KEY = "__base__";
+const RECOLOR_SWATCH_PX = 64;
+
+// 썸네일은 시트가 아니라 **프레임 한 칸**을 보여준다 — 1280px 짜리 띠를 68px 로 줄이면
+// 색이 사라진다. 상자는 서버가 manifest `frame_layout` 에서 읽어 준 것이고 (swatch),
+// 여기선 그 상자가 칸을 채우도록 `<img>` 를 키우고 밀어 넣는다. transform 이 아니라
+// width/margin 인 이유: 표시 샘플링 판정(display.js applyPixelScaling)이 clientWidth 를
+// 재기 때문에, 변환으로 키우면 판정이 확대를 못 보고 니어리스트가 안 걸린다.
+function recolorSwatchStyle(swatch) {
+ if (!swatch || !swatch.w || !swatch.h) return "";
+ const scale = RECOLOR_SWATCH_PX / Math.max(swatch.w, swatch.h);
+ return ` style="width:${swatch.sheetWidth * scale}px;max-width:none;` +
+ `margin-left:${-swatch.x * scale}px;margin-top:${-swatch.y * scale}px"`;
+}
+
+let recolorPicked = null; // 채택된 variant 이름 (없으면 null) — 저장 페이로드의 진실
+let recolorPreview = null; // 지금 스테이지에 보이는 것 (RECOLOR_BASE_KEY | variant 이름)
+
+function seedRecolorPick(runState) {
+ recolorPicked = (runState.recolor && runState.recolor.picked) || null;
+ recolorPreview = recolorPicked || RECOLOR_BASE_KEY;
+}
+
+function renderRecolorVariants(info) {
+ const host = document.getElementById("states");
+ let section = document.getElementById("recolor-variants");
+ if (!info) {
+ // 베이크 산출물이 없는 런엔 섹션 자체가 없다 (빈 껍데기를 남기지 않는다).
+ if (section) section.remove();
+ return;
+ }
+ if (!section) {
+ section = document.createElement("div");
+ section.id = "recolor-variants";
+ section.className = "state recolor-variants";
+ host.appendChild(section);
+ }
+ const items = [
+ {
+ key: RECOLOR_BASE_KEY,
+ label: t("rcBase"),
+ url: info.base.url,
+ present: info.base.present,
+ note: info.base.name,
+ pickable: false,
+ },
+ ...info.variants.map((v) => ({
+ key: v.name,
+ label: v.name,
+ url: v.url,
+ present: v.present,
+ note: STR[lang].rcVariantNote(v.substitutedPixels, v.passthroughPixels),
+ warn: (v.unusedSources && v.unusedSources.length)
+ ? STR[lang].rcUnusedSources(v.unusedSources)
+ : null,
+ manifestUrl: v.manifestUrl,
+ pickable: true,
+ })),
+ ];
+ if (!items.some((it) => it.key === recolorPreview)) recolorPreview = RECOLOR_BASE_KEY;
+
+ const meta = STR[lang].rcMeta(info.variants.length, info.match, info.tolerance);
+ section.innerHTML =
+ `<div class="state-head"><span class="name">${t("rcTitle")}</span>` +
+ `<span class="meta" data-tip="${t("tRcSection")}">${escapeHtml(meta)}</span></div>` +
+ (info.picked && !info.pickedKnown
+ ? `<div class="rc-unknown">${escapeHtml(STR[lang].rcPickUnknown(info.picked))}</div>`
+ : "") +
+ `<div class="rc-split">` +
+ `<div class="rc-stage">` +
+ items.map((it) => (it.present
+ ? `<img data-key="${escapeHtml(it.key)}" class="${it.key === recolorPreview ? "active" : ""}"` +
+ ` src="${escapeHtml(it.url)}" alt="${escapeHtml(it.label)}" />`
+ : "")).join("") +
+ `<div class="rc-stage-label"></div></div>` +
+ `<div class="rc-list">` +
+ items.map((it) =>
+ `<div class="rc-thumb${it.key === recolorPreview ? " previewing" : ""}` +
+ `${it.key === recolorPicked ? " picked" : ""}${it.present ? "" : " missing"}"` +
+ ` data-key="${escapeHtml(it.key)}" tabindex="0" data-tip="${t("tRcThumb")}">` +
+ (it.present
+ ? `<span class="rc-swatch${info.swatch ? " cropped" : ""}">` +
+ `<img src="${escapeHtml(it.url)}" alt="${escapeHtml(it.label)}"${recolorSwatchStyle(info.swatch)} />` +
+ `</span>`
+ : `<span class="rc-missing">${t("rcMissing")}</span>`) +
+ `<div class="rc-thumb-body">` +
+ `<span class="rc-name">${escapeHtml(it.label)}</span>` +
+ `<span class="rc-note">${escapeHtml(it.note || "")}</span>` +
+ (it.warn ? `<span class="rc-warn">${escapeHtml(it.warn)}</span>` : "") +
+ (it.manifestUrl
+ ? `<a class="rc-manifest" href="${escapeHtml(it.manifestUrl)}" target="_blank">manifest.json</a>`
+ : "") +
+ `</div>` +
+ (it.pickable
+ ? `<button type="button" class="rc-pick ghost" data-key="${escapeHtml(it.key)}"` +
+ ` data-tip="${t("tRcPick")}">` +
+ `${it.key === recolorPicked ? t("rcPicked") : t("rcPick")}</button>`
+ : "") +
+ `</div>`).join("") +
+ `</div></div>`;
+
+ const stageLabel = section.querySelector(".rc-stage-label");
+ const showPreview = (key) => {
+ recolorPreview = key;
+ for (const img of section.querySelectorAll(".rc-stage img")) {
+ img.classList.toggle("active", img.dataset.key === key);
+ }
+ for (const card of section.querySelectorAll(".rc-thumb")) {
+ card.classList.toggle("previewing", card.dataset.key === key);
+ }
+ const item = items.find((it) => it.key === key);
+ stageLabel.textContent = item ? item.label : "";
+ };
+ showPreview(recolorPreview);
+
+ for (const card of section.querySelectorAll(".rc-thumb")) {
+ const key = card.dataset.key;
+ // 지나가기만 해도 즉시 교체 = 깜빡임 비교. 클릭은 고정(포커스)이라 마우스를 떼도 남는다.
+ card.addEventListener("mouseenter", () => showPreview(key));
+ card.addEventListener("focus", () => showPreview(key));
+ card.addEventListener("click", (ev) => {
+ if (ev.target.closest(".rc-pick") || ev.target.closest(".rc-manifest")) return;
+ showPreview(key);
+ });
+ card.addEventListener("keydown", (ev) => {
+ if (ev.key === "Enter" || ev.key === " ") { ev.preventDefault(); showPreview(key); }
+ });
+ }
+ for (const btn of section.querySelectorAll(".rc-pick")) {
+ btn.addEventListener("click", () => pickRecolorVariant(btn.dataset.key));
+ }
+ syncPixelScaling(section);
+}
+
+// 픽은 토글이다 — 채택한 것을 다시 누르면 해제된다 (해제도 의도라 빈 객체로 저장된다).
+function pickRecolorVariant(name) {
+ recolorPicked = recolorPicked === name ? null : name;
+ recolorPreview = recolorPicked || recolorPreview;
+ setStatus(recolorPicked ? STR[lang].rcPickSaved(recolorPicked) : t("rcPickCleared"), "ok");
+ scheduleSave();
+ // 서버 스냅샷을 다시 받지 않고 로컬 진실로 다시 그린다 — 저장은 디바운스라
+ // 지금 /api/run 을 읽으면 방금 누른 픽이 아직 디스크에 없다.
+ renderRecolorVariants({ ...run.recolor, picked: recolorPicked, pickedKnown: recolorPicked !== null });
+}
diff --git a/sprite_gen/serve/curator/src/region-transform.js b/sprite_gen/serve/curator/src/region-transform.js
new file mode 100644
index 0000000..495a79f
--- /dev/null
+++ b/sprite_gen/serve/curator/src/region-transform.js
@@ -0,0 +1,252 @@
+// SPDX-License-Identifier: Apache-2.0
+// curator/region-transform.js — 선택한 사각 영역만 이동·회전·비틀기.
+// 로드 순서 SSoT = index.html (classic script 전역 어휘 공유; 빌드 스텝 없음)
+//
+// **왜 픽셀로 굽나** (maintainer 지시 2026-07-26 "일부 영역만 비틀기 회전 이동"):
+// 사이드카 `transforms[idx]` 는 셀 **전체** 표시 변형이라 영역을 표현할 수 없다.
+// 새 스키마(`region_transforms`)를 넣으면 Python bake·마이그레이션·오라클이 전부
+// 따라와야 한다. 대신 확정 시점에 결과를 래스터화해 기존 `pixels[idx]` 로 쓴다 —
+// 스키마 0 변경, bake 경로 그대로, undo/redo 도 기존 픽셀 히스토리를 탄다.
+//
+// 대가: 영역 변형은 **비가역 래스터**다(전체 변형처럼 파라미터로 안 남는다).
+// 확정 전엔 미리보기라 자유롭게 되돌리고, 확정 후엔 픽셀 undo 로 되돌린다.
+// 도트 편집기의 자유변형이 원래 이 계약이다.
+
+// 진행 중인 영역 변형. null 이면 미리보기 없음.
+// { state, idx, rect:{x,y,w,h}, src:[{x,y,hex}], t:{dx,dy,rotate,shx,shy}, canvas }
+let regionEdit = null;
+
+function regionActive(stateName, idx) {
+ return !!regionEdit && regionEdit.state === stateName && regionEdit.idx === idx;
+}
+
+// 선택 영역의 **현재 보이는** 픽셀을 읽어 둔다 — 원본 프레임이 아니라 픽셀 편집까지
+// 합성된 상태여야 한다(연필로 고친 뒤 그 영역을 옮기면 고친 게 따라가야 한다).
+function regionCapture(stage, stateName, idx, rect) {
+ const [cw, ch] = cellDims(stateName);
+ const img = stage.querySelector("img");
+ if (!img || !img.naturalWidth) return null;
+ const buf = document.createElement("canvas");
+ buf.width = cw;
+ buf.height = ch;
+ const ctx = buf.getContext("2d", { willReadFrequently: true });
+ ctx.imageSmoothingEnabled = false;
+ // 변형 이전 공간이다 — 픽셀 op 과 같은 좌표계(셀 픽셀). IDENTITY 로 그려야 맞는다.
+ drawFrameInto(ctx, editSourceFor(stateName, img), IDENTITY(), cw, ch, null,
+ getPixelOps(stateName, idx), 1);
+ const src = [];
+ const data = ctx.getImageData(0, 0, cw, ch).data;
+ // 올가미 선택이면 `rect` 는 바운딩 박스일 뿐이고 실제 모양은 `mask` 다 —
+ // 마스크 밖 픽셀을 집으면 올가미가 사각으로 퇴화한다.
+ const mask = rect.mask || null;
+ for (let y = rect.y; y < rect.y + rect.h; y += 1) {
+ for (let x = rect.x; x < rect.x + rect.w; x += 1) {
+ if (x < 0 || y < 0 || x >= cw || y >= ch) continue;
+ if (mask && !mask.has(`${x},${y}`)) continue;
+ const o = (y * cw + x) * 4;
+ const a = data[o + 3];
+ if (!a) continue;
+ src.push({ x, y, hex: rgbaHex(data[o], data[o + 1], data[o + 2], a) });
+ }
+ }
+ return src;
+}
+
+function rgbaHex(r, g, b, a) {
+ const h = (n) => n.toString(16).padStart(2, "0");
+ return `#${h(r)}${h(g)}${h(b)}${a < 255 ? h(a) : ""}`;
+}
+
+// 변형 결과를 셀 좌표 맵으로 계산한다. 역사상으로 목적지를 훑어 구멍을 막는다.
+function regionResolve(reg) {
+ const { rect, t } = reg;
+ const ox = rect.x + rect.w / 2;
+ const oy = rect.y + rect.h / 2;
+ const inv = tpInverseSample(t, ox, oy);
+ if (!inv) return new Map();
+ const byXY = new Map();
+ for (const p of reg.src) byXY.set(`${p.x},${p.y}`, p.hex);
+ // 목적지 탐색 범위 = 원 사각을 변형한 것의 여유 있는 바운딩 박스.
+ const pad = Math.ceil(Math.max(rect.w, rect.h) * 0.75) + 2;
+ const out = new Map();
+ const x0 = Math.floor(rect.x + (t.dx || 0)) - pad;
+ const y0 = Math.floor(rect.y + (t.dy || 0)) - pad;
+ const x1 = Math.ceil(rect.x + rect.w + (t.dx || 0)) + pad;
+ const y1 = Math.ceil(rect.y + rect.h + (t.dy || 0)) + pad;
+ for (let dy = y0; dy < y1; dy += 1) {
+ for (let dx = x0; dx < x1; dx += 1) {
+ const [sx, sy] = inv(dx + 0.5, dy + 0.5);
+ const hex = byXY.get(`${Math.floor(sx)},${Math.floor(sy)}`);
+ if (hex) out.set(`${dx},${dy}`, hex);
+ }
+ }
+ return out;
+}
+
+// 미리보기 — 스테이지 위 오버레이 캔버스에 결과만 그린다. 사이드카는 안 건드린다.
+function regionRenderPreview(stage, stateName) {
+ if (!regionEdit) return;
+ const [cw, ch] = cellDims(stateName);
+ let cv = regionEdit.canvas;
+ if (!cv) {
+ cv = document.createElement("canvas");
+ cv.className = "region-preview";
+ stage.appendChild(cv);
+ regionEdit.canvas = cv;
+ }
+ cv.width = cw;
+ cv.height = ch;
+ const ctx = cv.getContext("2d");
+ ctx.clearRect(0, 0, cw, ch);
+ // 원본 자리는 비워 보여야 "옮겼다" 가 읽힌다.
+ ctx.fillStyle = "rgba(0,0,0,0)";
+ for (const [key, hex] of regionResolve(regionEdit)) {
+ const [x, y] = key.split(",").map(Number);
+ ctx.fillStyle = hex.length === 9
+ ? `rgba(${parseInt(hex.slice(1, 3), 16)},${parseInt(hex.slice(3, 5), 16)},${parseInt(hex.slice(5, 7), 16)},${parseInt(hex.slice(7, 9), 16) / 255})`
+ : hex;
+ ctx.fillRect(x, y, 1, 1);
+ }
+ applyPixelScaling(cv);
+}
+
+// 확정 — 원본 영역을 지우고(null) 옮겨간 자리에 색을 찍어 픽셀 op 으로 쓴다.
+// 지우기를 먼저, 찍기를 나중에 해야 겹치는 자리가 살아남는다.
+function regionCommit(stateName, idx) {
+ if (!regionEdit) return false;
+ const moved = regionResolve(regionEdit);
+ const identity = !regionEdit.t.dx && !regionEdit.t.dy
+ && !regionEdit.t.rotate && !regionEdit.t.shx && !regionEdit.t.shy;
+ if (identity) { regionCancel(); return false; }
+ const e = entries[stateName];
+ const ops = e.pixels[idx] || (e.pixels[idx] = {});
+ const before = { ...ops };
+ for (const p of regionEdit.src) ops[`${p.x},${p.y}`] = null;
+ for (const [key, hex] of moved) ops[key] = hex;
+ if (pixelEdit) {
+ pixelEdit.journal.push({ full: before, after: { ...ops } });
+ pixelEdit.redo.length = 0;
+ }
+ regionCancel();
+ return true;
+}
+
+function regionCancel() {
+ if (regionEdit && regionEdit.canvas && regionEdit.canvas.parentNode) {
+ regionEdit.canvas.parentNode.removeChild(regionEdit.canvas);
+ }
+ regionEdit = null;
+}
+
+// 선택이 있으면 회전·비틀기 핸들을 **선택 영역으로 옮긴다** (maintainer 지시 2026-07-26
+// "로테이트랑 비틀기가 올가미 영역 위주로 위치를 이동했으면 좋겠어").
+//
+// 왜 중요한가: 핸들은 스테이지 고정 위치(위 가운데 / 왼아래)라 선택과 무관해 보이고,
+// 실제로도 셀 전체를 돌린다. 올가미로 팔 하나를 잡아 놓고 그 핸들을 잡으면 캐릭터가
+// 통째로 돈다 — maintainer이 실사용에서 바로 밟았다. 핸들이 선택 위로 따라오면 "이건 이 영역을
+// 돌린다" 가 위치로 읽히고, 아래 `wireRegionHandles` 가 실제 대상도 영역으로 바꾼다.
+function regionPlaceHandles(stage, stateName, sel) {
+ const rot = stage.querySelector(".rotate-handle");
+ const shr = stage.querySelector(".shear-handle");
+ if (!rot || !shr) return;
+ if (!sel) {
+ // 선택 해제 = CSS 기본 자리로 되돌린다 (인라인 제거).
+ for (const el of [rot, shr]) {
+ el.style.left = ""; el.style.top = ""; el.style.bottom = ""; el.style.marginLeft = "";
+ }
+ return;
+ }
+ const [cw, ch] = cellDims(stateName);
+ const pct = (v, span) => `${(v / span) * 100}%`;
+ rot.style.left = pct((sel.x0 + sel.x1) / 2, cw);
+ rot.style.top = `calc(${pct(sel.y0, ch)} - 18px)`;
+ rot.style.marginLeft = "-8px";
+ shr.style.left = `calc(${pct(sel.x0, cw)} - 16px)`;
+ shr.style.top = `calc(${pct(sel.y1, ch)} - 0px)`;
+ shr.style.bottom = "auto";
+}
+
+
+// 핸들 드래그의 **대상**을 영역으로 바꾼다. 선택이 없으면 아무것도 안 하고
+// `wireStage` 의 셀 전체 핸들러가 그대로 가져간다.
+// `wireStage`(zoom-editor.js:1291)보다 **먼저** 등록돼야 stopImmediatePropagation 이 먹는다.
+function wireRegionHandles(stage, stateName, idx, ctx) {
+ const { isRegionTool, hasSelection, selectionRect, afterCommit } = ctx;
+ const common = (axis) => ({
+ axis,
+ // **올가미 툴에서도 먹어야 한다.** `regionPlaceHandles` 는 툴과 무관하게 핸들을 선택
+ // 위로 옮기고 올가미는 비페인팅 툴이라 핸들이 숨지도 않는다 — 게이트만 변형 툴로
+ // 좁혀 두면 올가미 상태에서 그 핸들이 **셀 전체를 돌린다**(노을이 note 2026-07-26:
+ // `L` 한 번이면 maintainer이 겪은 증상에 다시 도달한다). "핸들 위치 = 대상" 불변식이
+ // 거짓이 되는 자리라 게이트를 선택 기준으로 맞춘다.
+ enabled: () => isRegionTool() && hasSelection(),
+ pixelsPerUnit: () => stage.clientWidth / cellDims(stateName)[0],
+ centerOf: () => {
+ const r = stage.getBoundingClientRect();
+ const [cw, ch] = cellDims(stateName);
+ const rect = selectionRect();
+ return [
+ r.left + ((rect.x + rect.w / 2) / cw) * r.width,
+ r.top + ((rect.y + rect.h / 2) / ch) * r.height,
+ ];
+ },
+ spanOf: () => [stage.clientWidth, stage.clientHeight],
+ onStart: () => {
+ const rect = selectionRect();
+ const src = regionCapture(stage, stateName, idx, rect);
+ regionEdit = { state: stateName, idx, rect, src: src || [],
+ t: { dx: 0, dy: 0, rotate: 0, shx: 0, shy: 0 }, canvas: null };
+ },
+ onDelta: (d) => {
+ if (!regionEdit) return;
+ regionEdit.t = { dx: Math.round(d.dx), dy: Math.round(d.dy),
+ rotate: d.rotate, shx: d.shx, shy: d.shy };
+ regionRenderPreview(stage, stateName);
+ },
+ onEnd: (moved) => {
+ if (!moved) { regionCancel(); return; }
+ if (regionCommit(stateName, idx) && afterCommit) afterCommit();
+ },
+ });
+ const rot = stage.querySelector(".rotate-handle");
+ const shr = stage.querySelector(".shear-handle");
+ if (rot) tpWireGesture(rot, common("rotate"));
+ if (shr) tpWireGesture(shr, common("shear"));
+}
+
+
+// 스테이지에 영역 변형 제스처를 건다. 마퀴 선택이 있고 변형 툴이 활성일 때만 먹는다.
+function wireRegionTransform(stage, stateName, idx, ctx) {
+ const { hasSelection, selectionRect, isTransformTool, afterCommit } = ctx;
+ tpWireGesture(stage, {
+ enabled: () => isTransformTool() && hasSelection(),
+ pixelsPerUnit: () => stage.clientWidth / cellDims(stateName)[0],
+ centerOf: () => {
+ const r = stage.getBoundingClientRect();
+ const [cw, ch] = cellDims(stateName);
+ const rect = selectionRect();
+ return [
+ r.left + ((rect.x + rect.w / 2) / cw) * r.width,
+ r.top + ((rect.y + rect.h / 2) / ch) * r.height,
+ ];
+ },
+ spanOf: () => [stage.clientWidth, stage.clientHeight],
+ onStart: () => {
+ const rect = selectionRect();
+ const src = regionCapture(stage, stateName, idx, rect);
+ regionEdit = { state: stateName, idx, rect, src: src || [],
+ t: { dx: 0, dy: 0, rotate: 0, shx: 0, shy: 0 }, canvas: null };
+ },
+ onDelta: (d) => {
+ if (!regionEdit) return;
+ // 이동은 정수 셀로 스냅한다 — 도트라 반 픽셀 이동은 결과가 뭉갠다.
+ regionEdit.t = { dx: Math.round(d.dx), dy: Math.round(d.dy),
+ rotate: d.rotate, shx: d.shx, shy: d.shy };
+ regionRenderPreview(stage, stateName);
+ },
+ onEnd: (moved) => {
+ if (!moved) { regionCancel(); return; }
+ if (regionCommit(stateName, idx) && afterCommit) afterCommit();
+ },
+ });
+}
diff --git a/sprite_gen/serve/curator/src/row-controls.js b/sprite_gen/serve/curator/src/row-controls.js
new file mode 100644
index 0000000..234aa52
--- /dev/null
+++ b/sprite_gen/serve/curator/src/row-controls.js
@@ -0,0 +1,129 @@
+// SPDX-License-Identifier: Apache-2.0
+// curator/row-controls.js — 줄 헤더 표시 컨트롤 팩토리 (토글/fps 스텝퍼/리롤 트리거)
+// 로드 순서 SSoT = index.html (classic script 전역 어휘 공유; 빌드 스텝 없음)
+
+// 줄별 토글 체크박스 공용 팩토리 — refs 줄과 확대 모달이 같은 클래스/핸들러를 쓰므로
+// sync*Controls 가 양쪽 인스턴스를 함께 갱신한다 (per-state truth 하나, 표시 N개).
+function makeStateToggle(cls, stateName, label, title, checked, onChange) {
+ const el = document.createElement("label");
+ el.className = "unfake-apply row-toggle";
+ el.title = title;
+ const input = document.createElement("input");
+ input.type = "checkbox";
+ input.className = cls;
+ input.dataset.state = stateName;
+ input.checked = checked;
+ input.addEventListener("change", (ev) => onChange(ev.target.checked));
+ el.appendChild(input);
+ el.appendChild(Object.assign(document.createElement("span"), { textContent: label }));
+ return el;
+}
+
+function makeGridToggle(stateName) {
+ return makeStateToggle("grid-state-check", stateName, t("pxGrid"), t("tGridState"),
+ !!gridStates[stateName], (checked) => {
+ gridStates[stateName] = checked;
+ syncGridControls();
+ sizePxGrids();
+ });
+}
+
+
+// 줄 리롤 버튼 — 같은 행을 한 번 더 생성해 **후보군에 병기** (maintainer 2026-07-19).
+// primary 를 덮지 않는다: 서버가 rerollN 테이크로 기록하고 전체 배치를 재추출한다.
+// UI 는 보간과 같은 생성 트리거 관용구(gen-trigger.js): 클릭 = 팝오버(모델 select
+// + 실행). Alt클릭 같은 트리거별 제스처는 두지 않는다.
+function makeRerollButton(stateName) {
+ const wrap = document.createElement("span");
+ wrap.className = "gen-wrap";
+ const btn = document.createElement("button");
+ btn.type = "button";
+ btn.className = "gif-btn reroll-btn";
+ btn.title = t("tRowReroll");
+ btn.innerHTML =
+ '<svg viewBox="0 0 16 16" width="12" height="12" aria-hidden="true">' +
+ '<path d="M13.5 8a5.5 5.5 0 1 1-1.6-3.9M13.5 1.8v2.7h-2.7" fill="none" ' +
+ 'stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/></svg>' +
+ `<span>${t("rowReroll")}</span>`;
+ const pop = document.createElement("div");
+ pop.className = "gen-pop";
+ pop.hidden = true;
+ const providerSel = makeProviderSelect();
+ pop.appendChild(providerSel);
+ const go = document.createElement("button");
+ go.type = "button";
+ go.className = "gif-btn";
+ go.textContent = t("genGo");
+ pop.appendChild(go);
+ btn.addEventListener("click", () => { pop.hidden = !pop.hidden; });
+ go.addEventListener("click", () => runServerGeneration({
+ url: "/api/reroll",
+ body: { state: stateName, provider: providerSel.value },
+ goBtn: go,
+ buttons: [btn],
+ busyMsg: STR[lang].rerollBusy(stateName),
+ doneMsg: STR[lang].rerollDone(stateName),
+ failPrefix: t("rerollFail"),
+ }));
+ wrap.appendChild(btn);
+ wrap.appendChild(pop);
+ return wrap;
+}
+
+function makeUnfakeToggle(stateName) {
+ return makeStateToggle("pp-state-check", stateName, t("unfakeState"), t("tUnfakeState"),
+ unfakeOn(stateName), (checked) => {
+ unfakeStates[stateName] = checked;
+ syncUnfakeControls();
+ refreshVariantImages();
+ scheduleSave();
+ });
+}
+
+
+// 줄 전체 재생 속도 (fps) 스텝퍼 — SSoT 는 sprite-request.json (서버가 원자 수정).
+// 프레임별 지속시간은 프레임 복제(아틀라스 셀 공유 = 부하 0)가 담당한다 (maintainer 확정
+// 2026-07-18 — per-frame duration 방식 폐기). 변경은 프리뷰/호흡 편집기에 즉시 반영.
+function makeFpsStepper(stateName) {
+ const st = run.states.find((s) => s.name === stateName);
+ const wrap = document.createElement("span");
+ wrap.className = "fps-stepper";
+ wrap.title = t("tFpsStepper");
+ const minus = document.createElement("button");
+ minus.type = "button";
+ minus.textContent = "−";
+ const label = document.createElement("span");
+ label.className = "fps-value";
+ label.textContent = `${(st && st.fps) || 6}fps`;
+ const plus = document.createElement("button");
+ plus.type = "button";
+ plus.textContent = "+";
+ const apply = async (next) => {
+ const clamped = Math.max(1, Math.min(30, next));
+ if (!st || clamped === st.fps) return;
+ minus.disabled = plus.disabled = true;
+ try {
+ const res = await fetch("/api/state-fps", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ state: stateName, fps: clamped }),
+ });
+ const data = await res.json();
+ if (!res.ok || !data.ok) throw new Error(data.error || res.status);
+ st.fps = clamped; // 모델 즉시 반영 — 프리뷰/에디터 틱이 이 값을 읽는다
+ label.textContent = `${clamped}fps`;
+ const meta = document.querySelector(`.state[data-state="${cssEscape(stateName)}"] .state-head .meta`);
+ if (meta) meta.textContent = meta.textContent.replace(/\d+fps/, `${clamped}fps`);
+ setStatus(STR[lang].fpsSet(stateName, clamped));
+ } catch (e) {
+ setStatus(t("fpsFail") + e.message, "err");
+ }
+ minus.disabled = plus.disabled = false;
+ };
+ minus.addEventListener("click", () => apply(((st && st.fps) || 6) - 1));
+ plus.addEventListener("click", () => apply(((st && st.fps) || 6) + 1));
+ wrap.appendChild(minus);
+ wrap.appendChild(label);
+ wrap.appendChild(plus);
+ return wrap;
+}
diff --git a/sprite_gen/serve/curator/src/row-export.js b/sprite_gen/serve/curator/src/row-export.js
new file mode 100644
index 0000000..5fc083e
--- /dev/null
+++ b/sprite_gen/serve/curator/src/row-export.js
@@ -0,0 +1,125 @@
+// SPDX-License-Identifier: Apache-2.0
+// curator/row-export.js — 줄 단위 내보내기 (저장 팝오버: GIF 서버 굽기 / WebM·MP4 클라 샘플)
+// 로드 순서 SSoT = index.html (classic script 전역 어휘 공유; 빌드 스텝 없음)
+//
+// row-controls.js(표시 토글/스텝퍼 팩토리)에서 분리 — 내보내기는 별개 관심사 (SRP,
+// 2026-07-19 텍소노미 정리). 서버측 생성 트리거는 gen-trigger.js, 여기는 다운로드만.
+
+// 줄 단위 저장 — 공용 저장 팝오버 (maintainer 2026-07-19 "row 저장버튼도 공용저장버튼으로"):
+// GIF = 서버 굽기(실시간 계약: 보는 것 = 받는 것, 4x 니어리스트), WebM(투명)/MP4(흰
+// 배경) = 비교뷰와 같은 클라 결정론 샘플 → /api/compare-gif 서버 조립.
+function makeGifButton(stateName) {
+ const wrap = document.createElement("span");
+ wrap.className = "dl-wrap row-dl-wrap";
+ const btn = document.createElement("button");
+ btn.type = "button";
+ btn.className = "gif-btn";
+ btn.title = t("tRowDl");
+ btn.innerHTML =
+ '<svg viewBox="0 0 16 16" width="12" height="12" aria-hidden="true">' +
+ '<path d="M8 2v8m0 0l-3-3m3 3l3-3M3 13h10" fill="none" stroke="currentColor" ' +
+ 'stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/></svg>' +
+ `<span>${t("cmpDl")} ▾</span>`;
+ const menu = document.createElement("div");
+ menu.className = "dl-menu";
+ menu.hidden = true;
+ menu.innerHTML =
+ `<button type="button" data-fmt="gif">GIF</button>` +
+ `<button type="button" data-fmt="webm">WebM · ${t("cmpDlAlpha")}</button>` +
+ `<button type="button" data-fmt="mp4">MP4 · ${t("cmpDlWhite")}</button>`;
+ btn.addEventListener("click", (ev) => {
+ ev.stopPropagation();
+ menu.hidden = !menu.hidden;
+ });
+ document.addEventListener("click", () => { menu.hidden = true; });
+ const download = async (fmt) => {
+ btn.disabled = true;
+ try {
+ if (fmt === "gif") {
+ await downloadArtifact(`gif?state=${encodeURIComponent(stateName)}`,
+ STR[lang].rowGifDone(stateName));
+ } else {
+ await downloadRowVideo(stateName, fmt);
+ setStatus(STR[lang].rowDlDone(stateName, fmt), "ok");
+ }
+ } catch (e) {
+ setStatus(t("exportFail") + e.message, "err");
+ } finally {
+ btn.disabled = false;
+ }
+ };
+ menu.querySelectorAll("button[data-fmt]").forEach((b) =>
+ b.addEventListener("click", (ev) => {
+ ev.stopPropagation();
+ menu.hidden = true;
+ download(b.dataset.fmt);
+ }));
+ wrap.appendChild(btn);
+ wrap.appendChild(menu);
+ return wrap;
+}
+
+// WebM/MP4 = 줄 재생 루프 1회를 클라에서 결정론 합성(캐노니컬+변형+픽셀편집+호흡,
+// 4x 니어리스트)해 서버(ffmpeg)가 조립한다 — 비교뷰 다운로드와 같은 경로.
+async function downloadRowVideo(stateName, fmt) {
+ const play = playList(stateName);
+ if (!play.length) throw new Error("empty sequence");
+ const st = run.states.find((s) => s.name === stateName);
+ const [cellW, cellH] = cellDims(stateName);
+ const bcfg = stateBreathe(stateName);
+ const pattern = bcfg ? breathePattern(bcfg, play.length) : [];
+ const scale = 4;
+ const frames = [];
+ for (let i = 0; i < play.length; i++) {
+ const f = frameOf(stateName, play[i]);
+ // 굽기는 `frame_variant` 로 해소한 변형(pp OFF 면 .plain)에서 굽는다 — 미러도 같은
+ // 변형에서 그려야 지문이 맞고 그림도 같다. 캐노니컬(`f.url`)로 그리면 지문이
+ // **영구 불일치**라 그 줄의 영상 내보내기가 계속 막힌다 (validator 실측 2026-07-26).
+ const bakeSrc = f && bakeFrameUrl(stateName, f);
+ const image = bakeSrc ? img(bakeSrc) : null;
+ if (!(image && image.complete && image.naturalWidth)) throw new Error("frame images still loading");
+ const base = document.createElement("canvas");
+ base.width = cellW;
+ base.height = cellH;
+ const bx = base.getContext("2d");
+ bx.imageSmoothingEnabled = false;
+ drawFrameInto(bx, image, getTransform(stateName, play[i]), cellW, cellH,
+ snapScaleFor(stateName), getPixelOps(stateName, play[i]));
+ // 줄의 첫 프레임 = 굽기의 기준 프레임. 얼린 해부가 그 프레임에서 나온 게 아니면
+ // 여기서 멈춘다 — 안 그러면 GIF(서버 굽기)와 다른 애니메이션이 파일로 나간다.
+ if (bcfg && i === 0) {
+ breatheAssertFresh(breatheReferenceKey(stateName), bcfg);
+ // 고칠 수 없는 차이라도 관측 가능해야 한다 (원칙 6) — 아래 `breatheResamplesDifferently`.
+ if (breatheResamplesDifferently(stateName)) {
+ setStatus(STR[lang].breatheResample(stateName), "warn");
+ }
+ }
+ const composed = bcfg ? breatheComposite(base, bcfg, pattern[i] || 0) : base;
+ const out = document.createElement("canvas");
+ out.width = cellW * scale;
+ out.height = cellH * scale;
+ const ox = out.getContext("2d");
+ ox.imageSmoothingEnabled = false;
+ ox.drawImage(composed, 0, 0, out.width, out.height);
+ frames.push(out.toDataURL("image/png"));
+ }
+ const res = await fetch("/api/compare-gif", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ frames,
+ duration_ms: Math.round(1000 / Math.max(1, (st && st.fps) || 6)),
+ format: fmt,
+ }),
+ });
+ if (!res.ok) {
+ const data = await res.json().catch(() => ({}));
+ throw new Error(data.error || res.status);
+ }
+ const blob = await res.blob();
+ const link = document.createElement("a");
+ link.href = URL.createObjectURL(blob);
+ link.download = `${run.characterId || "row"}-${stateName}.${fmt}`;
+ link.click();
+ URL.revokeObjectURL(link.href);
+}
diff --git a/sprite_gen/serve/curator/src/status.js b/sprite_gen/serve/curator/src/status.js
new file mode 100644
index 0000000..5689458
--- /dev/null
+++ b/sprite_gen/serve/curator/src/status.js
@@ -0,0 +1,10 @@
+// SPDX-License-Identifier: Apache-2.0
+// curator/status.js — 상태줄 표시
+// 로드 순서 SSoT = index.html (classic script 전역 어휘 공유; 빌드 스텝 없음)
+
+const statusEl = document.getElementById("status");
+
+function setStatus(text, kind = "") {
+ statusEl.textContent = text;
+ statusEl.className = "status" + (kind ? " " + kind : "");
+}
diff --git a/sprite_gen/serve/curator/src/store.js b/sprite_gen/serve/curator/src/store.js
new file mode 100644
index 0000000..086469f
--- /dev/null
+++ b/sprite_gen/serve/curator/src/store.js
@@ -0,0 +1,633 @@
+// 폐기된 호흡 사이드카 키 (파이썬 curation.RETIRED_BREATHE_KEYS 미러 — 둘이 갈리면
+// 한쪽만 보존하게 되므로 같이 고친다).
+const RETIRED_BREATHE_KEYS = ["splits", "amplitude", "subpixel", "hold"];
+
+// 파이썬 curation 의 허용 범위 미러. 굽기가 요란하게 거부하는 값을 웹뷰가 조용히 깎아
+// 되쓰면 사용자의 원래 숫자가 파괴되고 게이트 자체가 사라진다 — 같은 값으로 판정한다.
+// 파이썬 `float(v)` 가 받는 모양인가 — 수, 또는 수로만 이루어진 문자열.
+// `""`·`[]`·`{}`·`true` 는 JS `Number()` 가 조용히 0/1 로 바꾸지만 파이썬은 거부한다.
+function isNumericScalar(v) {
+ if (typeof v === "number") return Number.isFinite(v);
+ return typeof v === "string" && /^\s*[-+]?(\d+\.?\d*|\.\d+)([eE][-+]?\d+)?\s*$/.test(v);
+}
+
+function breatheRangeProblems(raw) {
+ const bounds = [["depth", 0.005, 0.20, 0.06], ["breaths", 1, 8, 1], ["lag", 0, 0.45, 0.1]];
+ const bad = [];
+ for (const [key, lo, hi, dflt] of bounds) {
+ // 생략(undefined)은 기본값. 명시적 null 은 굽기가 `float(None)` 으로 거부하므로
+ // **키와 무관하게** 여기서도 문제로 본다 — `Number(null) = 0` 이라 하한이 0 인 `lag`
+ // 만 범위 검사를 통과해 빠져나갔다 (validator 실측 2026-07-26: 원본이 0.1 로 덮였다).
+ const given = raw[key];
+ if (given === null) { bad.push(`${key}=null`); continue; }
+ // `Number("")`·`Number([])` 는 **0** 이다 — 값이 있는지만 보고 `Number()` 로 넘기면
+ // 하한이 0 인 `lag` 가 통과해 첫 autosave 가 사용자 값을 0 으로 덮는다(알림 0건).
+ // 파이썬은 `float("")`/`float([])` 이 터져 거부하는 값들이라 여기서도 거부한다.
+ if (given !== undefined && !isNumericScalar(given)) {
+ bad.push(`${key}=${JSON.stringify(given)} (수가 아님)`);
+ continue;
+ }
+ const v = given === undefined ? dflt : Number(given);
+ if (!Number.isFinite(v) || v < lo || v > hi) { bad.push(`${key}=${JSON.stringify(raw[key])}`); continue; }
+ // 정수여야 하는 값은 **정수인지도** 본다. `Math.round` 로 조용히 반올림하면 굽기
+ // (`_exact_int` 가 거부)와 갈리고, 첫 autosave 가 사이드카를 반올림값으로 덮어써
+ // loud reject 자체가 사라진다 (validator 실측 2026-07-25: breaths 2.7 → 굽기 2 vs 프리뷰 3).
+ if (key === "breaths" && !Number.isInteger(v)) bad.push(`${key}=${JSON.stringify(raw[key])} (정수 아님)`);
+ }
+ // 가로 독립 진폭 (2026-07-30 가로/세로 분리): null = depth 따름이 정당한 상태라
+ // depth 와 달리 명시적 null 을 허용하고, 0(가로 끄기)도 유효하다 — 파이썬 state_breathe 미러.
+ if (raw.depth_x != null) {
+ if (!isNumericScalar(raw.depth_x)) {
+ bad.push(`depth_x=${JSON.stringify(raw.depth_x)} (수가 아님)`);
+ } else {
+ const dx = Number(raw.depth_x);
+ if (!Number.isFinite(dx) || dx < 0 || dx > 0.20) bad.push(`depth_x=${JSON.stringify(raw.depth_x)}`);
+ }
+ }
+ if (raw.rigid_row != null) {
+ // `Number("")` 과 `Number([])` 는 **0** 이라 정수 검사만 하면 통과한다 — 그러면 첫
+ // autosave 가 사용자 사이드카를 0 으로 덮고 굽기의 loud reject 근거가 사라진다
+ // (validator 실측 2026-07-26: 알림 0건). 파이썬은 `float("")` 이 터져 거부하는 값들이다.
+ const raw_r = raw.rigid_row;
+ const numeric = isNumericScalar(raw_r);
+ const r = Number(raw_r);
+ if (!numeric || !Number.isInteger(r)) {
+ bad.push(`rigid_row=${JSON.stringify(raw_r)} (정수 아님)`);
+ } else if (r < 1) {
+ // `analyze` 가 `0 < rigid_row < height` 를 loud fail 한다. 상한은 해부 없이 모르므로
+ // 여기서 아는 하한만 본다 — 모르는 것을 아는 척하지 않는다.
+ bad.push(`rigid_row=${JSON.stringify(raw_r)} (1 이상이어야 한다)`);
+ }
+ }
+ return bad;
+}
+
+// SPDX-License-Identifier: Apache-2.0
+// curator/store.js — 런 스냅샷 + 큐레이션 인메모리 모델 (run/entries/프레임·복제 해석) — 클라이언트 상태 SSoT
+// 로드 순서 SSoT = index.html (classic script 전역 어휘 공유; 빌드 스텝 없음)
+
+let run = null; // /api/run snapshot
+
+let entries = {}; // { stateName: { order: [idx], sel: Set<idx>, transforms: { idx: {..} } } }
+
+const imageCache = new Map();
+
+const previews = {}; // stateName -> { playing, speed, cursor } preview transport state
+
+// --- pixel-unfake variant (fit.pixel_unfake runs save a .plain.png twin) --
+// Per-STATE toggles: each row with a twin gets its own on/off (what that row
+// displays AND bakes, persisted as curation.json states.<state>.pixel_unfake).
+// The header checkbox is a toggle-ALL over the same per-state truth.
+let unfakeTwinStates = new Set(); // states that actually saved a twin
+
+let unfakeStates = {}; // stateName -> bool (true = pixel-unfake variant)
+
+// Same per-state + toggle-all shape as pixel-unfake: each grid-capable row has
+// its own checkbox, the header checkbox sets all rows at once.
+
+let gridStates = {}; // stateName -> bool (overlay shown)
+
+let anchorStates = new Set(); // direction-anchor states (directionGroups runs)
+
+// ── 방향 앵커 프레임 (maintainer 2026-07-25) ──────────────────────────────────────
+// 앵커 = 그 방향의 identity 로 생성에 붙는 **단 한 장**. 지정(curation.json anchors)이
+// 있으면 그것, 없으면 앵커 행의 시퀀스 첫 프레임 (엔진 sprite_gen/anchor.py 와 같은 규칙).
+// 배지는 **클라가 직접 해석**한다 — 지금 편집 중인 상태(삭제·재정렬·지정)에서 "저장하면
+// 무엇이 앵커가 되는가" 를 보여야 하므로, 디스크 스냅샷(run.directionGroups[].anchorFrame)
+// 을 그대로 쓰면 한 박자 늦는다. 디스크 값은 칩 라벨/오류 표시에만 쓴다.
+let anchorPicks = {}; // direction -> {state, index} (사용자 지정)
+
+let anchorDirections = []; // 생성 방향 목록 (미러 방향 제외)
+
+function directionOfState(stateName) {
+ for (const d of anchorDirections) {
+ if (stateName === d || stateName.startsWith(d + "_")) return d;
+ }
+ return null;
+}
+
+function anchorRowOf(direction) {
+ const g = (run.directionGroups || []).find((x) => x.direction === direction && !x.mirrorOf);
+ return (g && g.anchor) || null;
+}
+
+// 그 방향의 기본 앵커 인스턴스 = 앵커 행의 시퀀스 첫 프레임 (index 0 이 아니다 —
+// 앞 프레임을 삭제/재정렬했으면 index 0 은 기각분이다).
+function defaultAnchorFrame(direction) {
+ const row = anchorRowOf(direction);
+ if (!row || !entries[row]) return null;
+ const play = playList(row);
+ return play.length ? { state: row, index: play[0], source: "default" } : null;
+}
+
+function resolvedAnchorFrame(direction) {
+ const pick = anchorPicks[direction];
+ if (pick) return { ...pick, source: "picked" };
+ return defaultAnchorFrame(direction);
+}
+
+function isAnchorFrame(stateName, idx) {
+ const d = directionOfState(stateName);
+ if (!d) return false;
+ const a = resolvedAnchorFrame(d);
+ return !!a && a.state === stateName && a.index === idx;
+}
+
+// 명시 지정된(고정된) 앵커인가 — 배지는 "지금 앵커인가"(isAnchorFrame), 버튼의 토글
+// 방향은 "고정돼 있나"(이것)로 갈린다. 기본값 앵커도 눌러서 고정할 수 있어야 한다.
+function isPinnedAnchorFrame(stateName, idx) {
+ const d = directionOfState(stateName);
+ const p = d && anchorPicks[d];
+ return !!p && p.state === stateName && p.index === idx;
+}
+
+// 낡은 핀(재생성된 행 / 증명 없는 핀) — 그 프레임을 다시 누르면 재지정으로 풀린다.
+function isStaleAnchorFrame(stateName, idx) {
+ const d = directionOfState(stateName);
+ const p = d && anchorPicks[d];
+ return !!p && !!p.stale && p.state === stateName && p.index === idx;
+}
+
+function anchorFrameLabel(direction) {
+ const a = resolvedAnchorFrame(direction);
+ return a ? `${a.state}#${a.index}` : "—";
+}
+
+let anchorCacheBust = 0; // 칩(라이브 베이크) 표시 캐시 무효화 — 지정이 바뀔 때만 증가
+
+// 지정/해제. 앵커 칩은 서버가 **디스크의 curation.json** 에서 굽기 때문에, 저장을
+// 먼저 밀어낸 뒤에 다시 그린다 (디바운스 250ms 를 기다리면 한 박자 옛 앵커가 보인다).
+async function setAnchorFrame(stateName, idx) {
+ const direction = directionOfState(stateName);
+ if (!direction) return;
+ // 토글 축은 **명시 지정 여부**다 (기본값으로 앵커인가가 아니다): 지정된 그 프레임을
+ // 다시 누르면 해제, 그 외에는(기본값으로 이미 앵커인 프레임 포함) 명시 지정. 기본값
+ // 앵커를 눌러도 무반응이면 "지금 이 프레임을 고정해서 재정렬·삭제에도 안 움직이게"
+ // 를 뷰에서 할 방법이 없다 (validator 검증 2026-07-25 범위 밖 note 1 — CLI 로만 가능했다).
+ const pinned = anchorPicks[direction];
+ if (pinned && pinned.state === stateName && pinned.index === idx) {
+ if (pinned.stale) {
+ // 낡은(증명 안 되는) 핀을 그 프레임에서 다시 누른 것 = **명시 재지정**. 지문을 새로
+ // 받아야 오류가 풀린다 — 저장 경로가 조용히 유효화하지 않는 게 계약이라(fail-safe),
+ // 푸는 길은 이 명시 의도뿐이다.
+ anchorPicks[direction] = { state: stateName, index: idx, repin: true };
+ } else {
+ delete anchorPicks[direction];
+ }
+ } else {
+ anchorPicks[direction] = { state: stateName, index: idx };
+ }
+ scheduleSave();
+ await flushSave(); // 저장이 카운터를 올리고 칩을 다시 받아온다 (persistence.save)
+ const group = (run.directionGroups || []).find((g) => g.direction === direction && !g.mirrorOf);
+ for (const name of (group ? group.states : [stateName])) {
+ if (entries[name]) rebuildState(name);
+ }
+ if (typeof renderPipelineTree === "function") renderPipelineTree(); // 트리 앵커 노드도 같은 진실
+ const label = anchorFrameLabel(direction);
+ setStatus(anchorPicks[direction] ? STR[lang].anchorPinned(direction, label)
+ : STR[lang].anchorUnpinned(direction, label), "ok");
+}
+
+let pixelEdit = null; // 모달 편집 세션: {state, idx, tool: 'pen'|'eraser', color, journal: []}
+
+// 편집 truth 인덱스 (maintainer 확정 2026-07-18): 링크된 복제의 편집 SSoT 는 원본
+// 프레임 하나다 — 복제는 재생 슬롯일 뿐. '링크 끊기' 한 복제(unlinked)만 자기
+// 편집을 소유한다. 모든 편집 읽기/쓰기는 이 리졸버를 거친다.
+function editIndex(stateName, idx) {
+ const e = entries[stateName];
+ const src = e && e.clones ? e.clones[idx] : undefined;
+ if (src === undefined) return idx;
+ return e.unlinked && e.unlinked.has(idx) ? idx : src;
+}
+
+function isLinkedClone(stateName, idx) {
+ const e = entries[stateName];
+ return !!(e && e.clones && e.clones[idx] !== undefined && !(e.unlinked && e.unlinked.has(idx)));
+}
+
+function getPixelOps(stateName, idx) {
+ const e = entries[stateName];
+ if (!e || !e.pixels) return null;
+ const ops = e.pixels[editIndex(stateName, idx)];
+ return ops && Object.keys(ops).length ? ops : null;
+}
+
+function unfakeOn(stateName) {
+ return unfakeStates[stateName] !== false;
+}
+
+// 소스 선택은 엔진이 구운 파일 사이에서만 갈린다 (트윈 = 추출이 만든 진실).
+// 트윈 없는 프레임의 퍼펙은 파일 변형이 아니라 표시 렌더러의 양자화 모드다
+// (snapScaleFor 의 측정 k) — 구 서버 추정 스냅 프리뷰 레거시는
+// 표시 격자와 다른 검출기로 스냅해 "격자 기준 퍼펙" 을 깨뜨려서 폐기했다
+// (maintainer 2026-07-24, plan curator-single-display-pipeline).
+function frameUrl(stateName, frame) {
+ if (frame.plainUrl) return !unfakeOn(stateName) ? frame.plainUrl : frame.url;
+ return frame.url;
+}
+
+// **굽기가 읽는 파일** — 파이썬 `frame_variant` + `row_frame_rel` 미러.
+// `frameUrl` 은 표시용이라 pp OFF 에서 `orig/` 고해상본(굽기가 안 읽는 파일)을 줄 수
+// 있다. 호흡은 굽기와 같은 그림을 내야 하므로 워프 base 도 신선도 기준도 이걸 쓴다 —
+// 안 그러면 지문이 영구 불일치라 영상 내보내기가 영구 차단된다 (validator 2026-07-26).
+// 퍼펙 토글 시드 — 첫 렌더 전에 해소돼야 한다 (`frameUrl` 이 읽는다).
+// boot 에 인라인돼 있던 것을 여기로 옮겼다: 이 시드가 `bakeVariant` 의 입력이라,
+// 그물이 `unfakeStates` 를 손으로 먹이면 "웹뷰가 서버와 같은 변종을 **스스로** 골라내는가"
+// 를 영영 못 묻는다 — 그 공백으로 변종 불일치가 한 라운드를 살아남았다
+// (validator 실측 2026-07-26).
+//
+// 퍼펙 토글은 **모든 줄**이 가진다 — 트윈 줄은 소스 전환(canonical↔orig), 트윈 없는
+// 줄은 측정 k 양자화 렌즈(snapScaleFor). "가능한 줄" 게이팅은 격자 게이팅과 같은
+// 병이었다 (maintainer 2026-07-24: 확대화면에 퍼펙 버튼이 없다 — 조건 분기 = 버그).
+function seedUnfakeState(snapshot) {
+ unfakeTwinStates = new Set(
+ snapshot.states.filter((s) => s.frames.some((f) => f.plainUrl)).map((s) => s.name));
+ const unfakeDefault = !(snapshot.curation && snapshot.curation.pixel_unfake === false);
+ unfakeStates = {};
+ for (const s of snapshot.states) {
+ const c = snapshot.curation && snapshot.curation.states && snapshot.curation.states[s.name];
+ // 트윈 없는 줄 기본 OFF (원본 먼저 — 양자화 렌즈는 사용자가 눌러서 본다).
+ // 이건 **표시 렌즈 기본값**이고 굽기 변종이 아니다 (아래 `bakeVariant`).
+ const fallback = unfakeTwinStates.has(s.name) ? unfakeDefault : false;
+ unfakeStates[s.name] = c && typeof c.pixel_unfake === "boolean" ? c.pixel_unfake : fallback;
+ }
+}
+
+// ── 굽기 변종 (표시 렌즈와 **다른 개념**) ───────────────────────────
+//
+// `unfakeOn` 은 **표시 렌즈**다: 트윈 없는 줄은 boot 시드가 기본 OFF 로 놓는다(원본 먼저,
+// 양자화 렌즈는 눌러서 본다). 그런데 그 값은 사이드카에 **저장되지 않으므로**
+// (persistence: 트윈 줄만 기록) 서버 `frame_variant` 는 그 줄을 `pixel` 로 본다.
+//
+// 이 둘을 같은 값으로 쓰면 기본 런(= `fit.pixel_unfake` 없는 런, `orig/`·`.plain.png`
+// 가 하나도 없다) 전부에서 웹뷰는 `plain`, 서버는 `pixel` 로 키를 지어 지문이 **영구
+// 불일치**가 된다 — 프리뷰가 영원히 원본으로 떨어지고 영상 내보내기가 영구 차단되며,
+// 안내대로 해부를 갱신해도 라우트가 또 `pixel` 로 같은 키를 만들어 안 풀린다
+// (validator 실측 2026-07-26).
+//
+// 그래서 굽기 변종은 **저장되는 값**으로만 해소한다 — 파이썬 `curation.frame_variant`
+// 미러(per-state bool > 런 전역 > pixel).
+
+// **뷰가 authoring 하는** per-state `pixel_unfake` (안 하면 undefined). persistence 전용.
+//
+// 트윈 없는 줄의 퍼펙은 표시 렌즈(측정 k 양자화)라 사이드카에 새로 적지 않는다 — 적으면
+// 굽기 리졸버가 존재하지 않는 `.plain` 변형을 요구한다.
+function authoredUnfake(stateName) {
+ return unfakeTwinStates.has(stateName) ? unfakeOn(stateName) : undefined;
+}
+
+// **사이드카에 남게 되는** per-state `pixel_unfake` — 굽기 변종 해소의 입력.
+//
+// 이걸 `authoredUnfake` 와 같은 값으로 쓰면 안 된다. 파이썬 `frame_variant` 의
+// per-state 분기는 **무조건**이라(선언이 bool 이면 즉시 확정) 트윈 없는 줄에 선언이 있어도
+// 그 값이 이긴다. 트윈 존재로 게이트하면 18칸 해소표 중 3칸이 갈리고, 그 줄은 웹뷰가
+// `plain` 을 골라 키를 못 만들어 **프리뷰·영상 내보내기가 영구 거부**된다 — 굽기는 멀쩡히
+// `pixel` 로 구우면서 (validator 실측 2026-07-26).
+//
+// 뷰가 authoring 하지 않는 줄의 선언은 서버가 이월하므로(`view_conditional`) 로드된 값이
+// 그대로 사이드카의 진실이다.
+function sidecarUnfake(stateName) {
+ const authored = authoredUnfake(stateName);
+ if (authored !== undefined) return authored;
+ const c = run && run.curation && run.curation.states
+ ? run.curation.states[stateName] : undefined;
+ return c && typeof c.pixel_unfake === "boolean" ? c.pixel_unfake : undefined;
+}
+
+// 사이드카의 런 전역 `pixel_unfake`. 뷰는 **트윈 줄이 전부 같을 때만** 이 필드를
+// authoring 한다(혼합/트윈 없음이면 생략). 생략은 삭제가 아니라 "안 건드림" 이고
+// 서버가 기존 값을 이월하므로, 여기서도 로드된 값이 그대로 진실이다 — 그러지 않으면
+// 트윈 없는 줄에서 서버는 `plain`, 웹뷰는 `pixel` 로 갈린다 (해소표 전수에서 발견).
+function savedRunUnfake() {
+ if (unfakeTwinStates.size) {
+ const vals = [...unfakeTwinStates].map((n) => unfakeOn(n));
+ if (vals.every((v) => v === vals[0])) return vals[0];
+ }
+ const loaded = run && run.curation ? run.curation.pixel_unfake : undefined;
+ return typeof loaded === "boolean" ? loaded : undefined;
+}
+
+// 굽기가 읽는 변종 — 파이썬 `curation.frame_variant` 미러.
+function bakeVariant(stateName) {
+ const own = sidecarUnfake(stateName);
+ if (typeof own === "boolean") return own ? "pixel" : "plain";
+ const wide = savedRunUnfake();
+ if (typeof wide === "boolean") return wide ? "pixel" : "plain";
+ return "pixel";
+}
+
+// URL 과 파일 스탬프를 **한 자리에서** 고른다. 둘을 따로 고르면 "어느 변종을 골랐나" 가
+// 갈릴 수 있고, 그러면 호흡 기준 프레임 키가 굽기와 다른 파일을 가리킨다.
+function bakeFrame(stateName, frame) {
+ if (bakeVariant(stateName) === "plain") {
+ // 변종이 plain 인데 트윈 파일이 없으면 **없는 파일을 가리키는 것**이다. 캐노니컬로
+ // 조용히 떨어지면 굽기(그 파일을 못 찾아 실패)와 웹뷰가 다른 진실을 갖는다.
+ return { url: frame.plainBakeUrl || null, stamp: frame.plainBakeStamp || null };
+ }
+ return { url: frame.url, stamp: frame.stamp || null };
+}
+
+function bakeFrameUrl(stateName, frame) {
+ return bakeFrame(stateName, frame).url;
+}
+
+// 호흡 경계선(rigid_row)을 재고 그릴 프레임 — **굽기가 해부를 확정하는 기준 프레임**.
+//
+// `rigid_row` 는 그 프레임의 콘텐츠 행 인덱스라, 모달이 열린 프레임을 재면 선의 화면
+// 위치와 저장되는 행 번호가 굽기와 어긋난다 (골든 픽스처에서 8px = 50px 캐릭터의 16%,
+// validator 실측 2026-07-26). 선택을 **한 함수로** 모아 둔다: 재는 자리와 그 재시도가
+// 각자 고르면 한쪽만 고쳐도 조용히 갈린다 — round-10 이 정확히 그 모양이었다.
+function breatheGeometryFrame(stateName, fallbackIdx) {
+ const play0 = playList(stateName)[0];
+ const index = play0 === undefined ? fallbackIdx : play0;
+ const frame = frameOf(stateName, index);
+ return { index, frame, url: frame ? bakeFrameUrl(stateName, frame) : null };
+}
+
+// 이 줄의 기준 프레임에 **정수 이동이 아닌** 변형이 걸려 있나.
+//
+// 굽기는 `apply_transform` 에서 BICUBIC 으로 리샘플하고(`snap_scale` 없는 런 = 기본 런
+// 전부) 이 웹뷰는 `imageSmoothingEnabled=false` 캔버스, 즉 NEAREST 다. 회전·확대가
+// 걸리면 같은 입력에도 두 쪽 그림이 다르다 (실측: rotate 3° 에서 12/12 위상 최대
+// 1803px 상이). 원인은 표시 파이프라인이라 호흡이 고칠 수 있는 게 아니지만, `row-export`
+// 와 비교뷰는 **이 캔버스로 파일을 굽는다** — 조용히 두면 사용자는 GIF 와 다른 파일을
+// 받고도 모른다 (원칙 6). 고치지 못하는 차이라도 말은 해야 한다.
+function breatheResamplesDifferently(stateName) {
+ const play = playList(stateName);
+ if (!play.length) return false;
+ const t = (entries[stateName].transforms || {})[editIndex(stateName, play[0])];
+ if (!t) return false;
+ return Number(t.rotate || 0) !== 0 || Number(t.scale || 1) !== 1
+ || Number(t.shx || 0) !== 0 || Number(t.shy || 0) !== 0;
+}
+
+// 파이썬 `breathe.reference_key` 의 재료를 사이드카에서 모은다 — **줄의 기준 프레임**
+// (`playList[0]`, 굽기의 `images[0]`) 하나에 대해서만.
+//
+// 픽셀을 안 읽는다: 굽기는 BICUBIC 으로 리샘플하고 캔버스는 NEAREST 라 결과 픽셀은
+// 구조적으로 다르다. 여기 들어가는 값은 전부 사이드카(사람의 의도)와 서버가 준 스탬프다.
+// 재료가 하나라도 없으면 **null 을 돌려 거부시킨다** — 없는 값을 기본값으로 메우면
+// 서로 다른 프레임이 같은 키를 갖는다.
+function breatheReferenceKey(stateName) {
+ const e = entries[stateName];
+ if (!e || !run || !run.requestStamp) return null;
+ const play = playList(stateName);
+ if (!play.length) return null;
+ const idx = play[0];
+ const frame = frameOf(stateName, idx);
+ if (!frame) return null;
+ const stamp = bakeFrame(stateName, frame).stamp;
+ if (!stamp) return null;
+ const src = cloneSrc(stateName, idx);
+ const editIdx = editIndex(stateName, idx);
+ const t = e.transforms ? e.transforms[editIdx] : null;
+ return breatheReferenceKeyOf({
+ state: stateName,
+ variant: bakeVariant(stateName),
+ requestStamp: run.requestStamp,
+ sourceIndex: src === null ? idx : src,
+ sourceStamp: stamp,
+ pixelOps: getPixelOps(stateName, idx),
+ transform: t,
+ });
+}
+
+// 복제 인스턴스 (entries[state].clones = {복제idx: 원본idx}) 인식 프레임 조회.
+// 복제 카드는 원본의 frame 객체(이미지 URL/크기)를 빌리되 자기 인덱스로 표시된다.
+// 서버/스키마 계약: 파일은 원본을 읽고, 변형/픽셀편집/순서는 복제 인덱스 소유.
+// 프레임의 유니크 표시명: 테이크 라벨(blink#2) 우선, 없으면 #인덱스.
+// 라벨은 원본(primary) 프레임에선 비어 있어 유니크하지 않지만, 인덱스는 줄 안에서
+// 항상 유니크하므로 이 조합이 카드 표시명의 SSoT 다 (복제 배지도 이걸 가리킨다).
+function frameDisplayName(stateName, idx) {
+ const st = run.states.find((s) => s.name === stateName);
+ const f = st && st.frames.find((x) => x.index === idx && x.clone === undefined);
+ return f && f.label ? f.label : `#${idx}`;
+}
+
+function cloneSrc(stateName, idx) {
+ const e = entries[stateName];
+ const src = e && e.clones ? e.clones[idx] : undefined;
+ return src === undefined ? null : src;
+}
+
+function frameOf(stateName, idx) {
+ if (stateName === BASE_STATE) {
+ if (!baseView) return null;
+ return { index: 0, present: true, url: baseView.url, plainUrl: baseView.rawUrl,
+ label: "base", contentSize: [baseView.cols, baseView.rows] };
+ }
+ const st = run.states.find((s) => s.name === stateName);
+ if (!st) return null;
+ const src = cloneSrc(stateName, idx);
+ const f = st.frames.find((fr) => fr.index === (src === null ? idx : src));
+ if (!f) return null;
+ if (src === null) return f;
+ return { ...f, index: idx, clone: src, label: null };
+}
+
+// 퍼펙 표시 중인 줄의 양자화 격자 스케일 (퍼펙 OFF 면 null). 격자 진실은 하나다:
+// - pp 런: 계약 scale — 굽기(curation.pixel_snap_scale)와 거울. 프리뷰가 굽기를 따른다.
+// - 그 외(임포트 등): **측정 k(`st.pixelScale`)** — 격자 오버레이가 그리는 바로 그 값.
+// 격자가 쳐지면 그 격자 기준으로 퍼펙이 된다 (maintainer 2026-07-24). k=1 은 항등.
+// 이건 표시 렌즈다 — 임포트 런 굽기는 양자화가 없으므로 사이드카에 저장하지
+// 않는다 (persistence 의 트윈-줄 한정 저장이 그 계약이다).
+function snapScaleFor(stateName) {
+ // unfakeOn 검사가 **모든 분기보다 먼저**다 — 베이스를 먼저 항등 처리하면 pp OFF 의
+ // 원본(raw) 뷰가 죽는다 (validator 기각 2026-07-24: 퍼펙 체크박스가 아무것도 안
+ // 바꾸는 "거짓말하는 컨트롤"이 됐다). 베이스 pp OFF = 소스 모드로 raw 를 그린다.
+ if (!unfakeOn(stateName)) return null;
+ if (stateName === BASE_STATE) return 1; // 베이스 pp ON = 논리 양자화 뷰 (캔버스 1:1)
+ if (run.fitPixelUnfake && run.pixelUnfake && run.pixelUnfake.scale) return run.pixelUnfake.scale;
+ const st = run.states.find((s) => s.name === stateName);
+ return (st && st.pixelScale) || 1;
+}
+
+function isIdentityTransform(t) {
+ return !t.rotate && t.scale === 1 && !t.dx && !t.dy && !t.shx && !t.shy && !t.flipX;
+}
+
+function img(url) {
+ if (!imageCache.has(url)) {
+ const i = new Image();
+ i.src = url;
+ imageCache.set(url, i);
+ }
+ return imageCache.get(url);
+}
+
+function getTransform(stateName, idx) {
+ const t = entries[stateName].transforms;
+ const key = editIndex(stateName, idx); // 링크 복제 = 원본 truth 공유 (쓰기도 이 객체로)
+ if (!t[key]) t[key] = IDENTITY();
+ return t[key];
+}
+
+// selected := the frame is in the sequence row (top). Moving a card between the
+// sequence and pool rows (drag or click) is what flips this; see moveCardToOtherZone.
+function isSelected(stateName, idx) {
+ return entries[stateName].sel.has(idx);
+}
+
+// play sequence = display order filtered to selected frames.
+// This is exactly what gets persisted as curation.json `selected`, which
+// compose_sprite_atlas.py lays out left-to-right in this order.
+function playList(stateName) {
+ const e = entries[stateName];
+ return e.order.filter((idx) => e.sel.has(idx));
+}
+
+// ── 베이스 = 줌 모달과 같은 컴포넌트 (maintainer 지시 2026-07-17 "같은 컴포넌트를 쓰라") ──
+// 가상 상태 "__base__" 로 줌 모달을 연다. 편집 공간 = 검출 격자의 논리 해상도
+// (예: 28×48) — 프레임과 동일한 조작감. 저장은 사이드카가 아니라 명시 버튼으로
+// /api/base-edit (space:"logical") 에 굽고, 서버가 논리→raw 블록 확장을 맡는다.
+const BASE_STATE = "__base__";
+
+let baseView = null; // {cols, rows, xEdges, yEdges, url(논리 PNG), rawUrl} — 베이스 뷰 상태
+
+let baseLogicalImg = null; // 논리 이미지 엘리먼트 — 편집/합성/샘플의 단일 소스
+
+// 편집·합성 소스: 베이스는 항상 논리 이미지 (pp OFF 로 raw 를 "보고" 있어도
+// 편집 공간은 논리 격자 — 균일 좌표가 이미지와 어긋나는 문제의 원천 차단).
+function editSourceFor(stateName, imgEl) {
+ return stateName === BASE_STATE && baseLogicalImg ? baseLogicalImg : imgEl;
+}
+
+function cellDims(stateName) {
+ if (stateName === BASE_STATE && baseView) return [baseView.cols, baseView.rows];
+ return [run.cell.width, run.cell.height];
+}
+
+function seedEntries() {
+ entries = {};
+ const curated = (run.curation && run.curation.states) || {};
+ for (const state of run.states) {
+ const physPresent = state.frames.filter((f) => f.present).map((f) => f.index);
+ const c = curated[state.name];
+ // 복제 인스턴스: {복제idx: 원본idx}. 복제idx 는 물리 범위 밖 정수, 원본은 물리
+ // 프레임이어야 한다 (손상 항목 스킵). 원본이 present 면 복제도 present 취급.
+ const physIdxSet = new Set(state.frames.map((f) => f.index));
+ const clones = {};
+ if (c && c.clones && typeof c.clones === "object") {
+ for (const [k, v] of Object.entries(c.clones)) {
+ const ci = Number(k);
+ const src = Number(v);
+ if (Number.isInteger(ci) && Number.isInteger(src) && !physIdxSet.has(ci) && physIdxSet.has(src)) clones[ci] = src;
+ }
+ }
+ const cloneIdx = Object.keys(clones).map(Number);
+ const present = [...physPresent, ...cloneIdx.filter((ci) => physPresent.includes(clones[ci]))];
+ // order = full display arrangement (sequence then pool); sel = which are on.
+ // Coerce to integers and de-dupe so a hand-edited / corrupt sidecar (string
+ // indices, duplicates) can't produce a duplicated or dropped frame.
+ const missing = state.frames.filter((f) => !f.present).map((f) => f.index);
+ const allIdx = [...present, ...missing];
+ const coerce = (arr, valid) => {
+ const seen = new Set();
+ const out = [];
+ for (const raw of Array.isArray(arr) ? arr : []) {
+ const i = Number(raw);
+ if (Number.isInteger(i) && valid.includes(i) && !seen.has(i)) {
+ seen.add(i);
+ out.push(i);
+ }
+ }
+ return out;
+ };
+ const archived = c && Array.isArray(c.deleted) ? coerce(c.deleted, allIdx) : [];
+ const archivedSet = new Set(archived);
+ const savedSel = (c && Array.isArray(c.selected) ? coerce(c.selected, present) : []).filter((i) => !archivedSet.has(i));
+ const savedOrder = (c && Array.isArray(c.order) ? coerce(c.order, allIdx) : []).filter((i) => !archivedSet.has(i));
+ let order;
+ if (savedOrder.length) {
+ // restore the exact saved arrangement (incl. pool order); append any
+ // newly-extracted frames that weren't in the saved order.
+ const seen = new Set([...savedOrder, ...archived]);
+ order = [...savedOrder, ...allIdx.filter((i) => !seen.has(i))];
+ } else if (savedSel.length) {
+ // older sidecar without `order`: selected leads, the rest trail.
+ const inSel = new Set(savedSel);
+ order = [...savedSel, ...present.filter((i) => !inSel.has(i) && !archivedSet.has(i)),
+ ...missing.filter((i) => !archivedSet.has(i))];
+ } else {
+ order = allIdx.filter((i) => !archivedSet.has(i));
+ }
+ const sel = savedSel.length ? new Set(savedSel) : new Set(present.filter((i) => !archivedSet.has(i)));
+ const transforms = {};
+ if (c && c.transforms) {
+ for (const [idx, t] of Object.entries(c.transforms)) {
+ transforms[idx] = { ...IDENTITY(), ...t };
+ }
+ }
+ const pixels = {};
+ if (c && c.pixels && typeof c.pixels === "object") {
+ for (const [k, v] of Object.entries(c.pixels)) {
+ const i = Number(k);
+ if (Number.isInteger(i) && v && typeof v === "object" && Object.keys(v).length) pixels[i] = { ...v };
+ }
+ }
+ const unlinked = new Set();
+ if (c && Array.isArray(c.unlinked)) {
+ for (const raw of c.unlinked) {
+ const ci = Number(raw);
+ if (clones[ci] !== undefined) unlinked.add(ci);
+ }
+ }
+ // 레거시 자가판정: 링크 개념 도입(2026-07-18) 이전에 복제에 직접 넣은 변형/픽셀
+ // 편집은 독립 의도였다 — 자동 unlinked 로 보존 (조용한 편집 소실 금지)
+ for (const ci of Object.keys(clones).map(Number)) {
+ if (unlinked.has(ci)) continue;
+ const hasOwn = (c && c.transforms && c.transforms[ci]) || (c && c.pixels && c.pixels[ci] && Object.keys(c.pixels[ci]).length);
+ if (hasOwn) unlinked.add(ci);
+ }
+ const names = {};
+ if (c && c.names && typeof c.names === "object") {
+ for (const [k, v] of Object.entries(c.names)) {
+ const i = Number(k);
+ if (Number.isInteger(i) && typeof v === "string" && v.trim()) names[i] = v.trim().slice(0, 24);
+ }
+ }
+ // 폐기된 분할선 스키마(splits/amplitude/subpixel/hold)를 가진 사이드카는 **건드리지
+ // 않고 그대로 들고 있는다.** 파싱 실패로 null 처리하면 그 줄이 "호흡 꺼짐"으로 보이고
+ // 첫 autosave 가 폐기 키를 사이드카에서 지워버려, 굽기의 loud reject 도 migrate-breathe
+ // 도 근거를 잃는다 (validator·validator 독립 실측 2026-07-25 — 구 런을 한 번 여는 것만으로 소실).
+ const rawBreathe = c && c.breathe;
+ const retired = rawBreathe
+ ? RETIRED_BREATHE_KEYS.filter((k) => k in rawBreathe) : [];
+ // 범위 밖 값도 **조용히 깎지 않는다.** 굽기는 loud reject 하는데 웹뷰만 깎아서 되쓰면
+ // 사용자의 원래 숫자가 파괴되고 loud reject 자체가 사라진다 (validator 실측 2026-07-25).
+ // 폐기 키와 같은 취급: 원본 보존 + 화면 통지.
+ const outOfRange = rawBreathe && !retired.length
+ ? breatheRangeProblems(rawBreathe) : [];
+ entries[state.name] = { order, sel, transforms, archived, pixels, clones, unlinked, names,
+ // 원본 보존 — persistence 가 이걸 그대로 되쓴다 (정규화·삭제 금지)
+ breatheRetired: (retired.length || outOfRange.length)
+ ? { keys: retired.length ? retired : outOfRange, raw: rawBreathe } : null,
+ // 호흡 후처리 레이어 (사이드카 breathe — curation.state_breathe 와 같은 형태).
+ // 클램프하지 않는다: 범위 검증은 위에서 하고, 여기서는 굽기와 같은 형변환만 한다
+ // (파이썬 `float()`/`int()` 처럼 숫자 문자열도 받는다).
+ // `depth` 생략은 굽기에서 기본값 0.06 이다 — 웹뷰만 "호흡 없음" 으로 읽으면
+ // 켜짐/꺼짐이 반대가 되고 첫 autosave 가 설정을 지운다 (validator note 2026-07-26).
+ // 명시적 `null` 은 키와 무관하게 위 범위 검사에 걸려 여기 안 온다.
+ breathe: rawBreathe && !retired.length && !outOfRange.length
+ // `depth` 생략은 굽기에서 0.06 이다. `Number(undefined)` = NaN 이고
+ // `JSON.stringify(NaN)` 은 `null` 이라, 기본값 분기가 없으면 첫 autosave 가
+ // 사이드카에 `depth: null` 을 박아 **굽기가 죽는다** (validator 실측 2026-07-26).
+ ? { depth: rawBreathe.depth == null ? 0.06 : Number(rawBreathe.depth),
+ // 위에서 정수 검증을 통과했으므로 반올림이 필요 없다 — 반올림하면 굽기와 갈린다
+ breaths: Number(rawBreathe.breaths == null ? 1 : rawBreathe.breaths),
+ lag: Number(rawBreathe.lag == null ? 0.1 : rawBreathe.lag),
+ rigid_row: rawBreathe.rigid_row == null ? null : Number(rawBreathe.rigid_row),
+ anatomy: rawBreathe.anatomy || null }
+ : null };
+ }
+ // 폐기 스키마가 하나라도 있으면 조용히 넘어가지 않는다 — 사용자가 마이그레이션을
+ // 실행할 수 있게 알린다 (굽기 쪽 loud reject 와 같은 계약을 UI 에서도 지킨다).
+ const stale = run.states.filter((s2) => entries[s2.name] && entries[s2.name].breatheRetired);
+ if (stale.length) {
+ const names = stale.map((s2) => s2.name).join(", ");
+ const why = stale.map((s2) => entries[s2.name].breatheRetired.keys.join("/")).join(" · ");
+ setStatus(`읽을 수 없는 호흡 사이드카: ${names} (${why}) — 원본은 그대로 두었다. `
+ + `\`sprite-gen migrate-breathe <run-dir> --apply\` 로 옮기거나 값을 범위 안으로 고쳐라.`, "err");
+ }
+}
diff --git a/sprite_gen/serve/curator/src/tooltip.js b/sprite_gen/serve/curator/src/tooltip.js
new file mode 100644
index 0000000..3345167
--- /dev/null
+++ b/sprite_gen/serve/curator/src/tooltip.js
@@ -0,0 +1,89 @@
+// SPDX-License-Identifier: Apache-2.0
+// curator/tooltip.js — 공통 툴팁 컴포넌트 (네이티브 title 대체)
+// 로드 순서 SSoT = index.html (classic script 전역 어휘 공유; 빌드 스텝 없음)
+
+// 단일 팝오버를 body 에 두고 document 위임으로 재사용한다. 대상은 `data-tip`
+// 속성으로 opt-in (title= 대신). `data-tip-copy` 가 있으면 팝오버가 인터랙티브
+// 해져(pointer-events auto + user-select text) 마우스를 팝오버 안으로 옮겨 텍스트를
+// 드래그·복사할 수 있다 — 에이전트 협업 시 프레임 풀네임을 그대로 집어가게 하려는 것.
+// 네이티브 title 은 커스텀과 겹쳐 이중 표시되므로 쓰지 않는다.
+const Tooltip = (() => {
+ let el = null;
+ let copyEl = null;
+ let anchor = null;
+ let hideTimer = 0;
+
+ function ensure() {
+ if (el) return;
+ el = document.createElement("div");
+ el.id = "sg-tip";
+ el.setAttribute("role", "tooltip");
+ document.body.appendChild(el);
+ // 팝오버 자체에 마우스가 들어오면 유지(복사 가능), 나가면 숨김
+ el.addEventListener("pointerenter", () => clearTimeout(hideTimer));
+ el.addEventListener("pointerleave", hide);
+ }
+
+ function position(target) {
+ const r = target.getBoundingClientRect();
+ el.style.maxWidth = Math.min(360, window.innerWidth - 16) + "px";
+ // 먼저 보이게 해 크기 측정, 그 다음 위치 클램프
+ el.style.visibility = "hidden";
+ el.classList.add("open");
+ const tr = el.getBoundingClientRect();
+ let top = r.bottom + 6;
+ if (top + tr.height > window.innerHeight - 6) top = Math.max(6, r.top - tr.height - 6);
+ let left = r.left;
+ if (left + tr.width > window.innerWidth - 6) left = Math.max(6, window.innerWidth - 6 - tr.width);
+ el.style.top = Math.round(top) + "px";
+ el.style.left = Math.round(left) + "px";
+ el.style.visibility = "";
+ }
+
+ function show(target) {
+ const text = target.getAttribute("data-tip");
+ if (!text) return;
+ ensure();
+ clearTimeout(hideTimer);
+ anchor = target;
+ const copyable = target.hasAttribute("data-tip-copy");
+ el.className = copyable ? "open copyable" : "open";
+ if (copyable) {
+ el.innerHTML = "";
+ copyEl = document.createElement("span");
+ copyEl.className = "sg-tip-text";
+ copyEl.textContent = text;
+ el.appendChild(copyEl);
+ } else {
+ el.textContent = text;
+ copyEl = null;
+ }
+ position(target);
+ }
+
+ function hide() {
+ clearTimeout(hideTimer);
+ hideTimer = setTimeout(() => {
+ if (el) el.classList.remove("open");
+ anchor = null;
+ }, 80);
+ }
+
+ // 위임: 어떤 요소든 data-tip 이 있으면 자동 적용 (공통 컴포넌트)
+ document.addEventListener("pointerover", (e) => {
+ const target = e.target.closest?.("[data-tip]");
+ if (target && target !== anchor) show(target);
+ });
+ document.addEventListener("pointerout", (e) => {
+ const target = e.target.closest?.("[data-tip]");
+ // 팝오버(복사가능)로 이동 중이면 유지 — pointerleave 가 최종 숨김을 담당
+ if (target && target === anchor && !e.relatedTarget?.closest?.("#sg-tip")) hide();
+ });
+ // 드래그/클릭이 시작되면 즉시 숨김 (제목 드래그 = 순서변경과 충돌 방지)
+ document.addEventListener("pointerdown", (e) => {
+ if (!e.target.closest?.("#sg-tip")) { if (el) el.classList.remove("open"); anchor = null; }
+ }, true);
+ window.addEventListener("scroll", () => { if (el) el.classList.remove("open"); anchor = null; }, true);
+
+ return { show, hide };
+})();
diff --git a/sprite_gen/serve/curator/src/transform-provider.js b/sprite_gen/serve/curator/src/transform-provider.js
new file mode 100644
index 0000000..db416e2
--- /dev/null
+++ b/sprite_gen/serve/curator/src/transform-provider.js
@@ -0,0 +1,124 @@
+// SPDX-License-Identifier: Apache-2.0
+// curator/transform-provider.js — 변형 제스처의 공용 프로바이더.
+// 로드 순서 SSoT = index.html (classic script 전역 어휘 공유; 빌드 스텝 없음)
+//
+// **왜 따로 있나**: 변형 제스처(이동·회전·비틀기)가 두 대상에 붙는다.
+// 1. 셀 전체 — 사이드카 `transforms[idx]` 파라미터를 고친다 (`transforms.js`)
+// 2. 선택 영역 — 픽셀을 실제로 옮겨 `pixels[idx]` 로 굽는다 (`region-transform.js`)
+// 제스처의 **수학과 손맛**(드래그 임계·회전 각도·시어 기울기 환산)은 둘이 같아야 한다.
+// 두 벌로 두면 한쪽만 고쳐져 "전체는 되는데 영역은 반대로 돈다" 같은 게 태어난다.
+// 그래서 여기에 한 벌만 둔다. 대상별 차이는 콜백(onDelta)이 흡수한다.
+
+// 드래그로 볼 최소 이동(px). 클릭과 드래그를 가르는 값 — `transforms.js` 가 쓰던 것과 같다.
+// `DRAG_THRESHOLD` 는 util.js 전역 — index.html 로드 순서가 그것을 먼저 보장한다.
+const TP_DRAG_THRESHOLD = DRAG_THRESHOLD;
+
+// 화면 각도는 시계방향이 +, 스키마(PIL)는 반시계가 + 다. 부호를 여기서 한 번만 뒤집는다 —
+// 두 소비자가 각자 뒤집으면 한쪽이 반대로 돈다.
+function tpScreenDeltaToRotate(startAngle, nowAngle) {
+ return -(((nowAngle - startAngle) * 180) / Math.PI);
+}
+
+// 기울기 정규화 — 전폭 드래그가 대략 1.0 기울기. 셀 전체·영역 두 경로가 같은 감도를 쓴다.
+function tpShearDelta(ddx, ddy, spanW, spanH) {
+ return { shx: ddx / Math.max(1, spanW), shy: ddy / Math.max(1, spanH) };
+}
+
+function tpAngleAt(cx, cy, ev) {
+ return Math.atan2(ev.clientY - cy, ev.clientX - cx);
+}
+
+// 포인터 제스처 한 벌을 건다. `onDelta({dx, dy, rotate, shx, shy}, ev)` 가 매 이동마다
+// **시작 시점 대비 누적 델타**를 받는다 — 소비자는 자기 기준값에 더하기만 하면 된다.
+//
+// 모디파이어로 축을 가른다 (핸들 DOM 을 안 늘린다 — 영역은 크기가 제각각이라
+// 핸들을 붙이면 작은 선택에서 핸들이 영역을 덮는다):
+// 기본 = 이동
+// Shift = 회전 (영역/셀 중심 기준)
+// Alt(Option) = 비틀기 (가로 드래그 = shx, 세로 = shy)
+function tpWireGesture(el, opts) {
+ const {
+ pixelsPerUnit, // () => 화면px / 셀px 배율
+ centerOf, // () => [clientX, clientY] 회전 중심
+ spanOf, // () => [width, height] 비틀기 정규화 기준(화면px)
+ onStart, // () => void — 스냅샷 찍을 자리
+ onDelta, // (delta, ev) => void
+ onEnd, // (moved) => void
+ enabled, // () => boolean
+ } = opts;
+
+ el.addEventListener("pointerdown", (ev) => {
+ if (enabled && !enabled(ev)) return;
+ if (ev.button || !ev.isPrimary) return;
+ ev.preventDefault();
+ // **stopPropagation 이 아니라 stopImmediatePropagation 이다.** 같은 엘리먼트(stage)에
+ // 셀 전체 이동 핸들러(`transforms.js` wireStage)가 같이 붙어 있어서, 버블링만 막으면
+ // 그놈이 그대로 실행돼 영역과 셀이 **같이** 움직인다(노을이 재현 2026-07-26:
+ // regionDelta dx=6 인데 wholeCellDx=6 도 같이 발생). 바로 옆 페인트 핸들러가
+ // 같은 이유로 이미 stopImmediatePropagation 을 쓴다.
+ ev.stopImmediatePropagation();
+ el.setPointerCapture(ev.pointerId);
+ if (onStart) onStart(ev);
+
+ const start = { x: ev.clientX, y: ev.clientY };
+ const [cx, cy] = centerOf ? centerOf() : [0, 0];
+ const startAngle = tpAngleAt(cx, cy, ev);
+ let moved = false;
+
+ const onMove = (e) => {
+ const ddx = e.clientX - start.x;
+ const ddy = e.clientY - start.y;
+ if (Math.abs(ddx) > TP_DRAG_THRESHOLD || Math.abs(ddy) > TP_DRAG_THRESHOLD) moved = true;
+ const delta = { dx: 0, dy: 0, rotate: 0, shx: 0, shy: 0 };
+ // 축 고정 — 핸들에서 온 제스처는 모디파이어와 무관하게 자기 축만 움직인다.
+ // (스테이지 드래그는 axis 없이 걸어 모디파이어로 가른다.)
+ const axis = opts.axis;
+ if (axis === "rotate" || (!axis && e.shiftKey)) {
+ delta.rotate = tpScreenDeltaToRotate(startAngle, tpAngleAt(cx, cy, e));
+ } else if (axis === "shear" || (!axis && e.altKey)) {
+ const [sw, sh] = spanOf ? spanOf() : [el.clientWidth, el.clientHeight];
+ const sh2 = tpShearDelta(ddx, ddy, sw, sh);
+ delta.shx = sh2.shx;
+ delta.shy = sh2.shy;
+ } else {
+ const ppu = pixelsPerUnit ? pixelsPerUnit() : 1;
+ delta.dx = ddx / ppu;
+ delta.dy = ddy / ppu;
+ }
+ onDelta(delta, e);
+ };
+ const onUp = () => {
+ el.releasePointerCapture(ev.pointerId);
+ el.removeEventListener("pointermove", onMove);
+ el.removeEventListener("pointerup", onUp);
+ if (onEnd) onEnd(moved);
+ };
+ el.addEventListener("pointermove", onMove);
+ el.addEventListener("pointerup", onUp);
+ });
+}
+
+// 영역 변형이 픽셀을 옮길 때 쓰는 역사상(destination → source). 정변환으로 소스를 훑으면
+// 회전·비틀기에서 목적지에 구멍이 뚫린다 — 목적지를 훑고 소스를 역으로 찾아야 빈틈이 없다.
+// `t` = {rotate(도, CCW+), shx, shy, dx, dy}, 중심 = (ox, oy) 셀 좌표.
+function tpInverseSample(t, ox, oy) {
+ const rad = ((t.rotate || 0) * Math.PI) / 180;
+ const cos = Math.cos(rad);
+ const sin = Math.sin(rad);
+ // 정변환 M = Shear · Rot (transforms.js matrixOf 와 같은 합성 순서)
+ const m00 = cos + (t.shx || 0) * sin;
+ const m01 = -sin + (t.shx || 0) * cos;
+ const m10 = (t.shy || 0) * cos + sin;
+ const m11 = -(t.shy || 0) * sin + cos;
+ const det = m00 * m11 - m01 * m10;
+ if (Math.abs(det) < 1e-9) return null;
+ const i00 = m11 / det;
+ const i01 = -m01 / det;
+ const i10 = -m10 / det;
+ const i11 = m00 / det;
+ return (dx, dy) => {
+ const px = dx - ox - (t.dx || 0);
+ const py = dy - oy - (t.dy || 0);
+ return [i00 * px + i01 * py + ox, i10 * px + i11 * py + oy];
+ };
+}
diff --git a/sprite_gen/serve/curator/src/transforms.js b/sprite_gen/serve/curator/src/transforms.js
new file mode 100644
index 0000000..640473e
--- /dev/null
+++ b/sprite_gen/serve/curator/src/transforms.js
@@ -0,0 +1,314 @@
+// SPDX-License-Identifier: Apache-2.0
+// curator/transforms.js — 카드 변형 (회전/스케일/시어/플립) 적용 + 스테이지 조작 배선
+// 로드 순서 SSoT = index.html (classic script 전역 어휘 공유; 빌드 스텝 없음)
+
+function applyCardTransform(stage, stateName, idx) {
+ const t = getTransform(stateName, idx);
+ const el = stage.querySelector("img");
+ if (!el) return;
+ const [cw, ch] = cellDims(stateName); // 베이스(가상 상태)는 검출 격자 논리 치수
+ // dx/dy are stored in cell pixels; CSS needs rendered pixels.
+ const ds = stage.clientWidth / cw;
+ const m = matrixOf(t);
+ const snap = snapScaleFor(stateName);
+ const canvas = stage.querySelector(".snap-canvas");
+ if (!canvas) return; // 프레임 없는 스테이지(missing 라벨)는 그릴 것이 없다
+ // ── 표시면은 캔버스 하나다 (maintainer 2026-07-24 "구현체가 몇 종류라 노이즈"). ──
+ // img 는 숨김 로더(natural size·load 이벤트·편집 소스)일 뿐 절대 표시면이 아니다.
+ // 예전엔 편집/변형/양자화 프레임만 캔버스로, 나머지는 img 로 갈라 그렸고 —
+ // 그 fork 의 한쪽만 보다가 표시 결함 5건(v1.56.85~89)이 전부 태어났다.
+ el.style.transform = "";
+ el.style.visibility = "hidden";
+ canvas.style.display = "block";
+ // 한 렌더러의 두 모드 (fork 아님 — drawFrameInto 하나가 렌더한다):
+ // - 양자화 (pp 뷰: 계약 scale 또는 측정 k): 변형을 격자 재양자화로 굽기와 동일하게
+ // 미리 본다. 이동이 격자 단위로 스냅된다 (의도). 격자 오버레이와 같은 k — 격자 기준 퍼펙.
+ // - 소스 (plain 뷰): 소스 해상도(ss)로 identity 렌더 + 이동은 CSS 변형.
+ // 편집 세션도 같은 두 모드를 그대로 쓴다 (WYSIWYG, maintainer 2026-07-19).
+ const quantize = !!snap; // 베이스 pp ON 은 snapScaleFor 가 1 을 돌려 여기 포함된다
+ const render = () => {
+ // 소스 모드는 소스 해상도로 그린다 — 셀 크기 캔버스에 고해상 원본 트윈을
+ // 그리면 64px 로 파괴된다 (maintainer 2026-07-24). 양자화 모드는 결과 격자가
+ // 목적이라 셀 크기 그대로다.
+ // 소스 모드의 **표시** 소스는 el(frameUrl 이 고른 파일 — 베이스 pp OFF 면 raw)이다.
+ // editSourceFor 는 편집 좌표 계약(베이스 = 항상 논리 공간)이라 양자화 모드에서만
+ // 소스로 쓴다 — 표시까지 논리로 강제하면 베이스의 원본 뷰가 사라진다 (validator 기각).
+ const source = quantize ? editSourceFor(stateName, el) : el;
+ const ss = quantize ? 1 : superSampleFor(source, cw);
+ canvas.width = cw * ss;
+ canvas.height = ch * ss;
+ const ctx = canvas.getContext("2d");
+ ctx.clearRect(0, 0, canvas.width, canvas.height);
+ const tt = quantize ? getTransform(stateName, idx) : IDENTITY();
+ drawFrameInto(ctx, source, tt, cw, ch, snap, getPixelOps(stateName, idx), ss);
+ // 버퍼 해상도가 여기서 정해진다 — 사실을 만든 자리에서 소비자(판정)를 갱신한다
+ // (validator R1, 2026-07-24: 바깥 스윕만 두면 canvas 기본값 300 을 보고 답한다).
+ applyPixelScaling(canvas);
+ };
+ canvas.style.transform = quantize
+ ? ""
+ : `translate(${t.dx * ds}px, ${t.dy * ds}px) matrix(${m.m00}, ${m.m10}, ${m.m01}, ${m.m11}, 0, 0)`;
+ if (el.complete && el.naturalWidth) render();
+ else el.addEventListener("load", render, { once: true });
+ const sh = t.shx || t.shy ? ` sh${(t.shx || 0).toFixed(2)},${(t.shy || 0).toFixed(2)}` : "";
+ const flip = t.flipX ? " ↔" : "";
+ const card = stage.closest(".card");
+ const tvalsEl = card.querySelector(".tvals");
+ // 항등 변형이면 값 줄을 비운다 (r0° ×1.00 +0,+0 상시 표시 = 잡음). 조정이 있을 때만 노출.
+ if (tvalsEl) {
+ tvalsEl.textContent = isIdentityTransform(t)
+ ? ""
+ : `r${t.rotate.toFixed(0)}° ×${t.scale.toFixed(2)} ${t.dx >= 0 ? "+" : ""}${t.dx.toFixed(0)},${t.dy >= 0 ? "+" : ""}${t.dy.toFixed(0)}${sh}${flip}`;
+ }
+ // flip 버튼은 도구(누를 때마다 반전)다 — 활성/비활성 상태 강조 없음 (maintainer 2026-07-19).
+ // 반전 상태 자체는 tvals 의 ↔ 로만 표시한다.
+ // 대응 격자(초록)는 콘텐츠 기준 — 변형이 바뀔 때마다 이 카드 것만 다시 그린다
+ // (이동은 따라오고, 비축정렬이 되면 숨는 판정도 여기서 갱신된다).
+ updateCardGrid(card);
+}
+
+// 같은 프레임을 보여주는 모든 스테이지(그리드 카드 + 확대 모달)를 함께 갱신 —
+// 어느 쪽에서 편집해도 두 화면이 실시간 동기화된다.
+function applyFrameTransformAll(stateName, idx) {
+ // 링크 동기화 (maintainer 2026-07-18): 편집 truth 를 공유하는 모든 인스턴스 카드
+ // (원본 + 링크된 복제들)를 같이 다시 그린다 — truth 는 하나, 표시는 전부.
+ const truth = editIndex(stateName, idx);
+ const e = entries[stateName];
+ const targets = new Set([truth]);
+ for (const i of e.order) {
+ if (editIndex(stateName, i) === truth) targets.add(i);
+ }
+ for (const i of targets) {
+ document
+ .querySelectorAll(`.card[data-state="${cssEscape(stateName)}"][data-idx="${i}"] .stage`)
+ .forEach((s) => applyCardTransform(s, stateName, i));
+ }
+}
+
+// ── 변형 조작 히스토리 (maintainer 2026-07-20 "커맨드제트 안 먹혀, 캐릭터 이동한 담에"):
+// 제스처(드래그 1회·클릭 1회) 단위 before/after 스냅샷. 이동/회전/시어/스케일/
+// 플립/리셋 전부 — 그리드 카드와 확대 모달 공통 (변형 truth 가 하나이므로 하나의
+// 전역 스택). Cmd+Z 라우팅 우선순위는 zoom-editor.js 소유: 호흡 > 픽셀 편집 > 변형.
+const transformHist = { list: [], pos: -1 };
+
+function tfSnapshot(stateName, idx) {
+ return { state: stateName, idx, tr: { ...getTransform(stateName, idx) } };
+}
+
+function pushTransformHist(before) {
+ const after = tfSnapshot(before.state, before.idx);
+ if (JSON.stringify(before.tr) === JSON.stringify(after.tr)) return; // 무변 제스처 = 잡음 금지
+ transformHist.list = transformHist.list.slice(0, transformHist.pos + 1);
+ transformHist.list.push({ before, after });
+ transformHist.pos = transformHist.list.length - 1;
+}
+
+function applyTfSnapshot(s) {
+ entries[s.state].transforms[editIndex(s.state, s.idx)] = { ...s.tr };
+ applyFrameTransformAll(s.state, s.idx);
+ scheduleSave();
+}
+
+function undoTransform() {
+ if (transformHist.pos < 0) return false;
+ applyTfSnapshot(transformHist.list[transformHist.pos].before);
+ transformHist.pos -= 1;
+ return true;
+}
+
+function redoTransform() {
+ if (transformHist.pos + 1 >= transformHist.list.length) return false;
+ transformHist.pos += 1;
+ applyTfSnapshot(transformHist.list[transformHist.pos].after);
+ return true;
+}
+
+function wireStage(stage, stateName, idx) {
+ const ds = () => stage.clientWidth / run.cell.width;
+
+ // translate by dragging, toggle select on a click that did not drag
+ stage.addEventListener("pointerdown", (ev) => {
+ if (ev.target.classList.contains("rotate-handle")) return;
+ ev.preventDefault();
+ stage.setPointerCapture(ev.pointerId);
+ const before = tfSnapshot(stateName, idx);
+ const t = getTransform(stateName, idx);
+ const start = { x: ev.clientX, y: ev.clientY, dx: t.dx, dy: t.dy };
+ let moved = false;
+
+ const onMove = (e) => {
+ const ddx = e.clientX - start.x;
+ const ddy = e.clientY - start.y;
+ if (Math.abs(ddx) > DRAG_THRESHOLD || Math.abs(ddy) > DRAG_THRESHOLD) moved = true;
+ t.dx = start.dx + ddx / ds();
+ t.dy = start.dy + ddy / ds();
+ applyFrameTransformAll(stateName, idx);
+ };
+ const onUp = () => {
+ stage.releasePointerCapture(ev.pointerId);
+ stage.removeEventListener("pointermove", onMove);
+ stage.removeEventListener("pointerup", onUp);
+ // 스테이지 클릭은 더 이상 시퀀스⇄풀 토글이 아니다 (maintainer 2026-07-15): 실수로
+ // 카드를 눌러 빠지는 걸 막는다. 이동은 넣기/빼기 버튼 또는 드래그로만.
+ if (moved) {
+ pushTransformHist(before);
+ scheduleSave();
+ }
+ };
+ stage.addEventListener("pointermove", onMove);
+ stage.addEventListener("pointerup", onUp);
+ });
+
+ // (휠 스케일 제거 — 맥 터치패드 오작동. 크기 조절은 우하단 돋보기 스크러버로.)
+
+ // rotate via the top handle
+ const handle = stage.querySelector(".rotate-handle");
+ handle.addEventListener("pointerdown", (ev) => {
+ ev.preventDefault();
+ ev.stopPropagation();
+ handle.setPointerCapture(ev.pointerId);
+ const before = tfSnapshot(stateName, idx);
+ const rect = stage.getBoundingClientRect();
+ const cx = rect.left + rect.width / 2;
+ const cy = rect.top + rect.height / 2;
+ const t = getTransform(stateName, idx);
+ const startScreen = Math.atan2(ev.clientY - cy, ev.clientX - cx);
+ const origRotate = t.rotate;
+
+ const onMove = (e) => {
+ // 화면각 → 스키마각(CCW+) 변환은 `transform-provider.js` 가 소유한다 — 여기서
+ // 따로 뒤집으면 영역 변형과 부호가 갈릴 수 있다(노을이 기각 R4 2026-07-26:
+ // "부호 반전이 한 곳" 이라는 주장이 사실이 아니었다. 이제 사실이다).
+ t.rotate = origRotate + tpScreenDeltaToRotate(startScreen, tpAngleAt(cx, cy, e));
+ applyFrameTransformAll(stateName, idx);
+ };
+ const onUp = () => {
+ handle.releasePointerCapture(ev.pointerId);
+ handle.removeEventListener("pointermove", onMove);
+ handle.removeEventListener("pointerup", onUp);
+ pushTransformHist(before);
+ scheduleSave();
+ };
+ handle.addEventListener("pointermove", onMove);
+ handle.addEventListener("pointerup", onUp);
+ });
+
+ // shear via the bottom-left handle: horizontal drag = shx, vertical = shy
+ const shear = stage.querySelector(".shear-handle");
+ shear.addEventListener("pointerdown", (ev) => {
+ ev.preventDefault();
+ ev.stopPropagation();
+ shear.setPointerCapture(ev.pointerId);
+ const before = tfSnapshot(stateName, idx);
+ const t = getTransform(stateName, idx);
+ const start = { x: ev.clientX, y: ev.clientY, shx: t.shx || 0, shy: t.shy || 0 };
+ const onMove = (e) => {
+ // 기울기 정규화(전폭 드래그 ≈ 1.0)도 프로바이더가 소유한다 — 영역 변형과 감도가
+ // 갈리면 "전체는 되는데 영역은 덜 기운다" 가 된다.
+ const sh = tpShearDelta(e.clientX - start.x, e.clientY - start.y,
+ stage.clientWidth, stage.clientHeight);
+ t.shx = start.shx + sh.shx;
+ t.shy = start.shy + sh.shy;
+ applyFrameTransformAll(stateName, idx);
+ };
+ const onUp = () => {
+ shear.releasePointerCapture(ev.pointerId);
+ shear.removeEventListener("pointermove", onMove);
+ shear.removeEventListener("pointerup", onUp);
+ pushTransformHist(before);
+ scheduleSave();
+ };
+ shear.addEventListener("pointermove", onMove);
+ shear.addEventListener("pointerup", onUp);
+ });
+}
+
+//
+// Each state renders two `.frames` rows: the top is the play SEQUENCE (selected
+// frames, in order) and the bottom is the candidate POOL (everything else,
+// e.g. an extra generated take). Dragging the ⠿ grip reorders within a row OR
+// moves a card between rows; which row a card lands in *is* its selection. The
+// grip lives in `.card-top`, outside `.stage`, so it never collides with the
+// stage's move/scale/rotate/shear drags.
+
+// 스프라이트 크기 스크러버 (‹⤢› 형태, 이모지 아님 — SVG): 화살표 클릭 = 스텝,
+// 가운데 아이콘 드래그 = 연속. 맥 터치패드에서 휠-스케일이 불편해 추가.
+// 아이콘 = 대각 리사이즈 — 돋보기는 "화면 배율"(view-nav.js) 전용 어휘라 여기 금지
+// (maintainer 지시 2026-07-20: 돋보기로 하니까 확대축소 보기로 오해).
+function makeScaleScrub(stateName, idx) {
+ const wrap = document.createElement("span");
+ wrap.className = "scale-scrub";
+ wrap.setAttribute("data-tip", t("tScaleScrub"));
+ wrap.innerHTML =
+ '<button type="button" class="ghost ss-step" data-dir="-1" aria-label="smaller">' +
+ '<svg viewBox="0 0 10 10" width="9" height="9"><path d="M2 5h6" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/></svg></button>' +
+ '<span class="ss-grab" aria-label="drag to scale">' +
+ '<svg viewBox="0 0 16 16" width="13" height="13">' +
+ '<path d="M9.8 3h3.2v3.2M6.2 13H3v-3.2" fill="none" stroke="currentColor" stroke-width="1.3" stroke-linecap="round" stroke-linejoin="round"/>' +
+ '<path d="M12.6 3.4 9.4 6.6M3.4 12.6l3.2-3.2" stroke="currentColor" stroke-width="1.3" stroke-linecap="round"/></svg></span>' +
+ '<button type="button" class="ghost ss-step" data-dir="1" aria-label="bigger">' +
+ '<svg viewBox="0 0 10 10" width="9" height="9"><path d="M2 5h6M5 2v6" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/></svg></button>';
+ const clamp = (v) => Math.min(SCALE_MAX, Math.max(SCALE_MIN, v));
+ // ± 연타가 스테이지 더블클릭(확대 모달 열기)으로 새지 않게 스크러버 안의
+ // 포인터/클릭 계열 이벤트는 전부 여기서 끊는다 (maintainer 지적 2026-07-16).
+ for (const type of ["pointerdown", "click", "dblclick"]) {
+ wrap.addEventListener(type, (ev) => ev.stopPropagation());
+ }
+ wrap.querySelectorAll(".ss-step").forEach((btn) => {
+ btn.addEventListener("pointerdown", (ev) => ev.stopPropagation());
+ btn.addEventListener("click", () => {
+ const before = tfSnapshot(stateName, idx);
+ const tr = getTransform(stateName, idx);
+ tr.scale = clamp(tr.scale * (btn.dataset.dir === "1" ? 1.05 : 1 / 1.05));
+ applyFrameTransformAll(stateName, idx);
+ pushTransformHist(before);
+ scheduleSave();
+ });
+ });
+ const grab = wrap.querySelector(".ss-grab");
+ grab.addEventListener("pointerdown", (ev) => {
+ if (ev.button || !ev.isPrimary) return;
+ ev.preventDefault();
+ ev.stopPropagation();
+ grab.setPointerCapture(ev.pointerId);
+ const before = tfSnapshot(stateName, idx);
+ const tr = getTransform(stateName, idx);
+ const startX = ev.clientX;
+ const startScale = tr.scale;
+ const onMove = (e2) => {
+ tr.scale = clamp(startScale * Math.exp((e2.clientX - startX) / 140));
+ applyFrameTransformAll(stateName, idx);
+ };
+ const onUp = () => {
+ grab.releasePointerCapture(ev.pointerId);
+ grab.removeEventListener("pointermove", onMove);
+ grab.removeEventListener("pointerup", onUp);
+ pushTransformHist(before);
+ scheduleSave();
+ };
+ grab.addEventListener("pointermove", onMove);
+ grab.addEventListener("pointerup", onUp);
+ });
+ return wrap;
+}
+
+function resetTransform(stateName, idx) {
+ const before = tfSnapshot(stateName, idx);
+ entries[stateName].transforms[editIndex(stateName, idx)] = IDENTITY();
+ applyFrameTransformAll(stateName, idx);
+ pushTransformHist(before);
+ scheduleSave();
+}
+
+function toggleFlipX(stateName, idx) {
+ const entry = entries[stateName];
+ if (!entry) return;
+ const before = tfSnapshot(stateName, idx);
+ const key = editIndex(stateName, idx);
+ if (!entry.transforms[key]) entry.transforms[key] = IDENTITY();
+ entry.transforms[key].flipX = entry.transforms[key].flipX ? 0 : 1;
+ // 모든 스테이지에 거울 반전을 렌더하고 flip 버튼을 강조한다.
+ applyFrameTransformAll(stateName, idx);
+ pushTransformHist(before);
+ scheduleSave();
+}
diff --git a/sprite_gen/serve/curator/src/tween.js b/sprite_gen/serve/curator/src/tween.js
new file mode 100644
index 0000000..b2c4a49
--- /dev/null
+++ b/sprite_gen/serve/curator/src/tween.js
@@ -0,0 +1,114 @@
+// SPDX-License-Identifier: Apache-2.0
+// curator/tween.js — AI 중간 프레임 보간 (프레임 쌍 픽 + 테이크 생성 요청)
+// 로드 순서 SSoT = index.html (classic script 전역 어휘 공유; 빌드 스텝 없음)
+
+// AI 중간 프레임(보간) — 이 줄의 두 프레임 사이를 RIFE 로 보간해 테이크로 기록하고
+// 전체 배치를 재추출한다. 부분 추출은 서버가 제공하지 않는다 (팔레트 배치 결합 —
+// docs/frame-interpolation.md). 완료되면 run 세대가 바뀌므로 뷰를 새로고침한다.
+//
+// 픽 모드: 팝오버가 열려 있는 동안 그 줄의 카드 클릭 = 보간 쌍 선택 (파란 테두리,
+// 최대 2개 FIFO — 세 번째 클릭이 가장 오래된 픽을 대체). 기존 선택(.selected)의
+// 파란 테두리는 픽 모드 동안 그 줄에서 억제해 픽만 파랗게 보인다.
+let tweenOpen = null; // {stateName, pop, btn, picks, fromInput, toInput, section}
+
+function closeTweenPick() {
+ if (!tweenOpen) return;
+ tweenOpen.pop.hidden = true;
+ if (tweenOpen.section) {
+ tweenOpen.section.classList.remove("tween-picking");
+ tweenOpen.section.querySelectorAll(".card.tween-picked")
+ .forEach((el) => el.classList.remove("tween-picked"));
+ }
+ tweenOpen = null;
+}
+
+document.addEventListener("click", (ev) => {
+ if (!tweenOpen) return;
+ const card = ev.target.closest(".card");
+ if (!card || card.dataset.state !== tweenOpen.stateName) return;
+ if (ev.target.closest(".gen-pop")) return;
+ ev.preventDefault();
+ ev.stopPropagation();
+ const idx = Number(card.dataset.idx);
+ const at = tweenOpen.picks.findIndex((p) => p.idx === idx);
+ if (at >= 0) {
+ tweenOpen.picks.splice(at, 1)[0].card.classList.remove("tween-picked");
+ } else {
+ tweenOpen.picks.push({ idx, card });
+ card.classList.add("tween-picked");
+ if (tweenOpen.picks.length > 2) {
+ tweenOpen.picks.shift().card.classList.remove("tween-picked");
+ }
+ }
+ const [a, b] = tweenOpen.picks;
+ if (a) tweenOpen.fromInput.value = a.idx;
+ if (b) tweenOpen.toInput.value = b.idx;
+}, true);
+
+function makeTweenButton(stateName) {
+ const wrap = document.createElement("span");
+ wrap.className = "gen-wrap";
+ const btn = document.createElement("button");
+ btn.type = "button";
+ btn.className = "gif-btn";
+ btn.title = t("tRowTween");
+ btn.innerHTML =
+ '<svg viewBox="0 0 16 16" width="12" height="12" aria-hidden="true">' +
+ '<path d="M2 8h2.5m7 0H14M8 5.5v5M5.5 8a2.5 2.5 0 115 0 2.5 2.5 0 01-5 0z" fill="none" ' +
+ 'stroke="currentColor" stroke-width="1.4" stroke-linecap="round"/></svg>' +
+ `<span>${t("rowTween")}</span>`;
+ const pop = document.createElement("div");
+ pop.className = "gen-pop";
+ pop.hidden = true;
+ const field = (label, value, step, min, max) => {
+ const lab = document.createElement("label");
+ const input = document.createElement("input");
+ input.type = "number";
+ input.value = value;
+ input.step = step;
+ input.min = min;
+ if (max !== undefined) input.max = max;
+ lab.append(label, input);
+ pop.appendChild(lab);
+ return input;
+ };
+ const fromInput = field(t("tweenFrom"), 0, 1, 0);
+ const toInput = field(t("tweenTo"), 1, 1, 0);
+ const tInput = field(t("tweenT"), 0.5, 0.05, 0.05, 0.95);
+ const providerSel = makeProviderSelect(); // 모델 선택/실행 관용구 SSoT = gen-trigger.js
+ pop.appendChild(providerSel);
+ const go = document.createElement("button");
+ go.type = "button";
+ go.className = "gif-btn";
+ go.textContent = t("genGo");
+ pop.appendChild(go);
+ btn.addEventListener("click", () => {
+ if (tweenOpen && tweenOpen.pop === pop) {
+ closeTweenPick();
+ return;
+ }
+ closeTweenPick();
+ pop.hidden = false;
+ const section = document.querySelector(`.state[data-state="${CSS.escape(stateName)}"]`);
+ if (section) section.classList.add("tween-picking");
+ tweenOpen = { stateName, pop, btn, picks: [], fromInput, toInput, section };
+ });
+ go.addEventListener("click", () => runServerGeneration({
+ url: "/api/interpolate",
+ body: {
+ state: stateName,
+ from: parseInt(fromInput.value, 10),
+ to: parseInt(toInput.value, 10),
+ t: parseFloat(tInput.value),
+ provider: providerSel.value,
+ },
+ goBtn: go,
+ buttons: [btn],
+ busyMsg: t("tweenBusy"),
+ doneMsg: STR[lang].tweenDone(stateName),
+ failPrefix: t("tweenFail"),
+ }));
+ wrap.appendChild(btn);
+ wrap.appendChild(pop);
+ return wrap;
+}
diff --git a/sprite_gen/serve/curator/src/util.js b/sprite_gen/serve/curator/src/util.js
new file mode 100644
index 0000000..06328a0
--- /dev/null
+++ b/sprite_gen/serve/curator/src/util.js
@@ -0,0 +1,48 @@
+// SPDX-License-Identifier: Apache-2.0
+// curator/util.js — 기하/문자열 순수 유틸 — 상태 없음
+// 로드 순서 SSoT = index.html (classic script 전역 어휘 공유; 빌드 스텝 없음)
+
+const IDENTITY = () => ({ rotate: 0, scale: 1, dx: 0, dy: 0, shx: 0, shy: 0, flipX: 0 });
+
+const SCALE_MIN = 0.2;
+
+const SCALE_MAX = 3;
+
+const DRAG_THRESHOLD = 4;
+
+// forward 2x2 matrix (Rotate · Shear · Scale · FlipX); mirrors curation.py transform_matrix
+function matrixOf(t) {
+ const rr = (t.rotate * Math.PI) / 180;
+ const c = Math.cos(rr);
+ const sn = Math.sin(rr);
+ const s = t.scale;
+ const shx = t.shx || 0;
+ const shy = t.shy || 0;
+ let m00 = s * (c + sn * shy);
+ const m01 = s * (c * shx + sn);
+ let m10 = s * (-sn + c * shy);
+ const m11 = s * (c - sn * shx);
+ // (maintainer 2026-05-28) flipX = horizontal mirror (image-gen 결과가 좌우 반대로
+ // 나올 때). diag(-1, 1) 을 matrix 마지막에 곱 → column-0 부호 반전.
+ if (t.flipX) {
+ m00 = -m00;
+ m10 = -m10;
+ }
+ return { m00, m01, m10, m11 };
+}
+
+function cssEscape(s) {
+ return s.replace(/"/g, '\\"');
+}
+
+// escape text that comes from run data (state name/action, frame labels from a
+// manifest / meta.json) before it goes into innerHTML, so an imported set can't
+// inject markup into the webview.
+function escapeHtml(s) {
+ return String(s)
+ .replace(/&/g, "&amp;")
+ .replace(/</g, "&lt;")
+ .replace(/>/g, "&gt;")
+ .replace(/"/g, "&quot;")
+ .replace(/'/g, "&#39;");
+}
diff --git a/sprite_gen/serve/curator/src/view-nav.js b/sprite_gen/serve/curator/src/view-nav.js
new file mode 100644
index 0000000..10e9134
--- /dev/null
+++ b/sprite_gen/serve/curator/src/view-nav.js
@@ -0,0 +1,124 @@
+// SPDX-License-Identifier: Apache-2.0
+// curator/view-nav.js — 디테일뷰 공용 뷰 내비게이션 (maintainer 지시 2026-07-20)
+// 로드 순서 SSoT = index.html (classic script 전역 어휘 공유; 빌드 스텝 없음)
+//
+// 3계층 계약: 모달(고정 최대 크기) ⊃ 뷰포트(화면 배율·팬) ⊃ 콘텐츠(스프라이트 —
+// 자체 변형/스케일은 transforms.js 소유). 이 모듈은 "뷰포트" 계층만 소유한다:
+// - Space 홀드 / 휠버튼(중클릭) / 손 툴 = 뷰 팬 (wirePan)
+// - 커서 앵커 줌 헬퍼 (keepViewAnchor) + 콘텐츠 중앙 정렬 (centerView)
+// - 돋보기 −/+/맞춤 위젯 팩토리 (makeViewNavWidget — 뷰포트 우하단 + 툴바 공용)
+// 확대편집(줌 모달)·호흡 포커스·비교 캔버스 세 디테일뷰가 전부 이 모듈을 쓴다.
+
+// ── 뷰 내비 아이콘 (SVG 라인 아이콘 — 이모지 금지) ──
+// 돋보기 = "화면 배율" 전용 어휘. 스프라이트 크기 조절(transforms.js scale-scrub)은
+// 대각 리사이즈 아이콘을 쓴다 — 돋보기와 혼동 금지 (maintainer 지시 2026-07-20).
+const VIEW_ICONS = {
+ zoomIn: '<svg viewBox="0 0 16 16" width="13" height="13" aria-hidden="true">' +
+ '<circle cx="7" cy="7" r="4.4" fill="none" stroke="currentColor" stroke-width="1.4"/>' +
+ '<path d="M7 5.2v3.6M5.2 7h3.6" stroke="currentColor" stroke-width="1.2" stroke-linecap="round"/>' +
+ '<path d="M10.4 10.4 14 14" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"/></svg>',
+ zoomOut: '<svg viewBox="0 0 16 16" width="13" height="13" aria-hidden="true">' +
+ '<circle cx="7" cy="7" r="4.4" fill="none" stroke="currentColor" stroke-width="1.4"/>' +
+ '<path d="M5.2 7h3.6" stroke="currentColor" stroke-width="1.2" stroke-linecap="round"/>' +
+ '<path d="M10.4 10.4 14 14" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"/></svg>',
+ fit: '<svg viewBox="0 0 16 16" width="13" height="13" aria-hidden="true">' +
+ '<path d="M5.5 2.5H2.5v3M10.5 2.5h3v3M5.5 13.5h-3v-3M10.5 13.5h3v-3" ' +
+ 'fill="none" stroke="currentColor" stroke-width="1.3" stroke-linecap="round" stroke-linejoin="round"/></svg>',
+};
+
+// ── 뷰 패닝 — Space+드래그 / 휠버튼(중클릭) 드래그 / 손 툴로 화면을 끈다 (maintainer 지시
+// 2026-07-17: 스프라이트 이동과 별개인 캔버스 시야 이동. 2026-07-19: 비교뷰에도 +
+// 손 툴 버튼 — Space 는 홀드형(누르는 동안만), 버튼은 토글형). 스크롤 컨테이너를
+// 당기는 방식이라 페인트/마키보다 먼저(capture) 가로챈다.
+let panSpaceHeld = false;
+
+document.addEventListener("keydown", (ev) => {
+ if (ev.code !== "Space") return;
+ if (!document.getElementById("zoom-modal") && !document.getElementById("compare-modal")) return;
+ // 버튼은 가드에서 제외 — 마지막 클릭한 버튼에 포커스가 남아도 Space=팬이 이긴다
+ // (포토샵 계약; 버튼 재발동 사고도 같이 막힘). 타이핑 필드만 존중.
+ if (ev.target && ev.target.closest && ev.target.closest("input, textarea, select")) return;
+ panSpaceHeld = true;
+ document.body.classList.add("pan-space");
+ ev.preventDefault();
+});
+
+document.addEventListener("keyup", (ev) => {
+ if (ev.code !== "Space") return;
+ panSpaceHeld = false;
+ document.body.classList.remove("pan-space");
+});
+
+function wirePan(surface, container, isToolActive) {
+ surface.addEventListener("pointerdown", (ev) => {
+ const toolOn = isToolActive && isToolActive();
+ if (!(ev.button === 1 || (ev.button === 0 && (panSpaceHeld || toolOn)))) return;
+ ev.preventDefault();
+ ev.stopImmediatePropagation();
+ const sx = ev.clientX, sy = ev.clientY;
+ const sl = container.scrollLeft, st = container.scrollTop;
+ const prevCursor = surface.style.cursor;
+ surface.style.cursor = "grabbing";
+ const onMove = (e2) => {
+ container.scrollLeft = sl - (e2.clientX - sx);
+ container.scrollTop = st - (e2.clientY - sy);
+ };
+ const onUp = () => {
+ window.removeEventListener("pointermove", onMove);
+ window.removeEventListener("pointerup", onUp);
+ surface.style.cursor = prevCursor;
+ };
+ window.addEventListener("pointermove", onMove);
+ window.addEventListener("pointerup", onUp);
+ }, true);
+}
+
+// 콘텐츠 중앙을 뷰포트 중앙으로 (모달 오픈 직후 / 맞춤 버튼)
+function centerView(viewport, content) {
+ const vr = viewport.getBoundingClientRect();
+ const cr = content.getBoundingClientRect();
+ viewport.scrollLeft += (cr.left + cr.width / 2) - (vr.left + vr.width / 2);
+ viewport.scrollTop += (cr.top + cr.height / 2) - (vr.top + vr.height / 2);
+}
+
+// 커서 앵커 줌: apply() 가 콘텐츠 크기를 바꾼 뒤에도 (clientX, clientY) 아래에
+// 있던 콘텐츠 지점이 그대로 그 자리에 남게 뷰포트 스크롤을 보정한다.
+// 좌표 인자가 없으면 뷰포트 중앙 기준 (버튼 줌 경로).
+function keepViewAnchor(viewport, content, clientX, clientY, apply) {
+ const vr = viewport.getBoundingClientRect();
+ const ax = clientX === null || clientX === undefined ? vr.left + vr.width / 2 : clientX;
+ const ay = clientY === null || clientY === undefined ? vr.top + vr.height / 2 : clientY;
+ const cr = content.getBoundingClientRect();
+ const fx = cr.width ? (ax - cr.left) / cr.width : 0.5;
+ const fy = cr.height ? (ay - cr.top) / cr.height : 0.5;
+ apply();
+ const cr2 = content.getBoundingClientRect();
+ viewport.scrollLeft += (cr2.left + fx * cr2.width) - ax;
+ viewport.scrollTop += (cr2.top + fy * cr2.height) - ay;
+}
+
+// 돋보기 −/+/맞춤 위젯 — 뷰포트 우하단 오버레이와 툴바가 같은 팩토리를 쓴다.
+// handlers: { zoomOut(), zoomIn(), fit() } — 라벨 갱신은 반환 요소의 .vn-label 로.
+function makeViewNavWidget(handlers, opts) {
+ const wrap = document.createElement("span");
+ wrap.className = "view-nav" + (opts && opts.corner ? " vn-corner" : "");
+ const mkBtn = (cls, icon, tip, fn) => {
+ const b = document.createElement("button");
+ b.type = "button";
+ b.className = `ghost ${cls}`;
+ b.innerHTML = icon;
+ b.setAttribute("data-tip", tip);
+ b.addEventListener("click", fn);
+ // 더블클릭/포인터 계열이 스테이지(모달 열기·페인트)로 새지 않게 차단
+ for (const type of ["pointerdown", "dblclick"]) b.addEventListener(type, (ev) => ev.stopPropagation());
+ return b;
+ };
+ wrap.appendChild(mkBtn("vn-out", VIEW_ICONS.zoomOut, t("tViewZoomOut"), handlers.zoomOut));
+ const label = document.createElement("span");
+ label.className = "vn-label";
+ label.textContent = "100%";
+ wrap.appendChild(label);
+ wrap.appendChild(mkBtn("vn-in", VIEW_ICONS.zoomIn, t("tViewZoomIn"), handlers.zoomIn));
+ if (handlers.fit) wrap.appendChild(mkBtn("vn-fit", VIEW_ICONS.fit, t("tViewZoomFit"), handlers.fit));
+ return wrap;
+}
diff --git a/sprite_gen/serve/curator/src/zones.js b/sprite_gen/serve/curator/src/zones.js
new file mode 100644
index 0000000..3f70d79
--- /dev/null
+++ b/sprite_gen/serve/curator/src/zones.js
@@ -0,0 +1,420 @@
+// SPDX-License-Identifier: Apache-2.0
+// curator/zones.js — 2존 큐레이션 (시퀀스/후보 풀) — 순서·이동·복제·보관함
+// 로드 순서 SSoT = index.html (classic script 전역 어휘 공유; 빌드 스텝 없음)
+
+function presentCards(container) {
+ return [...container.querySelectorAll(".card:not(.missing)")];
+}
+
+function zoneFrames(wrap) {
+ return { seq: wrap.querySelector(".seq-frames"), pool: wrap.querySelector(".pool-frames") };
+}
+
+// selection := membership of the sequence row. order := seq cards then pool
+// cards, so playList() (order ∩ sel) is exactly the sequence row, left to right.
+function commitZones(wrap, stateName) {
+ const { seq, pool } = zoneFrames(wrap);
+ const seqIdx = presentCards(seq).map((c) => Number(c.dataset.idx));
+ const poolIdx = presentCards(pool).map((c) => Number(c.dataset.idx));
+ // keep not-yet-extracted (missing) frames in order so their slot survives a
+ // reorder — if extraction later fills them in, they aren't silently dropped.
+ const state = run.states.find((s) => s.name === stateName);
+ const archivedSet = new Set(entries[stateName].archived || []);
+ const missingIdx = state ? state.frames.filter((f) => !f.present && !archivedSet.has(f.index)).map((f) => f.index) : [];
+ // 카드 없이 존재하는 프레임(예: 토글 OFF 로 풀에서 숨긴 호흡 위상)도 order 에
+ // 보존한다 — DOM 은 표시의 부분집합이지 인스턴스 진실이 아니다.
+ const seen = new Set([...seqIdx, ...poolIdx]);
+ const hiddenIdx = state
+ ? state.frames.filter((f) => f.present && !seen.has(f.index) && !archivedSet.has(f.index)).map((f) => f.index)
+ : [];
+ entries[stateName].sel = new Set(seqIdx);
+ entries[stateName].order = [...seqIdx, ...poolIdx, ...hiddenIdx, ...missingIdx];
+}
+
+// the present card the dragged card should be inserted *before*, by pointer x
+// within one row. null -> after them all.
+function reorderRefBefore(container, dragCard, x) {
+ let ref = null;
+ let closest = -Infinity;
+ for (const card of presentCards(container)) {
+ if (card === dragCard) continue;
+ const box = card.getBoundingClientRect();
+ const offset = x - (box.left + box.width / 2);
+ if (offset < 0 && offset > closest) {
+ closest = offset;
+ ref = card;
+ }
+ }
+ return ref;
+}
+
+// pick the row (seq above, pool below) whose band the cursor y falls into.
+function pickZone(seq, pool, y) {
+ const s = seq.getBoundingClientRect();
+ const p = pool.getBoundingClientRect();
+ return y < (s.bottom + p.top) / 2 ? seq : pool;
+}
+
+// FLIP across both rows: measure (First), reorder DOM (mutate), then invert +
+// Play in 2D so cards slide — including vertically when they cross rows —
+// since flexbox reflow can't be animated by CSS transitions alone.
+function flipReorder(containers, mutate) {
+ // exclude .missing (inert, not interactive) so unextracted slots don't animate
+ const cards = containers.flatMap((c) => [...c.querySelectorAll(".card:not(.dragging):not(.missing)")]);
+ const first = cards.map((c) => {
+ const b = c.getBoundingClientRect();
+ return { l: b.left, t: b.top };
+ });
+ mutate();
+ // pass 1: apply the inverted transform with no transition
+ const moved = [];
+ cards.forEach((c, i) => {
+ const b = c.getBoundingClientRect();
+ const dl = first[i].l - b.left;
+ const dt = first[i].t - b.top;
+ if (Math.abs(dl) < 0.5 && Math.abs(dt) < 0.5) return;
+ c.style.transition = "none";
+ c.style.transform = `translate(${dl}px, ${dt}px)`;
+ moved.push(c);
+ });
+ if (!moved.length) return;
+ // single forced reflow commits the inverted positions across all moved cards;
+ // a bare requestAnimationFrame is not reliable on Safari/Firefox (the inverted
+ // frame may not paint before the transition is enabled, so cards teleport).
+ void moved[0].offsetWidth;
+ // pass 2: enable the transition and release to home -> they slide
+ for (const c of moved) {
+ c.style.transition = "transform 0.18s ease";
+ c.style.transform = "";
+ }
+}
+
+// click affordance: send a card to the other row (sequence <-> pool), animated.
+function moveCardToOtherZone(card, stateName) {
+ const wrap = card.closest(".state");
+ const { seq, pool } = zoneFrames(wrap);
+ const dest = card.closest(".frames") === seq ? pool : seq;
+ flipReorder([seq, pool], () => dest.appendChild(card));
+ commitZones(wrap, stateName);
+ renderSelectionState(stateName);
+ if (previews[stateName] && previews[stateName].refresh) previews[stateName].refresh();
+ scheduleSave();
+}
+
+// The card header (`.card-top` = the title strip) is the drag handle: grab the
+// title anywhere and move past DRAG_THRESHOLD to reorder within a row or move it
+// between the sequence/pool rows. A press that never moves is a plain click and
+// does NOTHING (maintainer 2026-07-15): toggling sequence ⇄ pool is only the 넣기/빼기
+// button or a drop, so a stray click can't silently add/remove a frame.
+function wireReorder(handle, card, wrap, stateName) {
+ handle.addEventListener("pointerdown", (ev) => {
+ if (ev.button || !ev.isPrimary) return; // primary button + primary pointer only (no multi-touch parallel drag)
+ ev.preventDefault();
+ const { seq, pool } = zoneFrames(wrap);
+ const startX = ev.clientX;
+ const startY = ev.clientY;
+ let lifted = false;
+ let ph = null;
+ let grabDX = 0;
+ let grabDY = 0;
+
+ const moveCard = (x, y) => {
+ card.style.left = `${x - grabDX}px`;
+ card.style.top = `${y - grabDY}px`;
+ };
+
+ // lift the card out of flow so it floats under the cursor; a placeholder of
+ // the same size holds the slot it will drop into (in its current row). Only
+ // happens once the press crosses DRAG_THRESHOLD, so a plain click never lifts.
+ const lift = () => {
+ const rect = card.getBoundingClientRect();
+ grabDX = startX - rect.left;
+ grabDY = startY - rect.top;
+ ph = document.createElement("div");
+ ph.className = "card-placeholder";
+ ph.style.width = `${rect.width}px`;
+ ph.style.height = `${rect.height}px`;
+ card.parentNode.insertBefore(ph, card);
+ card.classList.add("dragging");
+ card.style.width = `${rect.width}px`;
+ card.style.height = `${rect.height}px`;
+ card.style.position = "fixed";
+ card.style.zIndex = "1000";
+ card.style.pointerEvents = "none";
+ lifted = true;
+ };
+
+ // listeners on window (not the handle): once lifted the card is fixed/detached
+ // from flow, so a handle-scoped pointerup could be missed — window catches the
+ // release anywhere.
+ const onMove = (e) => {
+ if (!lifted) {
+ if (Math.abs(e.clientX - startX) <= DRAG_THRESHOLD && Math.abs(e.clientY - startY) <= DRAG_THRESHOLD) return;
+ lift();
+ }
+ moveCard(e.clientX, e.clientY);
+ const zone = pickZone(seq, pool, e.clientY);
+ const firstMissing = zone.querySelector(".card.missing");
+ const refNode = reorderRefBefore(zone, card, e.clientX) || firstMissing;
+ if (ph.parentNode === zone && (ph.nextElementSibling === refNode || refNode === ph)) return;
+ flipReorder([seq, pool], () => zone.insertBefore(ph, refNode));
+ };
+ const end = (evUp) => {
+ window.removeEventListener("pointermove", onMove);
+ window.removeEventListener("pointerup", end);
+ window.removeEventListener("pointercancel", end);
+ if (!lifted) {
+ // 임계값을 넘지 않은 순수 클릭 — 아무 것도 하지 않는다. 시퀀스⇄풀 이동은
+ // 넣기/빼기 버튼(sel-btn)이나 드롭으로만 (maintainer 2026-07-15).
+ return;
+ }
+ // 보관함 칩 위에서 놓으면 보관 (풀에서도 제외)
+ const chip = wrap.querySelector(".archive-chip");
+ if (chip && evUp && typeof evUp.clientX === "number") {
+ const r = chip.getBoundingClientRect();
+ if (evUp.clientX >= r.left && evUp.clientX <= r.right && evUp.clientY >= r.top && evUp.clientY <= r.bottom) {
+ ph.remove();
+ card.remove();
+ archiveFrame(stateName, Number(card.dataset.idx));
+ return;
+ }
+ }
+ const fromRect = card.getBoundingClientRect();
+ card.classList.remove("dragging");
+ card.style.position = card.style.left = card.style.top = "";
+ card.style.width = card.style.height = card.style.zIndex = card.style.pointerEvents = "";
+ ph.parentNode.insertBefore(card, ph);
+ ph.remove();
+ // settle: slide the dropped card from the release point into its slot.
+ const toRect = card.getBoundingClientRect();
+ const dx = fromRect.left - toRect.left;
+ const dy = fromRect.top - toRect.top;
+ if (dx || dy) {
+ card.style.transition = "none";
+ card.style.transform = `translate(${dx}px, ${dy}px)`;
+ void card.offsetWidth; // commit before enabling transition (Safari/Firefox safe)
+ card.style.transition = "transform 0.16s ease";
+ card.style.transform = "";
+ }
+ commitZones(wrap, stateName);
+ renderSelectionState(stateName); // refresh selection classes + count
+ if (previews[stateName] && previews[stateName].refresh) previews[stateName].refresh();
+ scheduleSave();
+ };
+ window.addEventListener("pointermove", onMove);
+ window.addEventListener("pointerup", end);
+ window.addEventListener("pointercancel", end);
+ });
+}
+
+// 상태 섹션 in-place 재구성 (보관/복구 후) — 위치 보존
+function rebuildState(stateName) {
+ const st = run.states.find((s) => s.name === stateName);
+ const old = document.querySelector(`.state[data-state="${cssEscape(stateName)}"]`);
+ if (!st || !old) return;
+ // 스크롤 보존: 섹션 통째 교체가 페이지/행 가로 스크롤을 튀게 하면 안 된다 —
+ // 이전 높이를 잠깐 고정해(이미지 로드 전 수축 방지) 페이지 위치를 지키고,
+ // 가로 스크롤된 자식은 클래스 기준으로 위치를 복원한다.
+ const pageY = document.scrollingElement ? document.scrollingElement.scrollTop : window.scrollY;
+ const hScrolls = [...old.querySelectorAll("*")]
+ .filter((el) => el.scrollLeft > 0 && typeof el.className === "string" && el.className.trim())
+ .map((el) => ({ sel: "." + el.className.trim().split(/\s+/).join("."), left: el.scrollLeft }));
+ const oldH = old.getBoundingClientRect().height;
+ renderState(st, old); // old 자리에 교체 렌더
+ const nu = document.querySelector(`.state[data-state="${cssEscape(stateName)}"]`);
+ if (nu) {
+ nu.style.minHeight = `${oldH}px`;
+ setTimeout(() => { nu.style.minHeight = ""; }, 600);
+ for (const rec of hScrolls) {
+ const el = nu.querySelector(rec.sel);
+ if (el) el.scrollLeft = rec.left;
+ }
+ }
+ if (document.scrollingElement) document.scrollingElement.scrollTop = pageY;
+ else window.scrollTo(window.scrollX, pageY);
+}
+
+function archiveFrame(stateName, idx) {
+ const e = entries[stateName];
+ e.sel.delete(idx);
+ e.order = e.order.filter((i) => i !== idx);
+ if (cloneSrc(stateName, idx) !== null) {
+ // 복제 인스턴스는 보관함에 넣지 않고 완전히 제거한다 — 원본이 살아 있으니
+ // 언제든 다시 복제하면 되고, 보관함에 사본이 쌓이는 건 혼란만 준다.
+ delete e.clones[idx];
+ delete e.transforms[idx];
+ delete e.pixels[idx];
+ if (e.unlinked) e.unlinked.delete(idx);
+ } else if (!e.archived.includes(idx)) {
+ e.archived.push(idx);
+ }
+ scheduleSave();
+ rebuildState(stateName);
+}
+
+// 프레임 복제: 원본 카드 바로 뒤에, 같은 존(시퀀스/풀)으로, 현재 변형·픽셀편집을
+// 복사한 새 인스턴스를 만든다. 복제의 복제도 원본 프레임으로 평탄화해 기록한다.
+function duplicateFrame(stateName, idx) {
+ const e = entries[stateName];
+ const st = run.states.find((s) => s.name === stateName);
+ if (!st) return;
+ e.clones = e.clones || {};
+ const used = [
+ ...st.frames.map((f) => f.index),
+ ...Object.keys(e.clones).map(Number),
+ ...e.order,
+ ...e.archived,
+ ];
+ const newIdx = Math.max(-1, ...used) + 1;
+ const src = cloneSrc(stateName, idx) ?? idx;
+ e.clones[newIdx] = src;
+ // 링크 기본 (maintainer 확정 2026-07-18): 복제는 원본 편집 truth 를 공유한다 —
+ // 변형/픽셀을 복사하지 않는다. 독립은 '링크 끊기' 로만.
+ const pos = e.order.indexOf(idx);
+ e.order.splice(pos < 0 ? e.order.length : pos + 1, 0, newIdx);
+ if (e.sel.has(idx)) e.sel.add(newIdx);
+ scheduleSave();
+ rebuildState(stateName);
+}
+
+function restoreFrame(stateName, idx, toSequence) {
+ const e = entries[stateName];
+ e.archived = e.archived.filter((i) => i !== idx);
+ if (!e.order.includes(idx)) e.order.push(idx);
+ if (toSequence) e.sel.add(idx);
+ else e.sel.delete(idx);
+ scheduleSave();
+ rebuildState(stateName);
+}
+
+function renderSelectionState(stateName) {
+ document.querySelectorAll(`.card[data-state="${cssEscape(stateName)}"]`).forEach((card) => {
+ if (card.classList.contains("missing")) return;
+ const idx = Number(card.dataset.idx);
+ const inSeq = isSelected(stateName, idx);
+ card.classList.toggle("selected", inSeq);
+ const btn = card.querySelector(".sel-btn");
+ if (btn) {
+ // 아이콘(방향) + 라벨. 색상 강조 없이 방향 화살표로 넣기/빼기를 구분.
+ btn.innerHTML = (inSeq ? SEL_ICON.remove : SEL_ICON.add) +
+ `<span>${inSeq ? t("removeFromSeq") : t("addToSeq")}</span>`;
+ btn.setAttribute("data-tip", inSeq ? t("tSelRemove") : t("tSelAdd"));
+ }
+ });
+ const state = run.states.find((s) => s.name === stateName);
+ const countEl = document.querySelector(`.preview[data-state="${cssEscape(stateName)}"] .count`);
+ if (countEl) countEl.textContent = STR[lang].seqCount(entries[stateName].sel.size, state.requestFrames);
+}
+
+function renderArchive(state) {
+ const e = entries[state.name];
+ const wrap = document.createElement("div");
+ wrap.className = "archive-wrap";
+ const chip = document.createElement("button");
+ chip.type = "button";
+ chip.className = "ghost archive-chip";
+ chip.setAttribute("data-tip", t("tArchiveChip"));
+ chip.innerHTML =
+ '<svg viewBox="0 0 16 16" width="12" height="12" aria-hidden="true">' +
+ '<path d="M1.5 3h13v3h-13zM2.5 6v6.5A1 1 0 0 0 3.5 13.5h9a1 1 0 0 0 1-1V6M6 8.5h4" ' +
+ 'fill="none" stroke="currentColor" stroke-width="1.2" stroke-linejoin="round"/></svg>' +
+ `<span>${STR[lang].archiveChip(e.archived.length)}</span>`;
+ chip.addEventListener("click", () => {
+ if (e.archived.length) openArchiveModal(state.name);
+ });
+ wrap.appendChild(chip);
+ if (e.archived.length === 0) wrap.classList.add("empty");
+ return wrap;
+}
+
+// 보관함 풀 모달 — 일반 카드 크기로 크게 보고 버튼으로 복구 (팝오버 대체, UX)
+function openArchiveModal(stateName) {
+ document.getElementById("archive-modal")?.remove();
+ const state = run.states.find((s) => s.name === stateName);
+ const e = entries[stateName];
+ if (!state || !e.archived.length) return;
+ const modal = document.createElement("div");
+ modal.id = "archive-modal";
+ modal.innerHTML =
+ `<div class="zoom-backdrop"></div>` +
+ `<div class="card arch-modal-card">` +
+ `<div class="zoom-head"><span class="zoom-title">${STR[lang].archModalTitle(escapeHtml(stateName), e.archived.length)}</span>` +
+ `<button type="button" class="ghost zoom-close">${t("zoomClose")}</button></div>` +
+ `<div class="arch-grid"></div></div>`;
+ const grid = modal.querySelector(".arch-grid");
+ const frameByIdx = new Map(state.frames.map((f) => [f.index, f]));
+ for (const idx of e.archived) {
+ const f = frameByIdx.get(idx);
+ if (!f) continue;
+ const cardEl = document.createElement("div");
+ cardEl.className = "card arch-card";
+ cardEl.style.setProperty("--cell-aspect", run.cell.width / run.cell.height);
+ cardEl.innerHTML =
+ `<div class="card-top"><span class="idx">${f.label ? escapeHtml(f.label) : `#${idx}`}</span></div>` +
+ `<div class="stage">` +
+ (f.present ? `<img src="${escapeHtml(frameUrl(stateName, f))}" draggable="false" />` : `<div class="missing-label">${t("missingPending")}</div>`) +
+ `</div>` +
+ `<div class="card-controls">` +
+ `<button type="button" class="ghost ar-seq">${t("restoreToSeq")}</button>` +
+ `<button type="button" class="ghost ar-pool">${t("restoreToPool")}</button>` +
+ `</div>`;
+ const restore = (toSeq) => {
+ restoreFrame(stateName, idx, toSeq);
+ if (entries[stateName].archived.length) openArchiveModal(stateName);
+ else close();
+ };
+ cardEl.querySelector(".ar-seq").addEventListener("click", () => restore(true));
+ cardEl.querySelector(".ar-pool").addEventListener("click", () => restore(false));
+ grid.appendChild(cardEl);
+ }
+ const close = () => {
+ modal.remove();
+ document.removeEventListener("keydown", onKey);
+ };
+ const onKey = (ev) => { if (ev.key === "Escape") close(); };
+ modal.querySelector(".zoom-close").addEventListener("click", close);
+ modal.querySelector(".zoom-backdrop").addEventListener("click", close);
+ document.addEventListener("keydown", onKey);
+ document.body.appendChild(modal);
+}
+
+// 팝오버 미니카드를 끌어내// 팝오버 미니카드를 끌어내 시퀀스/후보 존에 떨어뜨리면 복구
+function wireArchiveRestoreDrag(mini, stateName, idx) {
+ mini.addEventListener("pointerdown", (ev) => {
+ if (ev.button || !ev.isPrimary) return;
+ ev.preventDefault();
+ const startX = ev.clientX;
+ const startY = ev.clientY;
+ let ghost = null;
+ const onMove = (e2) => {
+ if (!ghost) {
+ if (Math.abs(e2.clientX - startX) <= DRAG_THRESHOLD && Math.abs(e2.clientY - startY) <= DRAG_THRESHOLD) return;
+ ghost = mini.cloneNode(true);
+ ghost.classList.add("ap-ghost");
+ document.body.appendChild(ghost);
+ }
+ ghost.style.left = `${e2.clientX + 8}px`;
+ ghost.style.top = `${e2.clientY + 8}px`;
+ };
+ const end = (e2) => {
+ window.removeEventListener("pointermove", onMove);
+ window.removeEventListener("pointerup", end);
+ window.removeEventListener("pointercancel", end);
+ if (!ghost) return; // 클릭만 한 것 — 아무 일 없음
+ ghost.remove();
+ const sectionSel = `.state[data-state="${cssEscape(stateName)}"]`;
+ const seq = document.querySelector(`${sectionSel} .seq-frames`);
+ const pool = document.querySelector(`${sectionSel} .pool-frames`);
+ const over = (el) => {
+ if (!el) return false;
+ const r = el.getBoundingClientRect();
+ return e2.clientX >= r.left && e2.clientX <= r.right && e2.clientY >= r.top && e2.clientY <= r.bottom;
+ };
+ if (over(seq)) restoreFrame(stateName, idx, true);
+ else if (over(pool)) restoreFrame(stateName, idx, false);
+ };
+ window.addEventListener("pointermove", onMove);
+ window.addEventListener("pointerup", end);
+ window.addEventListener("pointercancel", end);
+ });
+}
diff --git a/sprite_gen/serve/curator/src/zoom-editor.js b/sprite_gen/serve/curator/src/zoom-editor.js
new file mode 100644
index 0000000..cdc5a95
--- /dev/null
+++ b/sprite_gen/serve/curator/src/zoom-editor.js
@@ -0,0 +1,1405 @@
+// SPDX-License-Identifier: Apache-2.0
+// curator/zoom-editor.js — 확대 편집 모달 — 픽셀 편집·팔레트·마키·팬·실행취소 + 호흡 포커스 모드
+// 로드 순서 SSoT = index.html (classic script 전역 어휘 공유; 빌드 스텝 없음)
+
+// 같은 entries/transform truth 를 쓰므로 모달 편집이 그리드 카드에 실시간 반영된다.
+// 휠/핀치 = 화면 배율(뷰 확대), 드래그/핸들/Shift+휠 = 기존 스프라이트 편집 그대로.
+let zoomView = null; // { stateName, idx, width }
+
+// 마지막 사용 펜 색 — 프레임/모달을 넘어가도 유지 (maintainer 2026-07-18 "스포이드로
+// 찍은 색으로 다음 프레임에 찍고 싶다"). 리로드에도 남게 localStorage 백업.
+let lastPenColor = null;
+try { lastPenColor = localStorage.getItem("sg-pen-color"); } catch { /* 무시 */ }
+function rememberPenColor(hex) {
+ if (!hex) return;
+ lastPenColor = hex;
+ try { localStorage.setItem("sg-pen-color", hex); } catch { /* 무시 */ }
+}
+
+function closeZoom() {
+ if (zoomView && zoomView.cleanupBreathe) zoomView.cleanupBreathe();
+ pixelEdit = null;
+ const modal = document.getElementById("zoom-modal");
+ if (modal) modal.remove();
+ zoomView = null;
+ document.removeEventListener("keydown", onZoomKey);
+}
+
+// ── 공용 툴 아이콘 (SVG 라인 아이콘 — 이모지 금지, 양 편집기 공용) ──
+const TOOL_ICONS = {
+ pen: '<svg viewBox="0 0 16 16" width="13" height="13" aria-hidden="true"><path d="m2 14 .8-3.2L11 2.6l2.4 2.4L5.2 13.2 2 14z" fill="none" stroke="currentColor" stroke-width="1.3" stroke-linejoin="round"/></svg>',
+ eraser: '<svg viewBox="0 0 16 16" width="13" height="13" aria-hidden="true"><path d="M9.5 2.5 2.8 9.2a1 1 0 0 0 0 1.4l2.6 2.6h4.1l4-4a1 1 0 0 0 0-1.4L9.5 2.5zM5.5 13.2 9.9 8.8" fill="none" stroke="currentColor" stroke-width="1.3" stroke-linejoin="round"/></svg>',
+ pick: '<svg viewBox="0 0 16 16" width="13" height="13" aria-hidden="true"><path d="M10.6 2a1.9 1.9 0 0 1 2.7 2.7l-1 1 .5.5-1.1 1.1-.5-.5-4.3 4.3-2.4.6.6-2.4 4.3-4.3-.5-.5L10 6.4l-.5-.5 1.1-1.1.5.5 1-1z" fill="none" stroke="currentColor" stroke-width="1.15" stroke-linejoin="round"/></svg>',
+ select: '<svg viewBox="0 0 16 16" width="13" height="13" aria-hidden="true"><rect x="2.5" y="2.5" width="11" height="11" fill="none" stroke="currentColor" stroke-width="1.2" stroke-dasharray="2.4 1.7"/></svg>',
+ transform: '<svg viewBox="0 0 16 16" width="13" height="13" aria-hidden="true"><path d="M4 1.8 12.6 8.4H8.2l-1.1 4.9L4 1.8z" fill="currentColor" stroke="currentColor" stroke-width="1.1" stroke-linejoin="round"/></svg>',
+ lasso: LASSO_ICON,
+ hand: '<svg viewBox="0 0 16 16" width="13" height="13" aria-hidden="true"><path d="M5.3 8V3.8a.95.95 0 0 1 1.9 0V7m0-3.9v-.6a.95.95 0 0 1 1.9 0V7m0-3.3a.95.95 0 0 1 1.9 0V7.8m0-2.3a.95.95 0 0 1 1.9 0v3.7c0 2.9-1.8 4.7-4.5 4.7-2.1 0-3.1-.9-4.2-2.5L3 9.9c-.5-.8-.3-1.6.4-2 .6-.4 1.3-.2 1.7.4z" fill="none" stroke="currentColor" stroke-width="1.2" stroke-linejoin="round" stroke-linecap="round"/></svg>',
+};
+
+// 뷰 패닝/커서 앵커 줌/돋보기 위젯 = view-nav.js 공용 (wirePan, keepViewAnchor,
+// centerView, makeViewNavWidget — 확대편집·호흡 포커스·비교뷰 세 디테일뷰 공유).
+
+function clearMarquee() {
+ if (pixelEdit) pixelEdit.sel = null;
+ document.querySelectorAll(".lasso-mask").forEach((el) => el.parentNode && el.parentNode.removeChild(el));
+ document.querySelectorAll(".marquee").forEach((m) => { m.hidden = true; });
+}
+
+// 툴 단축키 (포토샵 표준, maintainer 지시 2026-07-18): B/P=펜, E=지우개, I=스포이드, M=선택(마키).
+// 열려 있는 편집 툴바(줌/베이스 모달)에만 적용 — 입력 필드 포커스 중엔 무시.
+// 같은 툴 키 재입력 = 툴 끔 (버튼 재클릭과 동일 거동).
+// ev.code (물리 키) 기준 — 한글 IME/타 레이아웃에서도 동작 (ev.key 는 한글 모드에서
+// "ㅠ" 같은 조합 문자가 와 매칭이 죽는다 — 회귀 2026-07-19 maintainer).
+const TOOL_SHORTCUTS = { KeyV: ".et-transform", KeyL: ".et-lasso", KeyB: ".et-pen", KeyP: ".et-pen", KeyE: ".et-eraser", KeyI: ".et-pick", KeyM: ".et-select", KeyH: ".et-hand" };
+document.addEventListener("keydown", (ev) => {
+ if (ev.metaKey || ev.ctrlKey || ev.altKey) return;
+ const sel = TOOL_SHORTCUTS[ev.code];
+ if (!sel) return;
+ const a = document.activeElement;
+ if (a && (a.tagName === "INPUT" || a.tagName === "TEXTAREA" || a.isContentEditable)) return;
+ const bars = [...document.querySelectorAll(".edit-toolbar")].filter((el) => el.offsetParent !== null);
+ const btn = bars.length ? bars[bars.length - 1].querySelector(sel) : null;
+ if (btn) { ev.preventDefault(); btn.click(); }
+});
+
+function onZoomKey(ev) {
+ if (ev.key === "Escape") {
+ if (pixelEdit && pixelEdit.sel) { clearMarquee(); return; } // 선택 해제가 우선
+ if (zoomView && zoomView.breatheCancel) zoomView.breatheCancel(); // Esc = 호흡 적용 취소
+ closeZoom();
+ }
+ else if (ev.key === "ArrowLeft") stepZoomFrame(-1);
+ else if (ev.key === "ArrowRight") stepZoomFrame(1);
+}
+
+// 실행취소/재실행 단축키 — Cmd/Ctrl+Z, Cmd/Ctrl+Shift+Z (maintainer 지시 2026-07-17).
+// 활성 편집 컨텍스트로 라우팅: 베이스 에디터 모달이 열려 있으면 그쪽, 아니면
+// 줌 모달의 픽셀 편집 세션. 입력 필드에선 브라우저 기본 동작 유지.
+document.addEventListener("keydown", (ev) => {
+ // ev.code 기준 — 한글 IME 에서도 Cmd/Ctrl+Z 동작 (key 는 "ㅋ" 이 온다)
+ if (ev.code !== "KeyZ" || !(ev.metaKey || ev.ctrlKey)) return;
+ if (ev.target && ev.target.closest && ev.target.closest("input, textarea, select")) return;
+ // 베이스도 줌 모달(pixelEdit)로 통일 — 별도 에디터 분기는 폐기됨 (v1.56.24)
+ // 호흡 포커스 모드가 열려 있으면 선/진폭/주기 조정 히스토리가 우선이다 (maintainer 2026-07-17)
+ // 셋째 폴백 = 변형 히스토리 (maintainer 2026-07-20 "캐릭터 이동한 담에 Cmd+Z 안 먹혀"):
+ // 픽셀 툴이 꺼져 있으면 이동/회전/스케일/플립 제스처를 되돌린다 — 모달·그리드 공통.
+ // 변형 툴은 픽셀을 안 찍으므로 **"픽셀 툴 꺼짐" 과 같게** 라우팅한다. 안 그러면
+ // 변형 툴이 기본 활성이 된 뒤로 항상 undoPixel 로 가고 저널이 비어 조용히 아무 일도
+ // 안 일어난다 — 2026-07-20 maintainer 신고("캐릭터 이동한 담에 Cmd+Z 안 먹혀")의 재발이다
+ // (노을이 기각 R3 2026-07-26). 단 변형 툴로 **영역 변형을 구운 뒤**엔 픽셀 저널이
+ // 차므로 그때는 픽셀 undo 가 맞다 — 저널 유무로 가른다.
+ const pixelUndoable = pixelEdit && pixelEdit.undoFn
+ && ((pixelEdit.tool !== "transform" && pixelEdit.tool !== "lasso")
+ || (pixelEdit.journal && pixelEdit.journal.length));
+ const target = zoomView && zoomView.breatheUndo
+ ? { undo: zoomView.breatheUndo, redo: zoomView.breatheRedo }
+ : (pixelUndoable
+ ? { undo: pixelEdit.undoFn, redo: pixelEdit.redoFn }
+ : { undo: undoTransform, redo: redoTransform });
+ ev.preventDefault();
+ ev.stopImmediatePropagation();
+ if (ev.shiftKey) { if (target.redo) target.redo(); }
+ else if (target.undo) target.undo();
+}, true);
+
+function stepZoomFrame(delta) {
+ if (!zoomView || zoomView.stateName === BASE_STATE) return; // 베이스 = 단일 뷰
+ if (zoomView.breatheMode) return; // 호흡 포커스 모드: 프레임 이동 없음
+ // 표시 순서(order)를 따라 넘긴다 — 복제 인스턴스 카드도 순회에 포함
+ const e = entries[zoomView.stateName];
+ const present = e.order.filter((i) => {
+ const f = frameOf(zoomView.stateName, i);
+ return f && f.present;
+ });
+ if (!present.length) return;
+ const pos = present.indexOf(zoomView.idx);
+ openZoom(zoomView.stateName, present[(pos + delta + present.length) % present.length], zoomView.width);
+}
+
+function openZoom(stateName, idx, keepWidth) {
+ closeZoom();
+ const frame = frameOf(stateName, idx); // 복제 인스턴스 → 원본 이미지, 자기 변형
+ if (!frame || !frame.present) return;
+ const isBase = stateName === BASE_STATE; // 베이스도 같은 컴포넌트로 연다 (maintainer 지시 2026-07-17)
+ // 링크된 복제는 원본 프레임의 편집 세션을 연다 (편집 truth = 원본 하나, maintainer 2026-07-18)
+ if (!isBase) idx = editIndex(stateName, idx);
+ const [cellW, cellH] = cellDims(stateName);
+ const aspect = cellH / cellW;
+ const width = keepWidth
+ || Math.min(Math.floor(window.innerWidth * 0.8), Math.floor((window.innerHeight * 0.72) / aspect));
+ zoomView = { stateName, idx, width };
+
+ const modal = document.createElement("div");
+ modal.id = "zoom-modal";
+ const label = frame.clone !== undefined
+ ? `⧉ ${escapeHtml(STR[lang].cloneBadge(frame.clone))}`
+ : (frame.label ? escapeHtml(frame.label) : `#${idx}`);
+ modal.innerHTML =
+ `<div class="zoom-backdrop"></div>` +
+ `<div class="card zoom-card" data-state="${escapeHtml(stateName)}" data-idx="${idx}">` +
+ `<div class="zoom-head">` +
+ `<span class="zoom-title">${escapeHtml(isBase ? "base" : stateName)}${isBase ? ` · ${cellW}×${cellH}` : ` · ${label}`}</span>` +
+ `<span class="row-controls"></span>` +
+ (isBase ? "" :
+ `<button type="button" class="ghost zoom-prev" data-tip="${t("tZoomPrev")}">⏮</button>` +
+ `<button type="button" class="ghost zoom-next" data-tip="${t("tZoomNext")}">⏭</button>`) +
+ `<button type="button" class="ghost zoom-close">${t("zoomClose")}</button>` +
+ `</div>` +
+ `<div class="stage" data-tip="${t("tZoomStage")}">` +
+ `<div class="pxgrid"></div>` +
+ `<canvas class="ingrid"></canvas>` +
+ `<img src="${escapeHtml(frameUrl(stateName, frame))}" alt="frame ${idx}" draggable="false" />` +
+ `<canvas class="snap-canvas"></canvas>` +
+ `<div class="rotate-handle" data-tip="${t("tRotate")}"></div>` +
+ `<div class="shear-handle" data-tip="${t("tShear")}"></div>` +
+ `</div>` +
+ `<div class="card-controls">` +
+ `<span class="psize" data-tip="${t("tContentPx")}">${frame.contentSize ? `${frame.contentSize[0]}x${frame.contentSize[1]}px` : ""}</span>` +
+ `<span class="tvals"></span>` +
+ `<button type="button" class="ghost flip-btn" data-tip="${t("tFlipX")}" aria-label="flip-x">${FLIP_X_ICON}</button>` +
+ `<button type="button" class="ghost reset-btn" data-tip="${t("tReset")}" aria-label="reset">${RESET_ICON}</button>` +
+ `</div>` +
+ `</div>`;
+ document.body.appendChild(modal);
+ // 오프너(줄 라벨/버튼)에 남은 포커스 해제 — Space 홀드 팬이 버튼 가드에 걸리지 않게
+ if (document.activeElement instanceof HTMLElement) document.activeElement.blur();
+
+ const card = modal.querySelector(".zoom-card");
+ card.style.setProperty("--cell-aspect", cellW / cellH);
+ const stage = card.querySelector(".stage");
+ stage.style.width = `${width}px`;
+
+ // 컨트롤: 줄별 토글과 같은 클래스 → sync*Controls 가 카드/모달을 함께 갱신
+ const controls = card.querySelector(".row-controls");
+ // 완전 동일 계약 (maintainer 지시 2026-07-17 "다 똑같이"): 픽셀 언페이크·격자·변형은
+ // 베이스에도 전부. 프레임 전용은 GIF/이전·다음(다중 프레임 개념)뿐.
+ controls.appendChild(makeGridToggle(stateName)); // 격자는 언제나 — 베이스·프레임 공통
+ controls.appendChild(makeUnfakeToggle(stateName)); // 퍼펙은 언제나 — 줄 컨트롤과 같은 계약
+ if (!isBase) {
+ controls.appendChild(makeGifButton(stateName));
+ // 보간 버튼은 줄 헤더 전용 — 확대뷰에선 카드 픽이 불가능해 쓸 수 없다 (maintainer 2026-07-17).
+ card.querySelector(".zoom-prev").addEventListener("click", () => stepZoomFrame(-1));
+ card.querySelector(".zoom-next").addEventListener("click", () => stepZoomFrame(1));
+ }
+ card.querySelector(".reset-btn").addEventListener("click", () => resetTransform(stateName, idx));
+ // 좌우반전 = 도구 조작 (연필/지우개/마키 이동과 같은 취급, maintainer 2026-07-19):
+ // 활성/비활성 상태가 아니라 누를 때마다 반전. 마키 선택이 있으면 그 영역 픽셀만
+ // 반전(픽셀 저널 스트로크 — Cmd+Z 로 되돌림), 없으면 프레임 전체(변형 flipX).
+ card.querySelector(".flip-btn").addEventListener("click", () => {
+ if (pixelEdit && pixelEdit.sel && pixelEdit.state === stateName && pixelEdit.idx === idx) {
+ flipSelectionX();
+ return;
+ }
+ toggleFlipX(stateName, idx);
+ });
+ stage.appendChild(makeScaleScrub(stateName, idx));
+ card.querySelector(".zoom-close").addEventListener("click", closeZoom);
+ modal.querySelector(".zoom-backdrop").addEventListener("click", closeZoom);
+ // Space 홀드/휠버튼 드래그 + 손 툴(토글) = 뷰 패닝 (프레임·베이스 공통) —
+ // 팬/줌 배선은 뷰포트 구성 뒤에 (아래 stage-viewport 블록).
+ let panTool = false;
+
+ // ── 픽셀 편집 툴바: 연필/지우개 + 프레임 팔레트 + 컬러피커 + 되돌리기/비우기 ──
+ const toolbar = document.createElement("div");
+ toolbar.className = "edit-toolbar";
+ toolbar.innerHTML =
+ `<button type="button" class="ghost et-transform" data-tip="${t("tTransformTool")} (V)">${TOOL_ICONS.transform}</button>` +
+ `<button type="button" class="ghost et-pen" data-tip="${t("penTool")} (B)">` +
+ `${TOOL_ICONS.pen}</button>` +
+ `<button type="button" class="ghost et-eraser" data-tip="${t("eraserTool")} (E)">${TOOL_ICONS.eraser}</button>` +
+ `<button type="button" class="ghost et-pick" data-tip="${t("tPick")} (I)">${TOOL_ICONS.pick}</button>` +
+ `<button type="button" class="ghost et-select" data-tip="${t("tSelectTool")} (M)">${TOOL_ICONS.select}</button>` +
+ `<button type="button" class="ghost et-lasso" data-tip="${t("tLassoTool")} (L)">${TOOL_ICONS.lasso}</button>` +
+ `<button type="button" class="ghost et-hand" data-tip="${t("tHandTool")} (H)">${TOOL_ICONS.hand}</button>` +
+ `<button type="button" class="ghost et-undo" data-tip="${t("tUndoKeys")}">${t("undoEdit")}</button>` +
+ `<button type="button" class="ghost et-redo" data-tip="${t("tRedoKeys")}">${t("redoEdit")}</button>` +
+ `<button type="button" class="ghost et-clear">${t("clearEdits")}</button>`;
+ card.insertBefore(toolbar, stage);
+ if (isBase) {
+ // 베이스는 사이드카가 아니라 파일에 굽는다 — 명시 저장 (원본 .orig 1회 백업)
+ const saveBtn = document.createElement("button");
+ saveBtn.className = "et-basesave";
+ saveBtn.setAttribute("data-tip", t("tBaseEdit"));
+ saveBtn.textContent = t("baseEditSave");
+ saveBtn.addEventListener("click", async () => {
+ const ops = (entries[BASE_STATE].pixels && entries[BASE_STATE].pixels[0]) || {};
+ const tr = entries[BASE_STATE].transforms[0];
+ const trDirty = tr && (tr.rotate || tr.scale !== 1 || tr.dx || tr.dy || tr.shx || tr.shy || tr.flipX);
+ if (!Object.keys(ops).length && !trDirty) { closeZoom(); return; }
+ saveBtn.disabled = true;
+ try {
+ const res = await fetch("/api/base-edit", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ ops, space: "logical", transform: trDirty ? tr : null }),
+ });
+ const data = await res.json();
+ if (!res.ok || !data.ok) throw new Error(data.error || res.status);
+ entries[BASE_STATE].pixels = {};
+ entries[BASE_STATE].transforms = {}; // 변형은 파일에 구워졌다 — 표시 변형 초기화
+ pixelEdit = null;
+ setStatus(STR[lang].baseEditSaved(data.applied), "ok");
+ closeZoom();
+ const baseImg = document.querySelector(".base-row .base-stage img");
+ if (baseImg) baseImg.src = run.baseUrl + (run.baseUrl.includes("?") ? "&" : "?") + "v=" + Date.now();
+ } catch (e) {
+ setStatus(t("baseEditFail") + e.message, "err");
+ saveBtn.disabled = false;
+ }
+ });
+ toolbar.appendChild(saveBtn);
+ }
+ const penBtn = toolbar.querySelector(".et-pen");
+ const eraserBtn = toolbar.querySelector(".et-eraser");
+ const pickBtn = toolbar.querySelector(".et-pick");
+ const selectBtn = toolbar.querySelector(".et-select");
+ const transformBtn = toolbar.querySelector(".et-transform");
+ const lassoBtn = toolbar.querySelector(".et-lasso");
+ // ── 팔레트 도크 (Aseprite 식, maintainer 지시 2026-07-17): 스테이지 왼쪽 세로 팔레트 —
+ // 위 = 현재 쓰인 색 전부 (같은 색 1개, 빈도순), 아래 = 자유 색상 피커.
+ const stageRow = document.createElement("div");
+ stageRow.className = "stage-row";
+ stage.parentNode.insertBefore(stageRow, stage);
+ const dock = document.createElement("div");
+ dock.className = "palette-dock";
+ const swatchBox = document.createElement("div");
+ swatchBox.className = "palette-swatches";
+ const colorInput = document.createElement("input");
+ colorInput.type = "color";
+ colorInput.value = lastPenColor || "#1f2430"; // 마지막 사용 색 승계
+ colorInput.title = "color";
+ colorInput.className = "et-color";
+ dock.appendChild(swatchBox);
+ dock.appendChild(colorInput);
+ stageRow.appendChild(dock);
+
+ // ── 3계층 뷰 (maintainer 지시 2026-07-20): 모달(고정 최대) ⊃ 뷰포트(화면 배율·팬) ⊃
+ // 스테이지(캐릭터). 스테이지 사방에 큰 패딩을 둬 어느 구석이든 화면 중앙으로
+ // 끌어올 수 있다 (자유 팬). 스크롤 좌표계라 기존 %-오버레이/포인터 수학 무변.
+ const viewwrap = document.createElement("div");
+ viewwrap.className = "stage-viewwrap";
+ const viewport = document.createElement("div");
+ viewport.className = "stage-viewport";
+ const pad = document.createElement("div");
+ pad.className = "stage-pad";
+ pad.appendChild(stage);
+ viewport.appendChild(pad);
+ viewwrap.appendChild(viewport);
+ stageRow.appendChild(viewwrap);
+
+ // 화면 배율: 최소 120px, 최대 셀폭×64 (기존 0.9×창폭 캡 폐지 — maintainer "확대 더 되게")
+ const VIEW_MIN_W = 120;
+ const viewMaxW = Math.max(8000, cellW * 64);
+ const syncViewLabels = () => {
+ const pct = `${Math.round((zoomView.width / cellW) * 100)}%`;
+ modal.querySelectorAll(".view-nav .vn-label").forEach((el) => { el.textContent = pct; });
+ };
+ const setViewWidth = (w, anchorX, anchorY) => {
+ w = Math.round(Math.min(viewMaxW, Math.max(VIEW_MIN_W, w)));
+ if (!zoomView || w === zoomView.width) return;
+ keepViewAnchor(viewport, stage, anchorX, anchorY, () => {
+ zoomView.width = w;
+ stage.style.width = `${w}px`;
+ applyCardTransform(stage, stateName, idx);
+ sizePxGrids();
+ });
+ syncViewLabels();
+ };
+ const fitViewWidth = () => {
+ const vr = viewport.getBoundingClientRect();
+ return Math.max(VIEW_MIN_W, Math.min(Math.floor(vr.width - 48), Math.floor((vr.height - 48) / aspect)));
+ };
+ const viewHandlers = {
+ zoomOut: () => setViewWidth(zoomView.width / 1.25),
+ zoomIn: () => setViewWidth(zoomView.width * 1.25),
+ fit: () => { setViewWidth(fitViewWidth()); centerView(viewport, stage); },
+ };
+ // 돋보기 위젯 ×2 (maintainer 지시 2026-07-20): 툴바 + 뷰포트 우하단 코너
+ toolbar.appendChild(makeViewNavWidget(viewHandlers));
+ viewwrap.appendChild(makeViewNavWidget(viewHandlers, { corner: true }));
+ // 뷰 확대: 휠/핀치 — 커서 아래 지점이 고정되는 앵커 줌. 뷰포트 레벨이라
+ // 스테이지 밖 여백 위에서도 동작한다.
+ viewport.addEventListener("wheel", (ev) => {
+ ev.preventDefault();
+ ev.stopImmediatePropagation();
+ const factor = ev.deltaY < 0 ? 1.12 : 1 / 1.12;
+ setViewWidth(zoomView.width * factor, ev.clientX, ev.clientY);
+ }, { passive: false });
+ wirePan(viewport, viewport, () => panTool);
+ // 오픈 = 뷰포트에 맞춤 + 중앙 정렬 (프레임 넘김은 배율 유지 — keepWidth)
+ if (!keepWidth) {
+ zoomView.width = fitViewWidth();
+ stage.style.width = `${zoomView.width}px`;
+ }
+ centerView(viewport, stage);
+ syncViewLabels();
+
+ const handBtn = toolbar.querySelector(".et-hand");
+ handBtn.addEventListener("click", () => {
+ panTool = !panTool;
+ handBtn.classList.toggle("active", panTool);
+ viewport.classList.toggle("pan-tool", panTool);
+ });
+ const selBox = document.createElement("div");
+ selBox.className = "marquee";
+ selBox.hidden = true;
+ stage.appendChild(selBox);
+ const syncMarqueeBox = () => {
+ const sel = pixelEdit && pixelEdit.sel;
+ // 핸들도 선택을 따라간다 — 사각 선택으로 잡았을 때도 같아야 한다.
+ regionPlaceHandles(stage, stateName, sel);
+ // 올가미 마스크 오버레이도 여기서 동기화한다 — 안 하면 연필로 전환했을 때
+ // 선택은 없는데 파란 영역만 유령으로 남는다(노을이 note 2026-07-26).
+ // 사각 선택(mask 없음)으로 교체돼도 이 호출이 지워 준다.
+ lassoRenderMask(stage, stateName, sel && sel.mask ? sel : null);
+ selBox.hidden = !sel;
+ if (!sel) return;
+ // sel 은 소스 공간 — 표시가 변형(WYSIWYG)이라 점선도 순변환해서 그린다
+ // (회전/기울임은 축정렬 bbox 근사; 공간 수학 SSoT = display.js frameFwdXY).
+ const fwd = (x, y) => frameFwdXY(stateName, idx, x, y);
+ const cs = [fwd(sel.x0, sel.y0), fwd(sel.x1, sel.y0), fwd(sel.x0, sel.y1), fwd(sel.x1, sel.y1)];
+ const x0 = Math.min(...cs.map((p) => p[0]));
+ const x1 = Math.max(...cs.map((p) => p[0]));
+ const y0 = Math.min(...cs.map((p) => p[1]));
+ const y1 = Math.max(...cs.map((p) => p[1]));
+ selBox.style.left = `${(x0 / cellW) * 100}%`;
+ selBox.style.top = `${(y0 / cellH) * 100}%`;
+ selBox.style.width = `${((x1 - x0) / cellW) * 100}%`;
+ selBox.style.height = `${((y1 - y0) / cellH) * 100}%`;
+ };
+ const syncToolbar = () => {
+ penBtn.classList.toggle("active", !!pixelEdit && pixelEdit.tool === "pen");
+ eraserBtn.classList.toggle("active", !!pixelEdit && pixelEdit.tool === "eraser");
+ pickBtn.classList.toggle("active", !!pixelEdit && pixelEdit.tool === "pick");
+ selectBtn.classList.toggle("active", !!pixelEdit && pixelEdit.tool === "select");
+ transformBtn.classList.toggle("active", !!pixelEdit && pixelEdit.tool === "transform");
+ lassoBtn.classList.toggle("active", !!pixelEdit && pixelEdit.tool === "lasso");
+ stage.classList.toggle("lassoing", !!pixelEdit && pixelEdit.tool === "lasso");
+ stage.classList.toggle("transforming", !!pixelEdit && pixelEdit.tool === "transform");
+ // `pixel-editing` 은 **픽셀을 찍는 툴** 일 때만이다. 변형/올가미는 픽셀을 안 찍는데
+ // 이 클래스가 붙으면 curator.css 가 회전·비틀기 핸들과 크기 스크러버를 숨겨
+ // 확대뷰에서 셀 전체 변형 경로가 통째로 막힌다(노을이 기각 R2 2026-07-26).
+ const NON_PAINTING = { transform: true, lasso: true };
+ const painting = !!pixelEdit && !NON_PAINTING[pixelEdit.tool];
+ stage.classList.toggle("pixel-editing", painting);
+ stage.classList.toggle("picking", !!pixelEdit && pixelEdit.tool === "pick");
+ stage.classList.toggle("selecting", !!pixelEdit && pixelEdit.tool === "select");
+ syncMarqueeBox();
+ };
+ const setTool = (tool) => {
+ // 같은 툴 재클릭/재단축키(B 두 번)는 유지한다 — 해제 안 함 (maintainer 지시 2026-07-29:
+ // "두 번 누른다고 선택 해제되는 기능 없애줘"). 툴 끄기는 다른 툴 선택/모달 닫기로만.
+ if (pixelEdit && pixelEdit.tool === tool) return;
+ pixelEdit = { state: stateName, idx, tool, color: colorInput.value,
+ journal: (pixelEdit && pixelEdit.journal) || [],
+ redo: (pixelEdit && pixelEdit.redo) || [],
+ // 변형 툴은 선택을 이어받는다 — "네모로 잡고 넘어와서 비튼다" 가 이 툴의 용법이다.
+ sel: (tool === "select" || tool === "transform" || tool === "lasso")
+ ? (pixelEdit && pixelEdit.sel) || null : null,
+ undoFn: () => undoPixel(), redoFn: () => redoPixel() };
+ syncToolbar();
+ applyFrameTransformAll(stateName, idx); // 편집 모드도 변형 유지(WYSIWYG) — 재표시만
+ };
+ penBtn.addEventListener("click", () => setTool("pen"));
+ eraserBtn.addEventListener("click", () => setTool("eraser"));
+ pickBtn.addEventListener("click", () => setTool("pick"));
+ selectBtn.addEventListener("click", () => setTool("select"));
+ transformBtn.addEventListener("click", () => setTool("transform"));
+ lassoBtn.addEventListener("click", () => setTool("lasso"));
+ colorInput.addEventListener("input", () => {
+ rememberPenColor(colorInput.value);
+ if (pixelEdit) pixelEdit.color = colorInput.value;
+ });
+
+ // 스포이드 = display.js sampleDisplayedColor ("화면에 보이는 그 색" SSoT).
+ // 저널은 스트로크(액션) 단위 {sets: [{key, had, prev, value}]} — undo 는 통째로
+ // 되돌리고 redo 스택에 쌓는다. 새 액션이 생기면 redo 는 비운다 (표준 편집기 계약).
+ const undoPixel = () => {
+ if (!pixelEdit || !pixelEdit.journal.length) return;
+ const j = pixelEdit.journal.pop();
+ const e = entries[stateName];
+ const ops = e.pixels[idx] || (e.pixels[idx] = {});
+ if (j.full) { j.after = { ...(e.pixels[idx] || {}) }; e.pixels[idx] = j.full; }
+ else if (j.sets) {
+ for (let i = j.sets.length - 1; i >= 0; i--) {
+ const s = j.sets[i];
+ if (s.had) ops[s.key] = s.prev;
+ else delete ops[s.key];
+ }
+ }
+ pixelEdit.redo.push(j);
+ applyFrameTransformAll(stateName, idx);
+ scheduleSave();
+ buildPalette();
+ };
+ const redoPixel = () => {
+ if (!pixelEdit || !pixelEdit.redo.length) return;
+ const j = pixelEdit.redo.pop();
+ const e = entries[stateName];
+ if (j.full) e.pixels[idx] = j.after || {};
+ else if (j.sets) {
+ const ops = e.pixels[idx] || (e.pixels[idx] = {});
+ for (const s of j.sets) ops[s.key] = s.value;
+ }
+ pixelEdit.journal.push(j);
+ applyFrameTransformAll(stateName, idx);
+ scheduleSave();
+ buildPalette();
+ };
+ toolbar.querySelector(".et-undo").addEventListener("click", undoPixel);
+ toolbar.querySelector(".et-redo").addEventListener("click", redoPixel);
+ toolbar.querySelector(".et-clear").addEventListener("click", () => {
+ // **픽셀과 변형을 둘 다 비운다.** 예전엔 픽셀 op 만 지웠는데, 확대뷰에서 변형이
+ // 일급 툴이 된 뒤로 "옮기기만 하고 편집 비우기를 눌렀는데 아무 일도 안 난다" 가 됐다
+ // (maintainer 신고 2026-07-26 "클리어에디트도 안돼"). 버튼 이름이 약속하는 건 "이 프레임에
+ // 내가 한 편집을 없앤다" 이고, 이동·회전·비틀기도 그 편집이다.
+ const e = entries[stateName];
+ const ops = e.pixels[idx];
+ const hadPixels = !!(ops && Object.keys(ops).length);
+ const tr = getTransform(stateName, idx);
+ const hadTransform = !isIdentityTransform(tr);
+ if (!hadPixels && !hadTransform) return;
+ if (hadPixels) {
+ if (pixelEdit) { pixelEdit.journal.push({ full: { ...ops } }); pixelEdit.redo.length = 0; }
+ e.pixels[idx] = {};
+ }
+ // `resetTransform` 이 스냅샷·히스토리 push·저장까지 스스로 한다 — 여기서 또 쌓으면
+ // Cmd+Z 를 두 번 눌러야 돌아온다.
+ if (hadTransform) resetTransform(stateName, idx);
+ applyFrameTransformAll(stateName, idx);
+ scheduleSave();
+ });
+ // 프레임 고유색 팔레트 (빈도순 상위 12)
+ const buildPalette = () => {
+ const imgEl = editSourceFor(stateName, stage.querySelector("img"));
+ if (!(imgEl && imgEl.complete && imgEl.naturalWidth)) {
+ if (imgEl) imgEl.addEventListener("load", buildPalette, { once: true });
+ return;
+ }
+ // 합성(원본+편집) 기준 — 방금 찍은 색도 팔레트에 나타난다. 같은 색 1개, 빈도순.
+ const counts = new Map();
+ {
+ const cx = compositeCell();
+ const data = cx.getImageData(0, 0, cellW, cellH).data;
+ for (let i = 0; i < data.length; i += 4) {
+ if (data[i + 3] < 200) continue;
+ const hex = "#" + [data[i], data[i + 1], data[i + 2]].map((v) => v.toString(16).padStart(2, "0")).join("");
+ counts.set(hex, (counts.get(hex) || 0) + 1);
+ }
+ }
+ if (isBase) {
+ // 근접색 병합 — raw 유래 미세 변종(0,0,0 vs 1,1,1)을 대표색 1개로 (tol 24 실측:
+ // 426→18색). 크로마 배경색은 제외 (지우개가 그 역할).
+ const cornerHex = (() => {
+ const cx2 = compositeCell();
+ const d = cx2.getImageData(0, 0, 1, 1).data;
+ return [d[0], d[1], d[2]];
+ })();
+ const reps = [];
+ for (const [hex, n] of [...counts.entries()].sort((a, b) => b[1] - a[1])) {
+ const r = parseInt(hex.slice(1, 3), 16);
+ const g = parseInt(hex.slice(3, 5), 16);
+ const b2 = parseInt(hex.slice(5, 7), 16);
+ if (Math.abs(r - cornerHex[0]) + Math.abs(g - cornerHex[1]) + Math.abs(b2 - cornerHex[2]) <= 60) continue;
+ const hit = reps.find((q) => Math.abs(q.r - r) + Math.abs(q.g - g) + Math.abs(q.b - b2) <= 24);
+ if (hit) hit.n += n;
+ else reps.push({ hex, r, g, b: b2, n });
+ }
+ counts.clear();
+ for (const q of reps) counts.set(q.hex, q.n);
+ }
+ swatchBox.innerHTML = "";
+ for (const [hex] of [...counts.entries()].sort((a, b) => b[1] - a[1])) {
+ const b = document.createElement("button");
+ b.type = "button";
+ b.className = "swatch";
+ b.style.background = hex;
+ b.setAttribute("data-tip", hex);
+ b.classList.toggle("current", hex === colorInput.value);
+ b.addEventListener("click", () => {
+ colorInput.value = hex;
+ rememberPenColor(hex);
+ swatchBox.querySelectorAll(".swatch.current").forEach((s) => s.classList.remove("current"));
+ b.classList.add("current");
+ if (pixelEdit) { pixelEdit.color = hex; if (pixelEdit.tool !== "pen") setTool("pen"); }
+ else setTool("pen"), (pixelEdit.color = hex);
+ });
+ swatchBox.appendChild(b);
+ }
+ };
+
+ // 마키(영역 선택) 헬퍼 — 캡처는 "현재 보이는 픽셀"(원본 + 편집 합성) 기준
+ const compositeCell = () => {
+ const c = document.createElement("canvas");
+ c.width = cellW;
+ c.height = cellH;
+ const cx = c.getContext("2d");
+ cx.imageSmoothingEnabled = false;
+ const imgEl = editSourceFor(stateName, stage.querySelector("img"));
+ if (imgEl && imgEl.complete && imgEl.naturalWidth) cx.drawImage(imgEl, 0, 0, c.width, c.height);
+ const ops0 = entries[stateName].pixels[idx] || {};
+ for (const [key, val] of Object.entries(ops0)) {
+ const [x, y] = key.split(",").map(Number);
+ if (val) { cx.fillStyle = val; cx.fillRect(x, y, 1, 1); }
+ else cx.clearRect(x, y, 1, 1);
+ }
+ return cx;
+ };
+ const captureRegion = (sel) => {
+ const cx = compositeCell();
+ let chromaRef = null;
+ if (isBase) {
+ const d0 = cx.getImageData(0, 0, 1, 1).data; // 베이스 배경(크로마)은 내용이 아니다
+ chromaRef = [d0[0], d0[1], d0[2]];
+ }
+ const data = cx.getImageData(sel.x0, sel.y0, sel.x1 - sel.x0, sel.y1 - sel.y0).data;
+ const pixels = [];
+ const w = sel.x1 - sel.x0;
+ for (let i = 0; i < data.length; i += 4) {
+ if (data[i + 3] < 40) continue; // 투명은 옮길 내용 없음
+ if (chromaRef && Math.abs(data[i] - chromaRef[0]) + Math.abs(data[i + 1] - chromaRef[1]) + Math.abs(data[i + 2] - chromaRef[2]) <= 60) continue;
+ pixels.push({
+ dx: (i / 4) % w,
+ dy: Math.floor((i / 4) / w),
+ hex: "#" + [data[i], data[i + 1], data[i + 2]].map((v) => v.toString(16).padStart(2, "0")).join(""),
+ });
+ }
+ return pixels;
+ };
+ const commitRegionMove = (fromSel, pixels, ddx, ddy, duplicate) => {
+ if (!pixels.length || (ddx === 0 && ddy === 0)) return;
+ const staged = new Map(); // key -> value (이동: 원본 지움 먼저, 목적지 색이 덮음)
+ if (!duplicate) {
+ for (const p of pixels) staged.set(`${fromSel.x0 + p.dx},${fromSel.y0 + p.dy}`, null);
+ }
+ for (const p of pixels) {
+ const x = fromSel.x0 + p.dx + ddx;
+ const y = fromSel.y0 + p.dy + ddy;
+ if (x >= 0 && x < cellW && y >= 0 && y < cellH) staged.set(`${x},${y}`, p.hex);
+ }
+ const e = entries[stateName];
+ const ops = e.pixels[idx] || (e.pixels[idx] = {});
+ const sets = [];
+ for (const [key, value] of staged) {
+ if (key in ops && ops[key] === value) continue;
+ sets.push({ key, had: key in ops, prev: ops[key], value });
+ ops[key] = value;
+ }
+ if (!sets.length) return;
+ pixelEdit.journal.push({ sets });
+ pixelEdit.redo.length = 0;
+ applyFrameTransformAll(stateName, idx);
+ scheduleSave();
+ buildPalette();
+ };
+
+ // 마키 영역 좌우반전 — 현재 보이는 픽셀(합성)을 영역 안에서 거울로 뒤집어 픽셀
+ // 저널 스트로크로 기록한다 (maintainer 2026-07-19 "영역선택하고 좌우반전하면 거기만 툭툭").
+ // 달라지는 픽셀만 ops 로 남기므로 다시 누르면 정확히 원복되고 Cmd+Z 도 스트로크
+ // 단위로 먹는다. 투명은 null(지움) — 베이스의 크로마 배경은 균일색이라 자연 무변.
+ function flipSelectionX() {
+ const sel = pixelEdit && pixelEdit.sel;
+ if (!sel || sel.x1 <= sel.x0 || sel.y1 <= sel.y0) return;
+ const cx = compositeCell();
+ const w = sel.x1 - sel.x0;
+ const h = sel.y1 - sel.y0;
+ const data = cx.getImageData(sel.x0, sel.y0, w, h).data;
+ const hexAt = (i) => "#" + [data[i], data[i + 1], data[i + 2]]
+ .map((v) => v.toString(16).padStart(2, "0")).join("");
+ const e = entries[stateName];
+ const ops = e.pixels[idx] || (e.pixels[idx] = {});
+ const sets = [];
+ for (let y = 0; y < h; y++) {
+ for (let x = 0; x < w; x++) {
+ const cur = (y * w + x) * 4;
+ const mir = (y * w + (w - 1 - x)) * 4;
+ const curVal = data[cur + 3] >= 128 ? hexAt(cur) : null;
+ const mirVal = data[mir + 3] >= 128 ? hexAt(mir) : null;
+ if (curVal === mirVal) continue; // 화면 무변 — op 잡음 남기지 않는다
+ const key = `${sel.x0 + x},${sel.y0 + y}`;
+ sets.push({ key, had: key in ops, prev: ops[key], value: mirVal });
+ ops[key] = mirVal;
+ }
+ }
+ if (!sets.length) return;
+ pixelEdit.journal.push({ sets });
+ pixelEdit.redo.length = 0;
+ applyFrameTransformAll(stateName, idx);
+ scheduleSave();
+ buildPalette();
+ }
+
+ // ── 변형 툴이 기본 상태다 (maintainer 지시 2026-07-26 "이게 기본상태인걸로"). ──
+ // 예전엔 "아무 툴도 안 켜진 상태" 가 암묵적으로 셀 전체 변형이었다 — 화면에 표시가
+ // 없어서 지금 무슨 모드인지 알 수 없었다. 그 암묵 모드를 이름 있는 툴로 승격한다.
+ pixelEdit = { state: stateName, idx, tool: "transform", color: colorInput.value,
+ journal: [], redo: [], sel: null,
+ undoFn: () => undoPixel(), redoFn: () => redoPixel() };
+ // 올가미 — 자유곡선으로 잡고 그 마스크를 `sel` 에 얹는다 (bbox 는 유지).
+ wireLasso(stage, stateName, {
+ isLassoTool: () => !!pixelEdit && pixelEdit.tool === "lasso"
+ && pixelEdit.state === stateName && pixelEdit.idx === idx,
+ srcXY: (e2) => pointerSrcXY(stage, stateName, idx, e2),
+ onSelection: (sel) => {
+ if (!pixelEdit) return;
+ pixelEdit.sel = sel;
+ lassoRenderMask(stage, stateName, sel);
+ regionPlaceHandles(stage, stateName, sel);
+ syncMarqueeBox();
+ if (sel) {
+ // 잡았으면 바로 비틀 수 있게 변형 툴로 넘긴다 — 올가미의 용법이 그것이다.
+ setTool("transform");
+ setStatus(t("lassoSelected")(sel.mask.size), "ok");
+ }
+ },
+ });
+ const regionCtx = {
+ isTransformTool: () => !!pixelEdit && pixelEdit.tool === "transform"
+ && pixelEdit.state === stateName && pixelEdit.idx === idx,
+ // 핸들은 **선택이 살아 있는 비페인팅 툴 전부**에서 영역을 대상으로 한다.
+ isRegionTool: () => !!pixelEdit && (pixelEdit.tool === "transform" || pixelEdit.tool === "lasso")
+ && pixelEdit.state === stateName && pixelEdit.idx === idx,
+ hasSelection: () => !!(pixelEdit && pixelEdit.sel),
+ selectionRect: () => {
+ const s0 = pixelEdit.sel;
+ // 올가미면 bbox 에 마스크를 얹어 넘긴다 — 마스크가 없으면 사각 선택 그대로다.
+ return { x: s0.x0, y: s0.y0, w: s0.x1 - s0.x0, h: s0.y1 - s0.y0, mask: s0.mask || null };
+ },
+ afterCommit: () => {
+ applyFrameTransformAll(stateName, idx);
+ scheduleSave();
+ setStatus(t("regionTransformed"), "ok");
+ },
+ };
+ // 순서가 계약이다 — 둘 다 `wireStage`(아래, 셀 전체)보다 먼저 등록돼야
+ // stopImmediatePropagation 이 셀 전체 경로를 막는다.
+ wireRegionHandles(stage, stateName, idx, regionCtx);
+ wireRegionTransform(stage, stateName, idx, regionCtx);
+ syncToolbar();
+ buildPalette();
+
+ // 페인트: 편집 툴 활성 시 스테이지 드래그는 그리기 (다른 핸들러보다 먼저 등록해 가로챔)
+ stage.addEventListener("pointerdown", (ev) => {
+ if (!pixelEdit || pixelEdit.state !== stateName || pixelEdit.idx !== idx) return;
+ // 변형 툴은 픽셀을 안 찍는다. 선택이 있으면 영역 변형(region-transform.js)이,
+ // 없으면 `wireStage` 의 셀 전체 변형이 그 드래그를 가져간다.
+ if (pixelEdit.tool === "transform" || pixelEdit.tool === "lasso") return;
+ if (ev.button || !ev.isPrimary) return;
+ ev.preventDefault();
+ ev.stopImmediatePropagation();
+ // 표시는 변형(WYSIWYG) 그대로, 저장은 소스 공간 — 공간 수학 SSoT 는 display.js.
+ const cellX = (e2) => Math.floor(pointerSrcXY(stage, stateName, idx, e2)[0]);
+ const cellY = (e2) => Math.floor(pointerSrcXY(stage, stateName, idx, e2)[1]);
+ // 스포이드: 색만 집고 바로 연필로 전환 (드래그 페인트 아님). 투명 픽셀은 무시.
+ // 집는 색 = 화면에 보이는 그 색 (표시 비트맵 샘플, display.js SSoT).
+ if (pixelEdit.tool === "pick") {
+ const hex = sampleDisplayedColor(stage, stateName, idx, ev);
+ if (hex) {
+ colorInput.value = hex;
+ rememberPenColor(hex);
+ pixelEdit.color = hex;
+ pixelEdit.tool = "pen"; // 집은 색으로 즉시 그리게
+ syncToolbar();
+ setStatus(`${t("pickTool")}: ${hex}`, "ok");
+ }
+ return;
+ }
+ try { stage.setPointerCapture(ev.pointerId); } catch { /* 일부 펜/합성 포인터 */ }
+ const s = snapScaleFor(stateName) || 1;
+ const finish = (onMove, onUp) => {
+ try { stage.releasePointerCapture(ev.pointerId); } catch { /* no-op */ }
+ stage.removeEventListener("pointermove", onMove);
+ stage.removeEventListener("pointerup", onUp);
+ };
+
+ // ── 선택(마키): 점선 드래그로 영역 선택 → 안쪽 드래그 = 이동, Alt+드래그 = 복제 ──
+ if (pixelEdit.tool === "select") {
+ const sx = cellX(ev), sy = cellY(ev);
+ const sel = pixelEdit.sel;
+ const inside = sel && sx >= sel.x0 && sx < sel.x1 && sy >= sel.y0 && sy < sel.y1;
+ if (inside) {
+ const grab = captureRegion(sel);
+ const from = { ...sel };
+ let delta = [0, 0];
+ // 라이브 프리뷰: 드래그 중에도 픽셀이 점선과 함께 실제로 따라온다.
+ // 밑층(img/snap-canvas)을 잠깐 숨기고 전체 합성본을 프리뷰 캔버스에 직접 그린다 —
+ // 원본 자리는 비우고(이동) 목적지에 그대로 칠해 드롭 결과와 동일하게 보인다.
+ const fullC = compositeCell().canvas;
+ let chromaFill = null;
+ if (isBase) {
+ const d0 = fullC.getContext("2d").getImageData(0, 0, 1, 1).data;
+ chromaFill = `rgb(${d0[0]},${d0[1]},${d0[2]})`;
+ }
+ const prev = document.createElement("canvas");
+ prev.width = cellW; prev.height = cellH;
+ Object.assign(prev.style, { position: "absolute", inset: "0", width: "100%",
+ height: "100%", pointerEvents: "none" });
+ // nearest 여부는 인라인으로 박지 않는다 — 판정 소유자에게 맡긴다 (부착 직후 호출).
+ // (인라인 무조건 부여는 grep image-rendering 에도 안 잡혀 계약 밖에 숨는다)
+ const hidden = [stage.querySelector("img"), stage.querySelector(".snap-canvas")].filter(Boolean);
+ const work = document.createElement("canvas");
+ work.width = cellW; work.height = cellH;
+ const drawPreview = (ddx, ddy, dup) => {
+ // 소스 공간에서 이동을 합성한 뒤, 표시 변형을 통과시켜 그린다 (WYSIWYG 일치)
+ const wctx = work.getContext("2d");
+ wctx.imageSmoothingEnabled = false;
+ wctx.clearRect(0, 0, cellW, cellH);
+ wctx.drawImage(fullC, 0, 0);
+ if (!dup) for (const p of grab) {
+ const x = from.x0 + p.dx, y = from.y0 + p.dy;
+ if (chromaFill) { wctx.fillStyle = chromaFill; wctx.fillRect(x, y, 1, 1); }
+ else wctx.clearRect(x, y, 1, 1);
+ }
+ for (const p of grab) {
+ const x = from.x0 + p.dx + ddx, y = from.y0 + p.dy + ddy;
+ if (x >= 0 && x < cellW && y >= 0 && y < cellH) {
+ wctx.fillStyle = p.hex;
+ wctx.fillRect(x, y, 1, 1);
+ }
+ }
+ const pcx = prev.getContext("2d");
+ pcx.clearRect(0, 0, cellW, cellH);
+ drawFrameInto(pcx, work, getTransform(stateName, idx), cellW, cellH, snapScaleFor(stateName));
+ };
+ hidden.forEach((el2) => { el2.style.visibility = "hidden"; });
+ stage.insertBefore(prev, selBox);
+ applyPixelScaling(prev); // 부착 후에야 표시폭이 정해진다
+ drawPreview(0, 0, ev.altKey);
+ const onMove = (e2) => {
+ const step = s;
+ delta = [
+ Math.round((cellX(e2) - sx) / step) * step,
+ Math.round((cellY(e2) - sy) / step) * step,
+ ];
+ pixelEdit.sel = { x0: from.x0 + delta[0], y0: from.y0 + delta[1],
+ x1: from.x1 + delta[0], y1: from.y1 + delta[1] };
+ syncMarqueeBox();
+ drawPreview(delta[0], delta[1], e2.altKey);
+ };
+ const onUp = (e2) => {
+ finish(onMove, onUp);
+ prev.remove();
+ hidden.forEach((el2) => { el2.style.visibility = ""; });
+ commitRegionMove(from, grab, delta[0], delta[1], e2.altKey);
+ syncMarqueeBox();
+ };
+ stage.addEventListener("pointermove", onMove);
+ stage.addEventListener("pointerup", onUp);
+ } else {
+ const norm = (ax, ay, bx, by) => {
+ const clampX = (v) => Math.max(0, Math.min(cellW, v));
+ const clampY = (v) => Math.max(0, Math.min(cellH, v));
+ const x0 = Math.floor(Math.min(ax, bx) / s) * s;
+ const y0 = Math.floor(Math.min(ay, by) / s) * s;
+ const x1 = Math.ceil((Math.max(ax, bx) + 1) / s) * s;
+ const y1 = Math.ceil((Math.max(ay, by) + 1) / s) * s;
+ return { x0: clampX(x0), y0: clampY(y0), x1: clampX(x1), y1: clampY(y1) };
+ };
+ // Space(또는 Cmd/Ctrl) 홀드 중엔 앵커가 커서와 함께 움직여 영역 전체가 이동한다
+ // (포토샵 마키 표준). 떼면 그 자리에서 다시 크기 조절로 복귀.
+ let ax = sx, ay = sy;
+ let lx = sx, ly = sy;
+ let spaceHeld = false;
+ const onKey = (ke) => {
+ if (ke.code === "Space") { spaceHeld = ke.type === "keydown"; ke.preventDefault(); }
+ };
+ window.addEventListener("keydown", onKey, true);
+ window.addEventListener("keyup", onKey, true);
+ pixelEdit.sel = norm(ax, ay, sx, sy);
+ syncMarqueeBox();
+ const onMove = (e2) => {
+ const cx2 = cellX(e2), cy2 = cellY(e2);
+ if (spaceHeld || e2.metaKey || e2.ctrlKey) { ax += cx2 - lx; ay += cy2 - ly; }
+ lx = cx2; ly = cy2;
+ pixelEdit.sel = norm(ax, ay, cx2, cy2);
+ syncMarqueeBox();
+ };
+ const onUp = () => {
+ window.removeEventListener("keydown", onKey, true);
+ window.removeEventListener("keyup", onKey, true);
+ finish(onMove, onUp);
+ };
+ stage.addEventListener("pointermove", onMove);
+ stage.addEventListener("pointerup", onUp);
+ }
+ return;
+ }
+
+ const e = entries[stateName];
+ if (!e.pixels[idx]) e.pixels[idx] = {};
+ const ops = e.pixels[idx];
+ const stroke = []; // 스트로크(드래그 1회) 단위 액션 — undo/redo 가 통째로 다룬다
+ const paint = (e2) => {
+ const x = cellX(e2);
+ const y = cellY(e2);
+ if (!(x >= 0 && x < cellW && y >= 0 && y < cellH)) return;
+ const bx = Math.floor(x / s) * s;
+ const by = Math.floor(y / s) * s;
+ const value = pixelEdit.tool === "eraser" ? null : pixelEdit.color;
+ let changed = false;
+ for (let dy = 0; dy < s; dy++) {
+ for (let dx = 0; dx < s; dx++) {
+ const key = `${bx + dx},${by + dy}`;
+ if (ops[key] === value && key in ops) continue;
+ stroke.push({ key, had: key in ops, prev: ops[key], value });
+ ops[key] = value;
+ changed = true;
+ }
+ }
+ if (changed) applyFrameTransformAll(stateName, idx);
+ };
+ paint(ev);
+ const onMove = (e2) => paint(e2);
+ const onUp = () => {
+ finish(onMove, onUp);
+ if (stroke.length) {
+ pixelEdit.journal.push({ sets: stroke });
+ pixelEdit.redo.length = 0;
+ buildPalette();
+ }
+ scheduleSave();
+ };
+ stage.addEventListener("pointermove", onMove);
+ stage.addEventListener("pointerup", onUp);
+ });
+
+ // 뷰 확대 휠 = 뷰포트 레벨 앵커 줌 (위 stage-viewport 블록이 소유)
+
+ // ── 호흡 모드 (레이어, maintainer 확정 2026-07-18): 실제 시퀀스가 재생되는 위에
+ // 강체 경계·진폭·호흡 횟수를 조정하면 즉시 truth(사이드카)에 반영된다.
+ // 깜빡임 프레임도 그대로 숨쉰다 (직교 레이어). 굽기/재추출/적용 대기 없음.
+ if (!isBase && pendingBreathe) {
+ pendingBreathe = false;
+ card.classList.add("breathe-focus");
+ zoomView.breatheMode = true;
+ stage.addEventListener("pointerdown", (ev) => {
+ if (!ev.target.closest(".breathe-line")) {
+ ev.stopImmediatePropagation();
+ ev.preventDefault();
+ }
+ }, true);
+ const e0 = entries[stateName];
+ const beforeCfg = e0.breathe ? JSON.parse(JSON.stringify(e0.breathe)) : null; // Esc 복원
+ // enabled = 호흡 레이어 on/off (maintainer 2026-07-19: 이 뷰가 유일한 확대 재생 뷰라
+ // 꺼진 상태로 열거나 여기서 꺼도 무호흡 애니메이션이 그대로 재생돼야 한다).
+ // 열 때 줄 체크박스 truth 를 승계 — 꺼진 행을 열어도 강제로 켜지 않는다.
+ const bm = { cfg: null, enabled: !!e0.breathe, geomReady: false, hist: [], histPos: -1, cancelled: false, tick: 0, dragging: false };
+ const clone = (o) => JSON.parse(JSON.stringify(o));
+ const commit = () => { // 조정 = 즉시 truth 반영 + 디바운스 저장 (maintainer: 적용 대기 금지)
+ if (bm.cancelled) return;
+ e0.breathe = bm.enabled ? clone(bm.cfg) : null;
+ scheduleSave();
+ if (typeof scheduleStrip === "function") scheduleStrip();
+ };
+ const pushHist = () => {
+ bm.hist = bm.hist.slice(0, bm.histPos + 1);
+ bm.hist.push({ enabled: bm.enabled, cfg: clone(bm.cfg) });
+ bm.histPos = bm.hist.length - 1;
+ };
+ const restoreHist = (pos) => {
+ if (pos < 0 || pos >= bm.hist.length || pos === bm.histPos) return;
+ bm.histPos = pos;
+ const h = bm.hist[pos];
+ bm.cfg = clone(h.cfg);
+ bm.enabled = h.enabled !== false;
+ syncBreatheControls();
+ syncLines();
+ commit();
+ };
+ bm.cfg = e0.breathe ? clone(e0.breathe)
+ : { depth: 0.06, breaths: 1, lag: 0.1, rigid_row: null, axis_x: null, torso_half: null, anatomy: null };
+
+ // 실루엣 지오메트리 (선 표시 기준): 이미지 로드 전 빈 합성이면 재시도
+ // (회귀 2026-07-17 로드 레이스 — 선이 바닥에 붙고 드래그 죽음)
+ let btop = 0;
+ let bleft = 0;
+
+ // 강체 경계 1개 — 이 위는 안 움직인다. 드래그 = 즉시 반영, 놓으면 서버에 다시
+ // 물어 해부를 갱신한다(검출 SSoT = 서버). 구 방식의 분할선 N개는 폐기됐다:
+ // 선은 "이 위가 움직인다" 였고 경계는 "이 위는 안 움직인다" 라 반대 개념이다.
+ const lineEls = [];
+ let anatomyBusy = false;
+ let anatomyPending = false;
+ const refreshAnatomy = async () => {
+ // 진행 중이면 **드롭하지 않고 예약한다** — 드롭하면 마지막 드래그 값이 서버에
+ // 반영되지 않은 채 낡은 파생값(basis_row·torso_half)이 사이드카에 남는다.
+ if (anatomyBusy) { anatomyPending = true; return; }
+ anatomyBusy = true;
+ setRecalcBadge(true);
+ try {
+ const { anatomy } = await fetchBreatheAnatomy(
+ stateName, bm.cfg.rigid_row, bm.cfg.axis_x, bm.cfg.torso_half);
+ bm.cfg.anatomy = anatomy;
+ syncLines();
+ commit();
+ rebuildStrip();
+ } catch (err) {
+ // 실패했으면 낡은 파생값을 **그대로 두지 않는다.** 지문을 무효화해 굽기가 다시
+ // 재게 하고(사이드카는 그래도 정합), 프리뷰는 거부되어 원본을 보여준다.
+ if (bm.cfg.anatomy) bm.cfg.anatomy = { ...bm.cfg.anatomy, fingerprint: null };
+ commit();
+ setStatus(t("breatheFail") + err.message, "err");
+ }
+ anatomyBusy = false;
+ if (anatomyPending) { anatomyPending = false; await refreshAnatomy(); return; }
+ setRecalcBadge(false);
+ };
+ // "재계산 중" 배지 — 드래그를 놓고 서버가 해부를 다시 재는 동안 프리뷰는 직전
+ // 값으로 계속 재생하고(위 liveCfg), 이 배지가 재계산 중임을 알린다 (maintainer 2026-07-30:
+ // "렌더링 중이면 로딩이라도 돌려줘").
+ let recalcEl = null;
+ const setRecalcBadge = (on) => {
+ if (on) {
+ if (!recalcEl) {
+ recalcEl = document.createElement("div");
+ recalcEl.className = "breathe-recalc";
+ recalcEl.innerHTML = `<span class="breathe-recalc-spin"></span>${t("breatheRecalc")}`;
+ stage.appendChild(recalcEl);
+ }
+ recalcEl.style.display = "";
+ } else if (recalcEl) {
+ recalcEl.style.display = "none";
+ }
+ };
+ function wireLine(ln, apply) {
+ // apply(e2, rect) 가 드래그 좌표를 bm.cfg 의 의도 값으로 바꾼다. 드래그 중에는
+ // `anatomy` 를 **손대지 않는다** — 의도만 바꿔 두면 미러가 "캐시가 의도와
+ // 어긋난다" 로 거부해 원본을 보여주고, pointerup 의 refreshAnatomy() 가 서버
+ // 값으로 갱신한다. 의도만 갈아끼우면 파생값(basis_row 등)이 낡은 채 저장돼
+ // 굽기와 갈린다 (validator 실측 2026-07-25: _dome 에서 11/12 위상 불일치).
+ ln.addEventListener("pointerdown", (ev) => {
+ ev.preventDefault();
+ ev.stopImmediatePropagation();
+ if (!bm.geomReady || !bm.cfg.anatomy) return;
+ ln.setPointerCapture(ev.pointerId);
+ bm.dragging = true; // 프리뷰는 직전 해부로 계속 재생 (renderTick 참조)
+ const onMove = (e2) => {
+ apply(e2, stage.getBoundingClientRect());
+ syncLines(); // 선은 의도값을 즉시 따라온다. commit 은 놓을 때 한 번 —
+ }; // per-move 저장/리빌드는 드래그를 무겁게만 한다.
+ const onUp = () => {
+ ln.removeEventListener("pointermove", onMove);
+ ln.removeEventListener("pointerup", onUp);
+ bm.dragging = false;
+ commit();
+ refreshAnatomy(); // basis_row 등 파생값은 서버가 다시 계산한다
+ pushHist();
+ };
+ ln.addEventListener("pointermove", onMove);
+ ln.addEventListener("pointerup", onUp);
+ });
+ }
+ // 영역 조정 4선 (2026-07-30 maintainer): [0] 강체 경계(가로) [1] 몸통 축(세로 중앙)
+ // [2][3] 몸통 반폭(세로 좌/우, 축 대칭 — 어느 쪽을 끌든 같은 torso_half 가 바뀐다).
+ // 축·반폭은 부속(팔·날개) 보호 밴드가 어디서 시작하는지를 사람이 정하는 손잡이다.
+ const cellCol = (e2, r) => ((e2.clientX - r.left) / r.width) * cellW - bleft;
+ const LINES = [
+ { cls: "breathe-line", hint: "breatheHint", apply: (e2, r) => {
+ const yCell = ((e2.clientY - r.top) / r.height) * cellH;
+ // 해부는 변형 후 프레임 기준이므로 셀 좌표의 콘텐츠 상단(btop)이 곧 0행이다.
+ const row = Math.round(yCell - btop);
+ bm.cfg.rigid_row = Math.min(bm.cfg.anatomy.height - 2, Math.max(1, row));
+ } },
+ { cls: "breathe-line breathe-line-v breathe-axis", hint: "breatheAxisHint", apply: (e2, r) => {
+ const col = Math.round(cellCol(e2, r));
+ bm.cfg.axis_x = Math.min(bm.cfg.anatomy.width - 1, Math.max(0, col));
+ } },
+ { cls: "breathe-line breathe-line-v", hint: "breatheTorsoHint", apply: (e2, r) => {
+ const axis = bm.cfg.axis_x != null ? bm.cfg.axis_x : bm.cfg.anatomy.axis_x;
+ const half = Math.round(Math.abs(cellCol(e2, r) - axis));
+ bm.cfg.torso_half = Math.min(bm.cfg.anatomy.width, Math.max(1, half));
+ } },
+ { cls: "breathe-line breathe-line-v", hint: "breatheTorsoHint", apply: (e2, r) => {
+ const axis = bm.cfg.axis_x != null ? bm.cfg.axis_x : bm.cfg.anatomy.axis_x;
+ const half = Math.round(Math.abs(cellCol(e2, r) - axis));
+ bm.cfg.torso_half = Math.min(bm.cfg.anatomy.width, Math.max(1, half));
+ } },
+ ];
+ const syncLines = () => {
+ const anat = bm.cfg.anatomy;
+ while (lineEls.length > (anat ? LINES.length : 0)) lineEls.pop().remove();
+ if (!anat) return;
+ while (lineEls.length < LINES.length) {
+ const spec = LINES[lineEls.length];
+ const ln = document.createElement("div");
+ ln.className = spec.cls;
+ ln.setAttribute("data-tip", t(spec.hint));
+ wireLine(ln, spec.apply);
+ stage.appendChild(ln);
+ lineEls.push(ln);
+ }
+ const vis = bm.geomReady && bm.enabled ? "" : "hidden";
+ // 선 위치는 **의도값 우선** — anatomy 는 서버 재검출 후에야 갱신되므로 anatomy 만
+ // 읽으면 드래그 중 선이 커서를 안 따라온다 (maintainer 실기기 2026-07-30).
+ const rigid = bm.cfg.rigid_row != null ? bm.cfg.rigid_row : anat.rigid_row;
+ const axis = bm.cfg.axis_x != null ? bm.cfg.axis_x : anat.axis_x;
+ const torso = bm.cfg.torso_half != null ? bm.cfg.torso_half : anat.torso_half;
+ lineEls[0].style.top = `${((btop + rigid) / cellH) * 100}%`;
+ const axisCol = bleft + axis;
+ lineEls[1].style.left = `${((axisCol + 0.5) / cellW) * 100}%`;
+ lineEls[2].style.left = `${((axisCol - torso + 0.5) / cellW) * 100}%`;
+ lineEls[3].style.left = `${((axisCol + torso + 0.5) / cellW) * 100}%`;
+ for (const ln of lineEls) ln.style.visibility = vis;
+ // 몸통 반폭 선은 부속 보호가 실제로 걸릴 때만 실선처럼 진하게 — 그 판정
+ // (max_half >= 1.3 x torso_half)은 굽기 protect() 와 같은 식이다. 흐릿한
+ // 상태에서도 끌 수는 있다 (안쪽으로 끌면 보호가 켜진다).
+ const appendage = anat.max_half >= 1.3 * torso;
+ for (const ln of [lineEls[2], lineEls[3]]) ln.style.opacity = appendage ? "" : "0.35";
+ };
+
+ // 굽기가 해부를 확정하는 프레임 = 재생 첫 슬롯. 신선도 판정은 이 프레임으로만 한다
+ // (프레임마다 보면 깜빡임처럼 정상적으로 다른 프레임까지 거부해 프리뷰가 죽는다).
+ // 그림이 아니라 **키**다. 굽기(BICUBIC)와 캔버스(NEAREST)는 같은 원본·같은 변형에도
+ // 다른 픽셀을 만들어서, 여기서 프레임을 다시 그려 지문을 찍으면 영구 불일치가 된다.
+ const breatheRef = () => breatheReferenceKey(stateName);
+
+ // 시퀀스 재생 미리보기 — 실제 재생 순서(playList: 깜빡임 포함) 위에 위상을 얹는다.
+ const bcanvas = stage.querySelector(".snap-canvas");
+ const bImg = stage.querySelector("img");
+ const renderTick = () => {
+ if (!bcanvas) return;
+ const play = playList(stateName);
+ const pattern = breathePattern(bm.cfg, play.length || 1);
+ const cursor = play.length ? bm.tick % play.length : 0;
+ const frameIdx = play.length ? play[cursor] : idx;
+ const phase = bm.enabled ? (pattern[cursor] || 0) : 0; // off = 무호흡 재생
+ const f = frameOf(stateName, frameIdx);
+ // 호흡 프리뷰 = 굽기 결과 미리보기 — **굽기가 읽는 파일**로 그린다.
+ // (구 2026-07-18 결정 "항상 캐노니컬" 은 분할선 시절 이음매가 근거였고, 봉투에는
+ // 이음매가 없다. 굽기는 `frame_variant` 로 해소한 파일을 읽으므로 그걸 따라간다.)
+ const bakeSrc = f && bakeFrameUrl(stateName, f);
+ const image = bakeSrc ? img(bakeSrc) : null;
+ bImg.style.visibility = "hidden";
+ bcanvas.style.display = "block";
+ bcanvas.width = cellW;
+ bcanvas.height = cellH;
+ applyPixelScaling(bcanvas); // 버퍼를 정한 자리에서 판정 — 계약: display.js 상단
+ const bctx = bcanvas.getContext("2d");
+ bctx.imageSmoothingEnabled = false;
+ bctx.clearRect(0, 0, cellW, cellH);
+ if (!(image && image.complete && image.naturalWidth)) return;
+ const base = document.createElement("canvas");
+ base.width = cellW;
+ base.height = cellH;
+ const baseCtx = base.getContext("2d");
+ baseCtx.imageSmoothingEnabled = false;
+ drawFrameInto(baseCtx, image, getTransform(stateName, frameIdx), cellW, cellH,
+ snapScaleFor(stateName), getPixelOps(stateName, frameIdx));
+ // 꺼진 줄은 워프를 **아예 안 부른다.** 봉투에서 위상 0 은 항등이 아니라서
+ // (진행파 지연) 위상만 0 으로 넘기면 정지 상태가 워프된 그림이 된다 — 굽기는
+ // off 면 state_breathe 가 None 이라 원본을 굽는다 (validator 검증 2026-07-25).
+ // 드래그 중에는 오버라이드를 직전 해부값으로 중화해 재생을 유지한다 — 의도값
+ // 그대로 두면 미러가 stale 거부로 원본 정지를 그려 "뻗는/로딩" 으로 읽힌다
+ // (maintainer 실기기 2026-07-30). 거부 계약은 드래그 밖(영속 상태)에서 그대로 산다.
+ const liveCfg = (bm.dragging || anatomyBusy) && bm.cfg.anatomy
+ ? { ...bm.cfg, rigid_row: bm.cfg.anatomy.rigid_row, axis_x: bm.cfg.anatomy.axis_x,
+ torso_half: bm.cfg.anatomy.torso_half }
+ : bm.cfg;
+ bctx.drawImage(bm.enabled ? breatheComposeForPreview(base, liveCfg, phase, breatheRef()) : base, 0, 0);
+ };
+ // 재생 타이밍 = 줄 프리뷰와 동일 계약: 현재 fps × 줄 배속(pv.speed)
+ // (maintainer 2026-07-18 "배속 해둔 거 확대해서도 배속으로"; fps 는 줄 스텝퍼로 실시간 변경)
+ const tickLoop = () => {
+ bm.tick += 1;
+ renderTick();
+ const live = run.states.find((s) => s.name === stateName);
+ const fps = (live && live.fps) || 6;
+ const speed = (previews[stateName] && previews[stateName].speed) || 1;
+ bm.timer = setTimeout(tickLoop, Math.max(40, 1000 / Math.max(0.1, fps * speed)));
+ };
+ tickLoop();
+
+ const initSilhouette = () => {
+ if (bm.geomReady) return true;
+ // 지오메트리 truth = **굽기가 해부를 확정하는 기준 프레임**의 합성 bbox.
+ // `rigid_row` 는 그 프레임의 콘텐츠 행 인덱스이고, 굽기는 그걸 `rigid_u` 비율로
+ // 바꿔 각 프레임에 건다. 모달이 열린 프레임(`idx`)을 재면 원점이 달라져 선의 화면
+ // 위치와 저장되는 행 번호가 굽기와 어긋난다 — 재생 순서만 바꿔도 도달하고,
+ // 골든 픽스처에서 8px(50px 캐릭터의 16%) 어긋났다 (validator 실측 2026-07-26).
+ // 변형·픽셀편집을 적용한 뒤 재는 것은 그대로다 (회귀 2026-07-18 maintainer).
+ const { index: refIdx, url: refUrl } = breatheGeometryFrame(stateName, idx);
+ const canonImg = refUrl ? img(refUrl) : null;
+ if (canonImg && canonImg.complete && canonImg.naturalWidth) {
+ const cvs = document.createElement("canvas");
+ cvs.width = cellW;
+ cvs.height = cellH;
+ const cctx = cvs.getContext("2d");
+ cctx.imageSmoothingEnabled = false;
+ drawFrameInto(cctx, canonImg, getTransform(stateName, refIdx), cellW, cellH,
+ snapScaleFor(stateName), getPixelOps(stateName, refIdx));
+ const dd = cctx.getImageData(0, 0, cellW, cellH).data;
+ let ttop = cellH, tbot = 0, tleft = cellW;
+ for (let y = 0; y < cellH; y++) {
+ for (let x = 0; x < cellW; x++) {
+ if (dd[(y * cellW + x) * 4 + 3] >= 40) {
+ if (y < ttop) ttop = y;
+ if (y + 1 > tbot) tbot = y + 1;
+ if (x < tleft) tleft = x;
+ }
+ }
+ }
+ if (tbot <= ttop) return false; // 아직 빈 합성 — 재시도 경로가 처리
+ btop = ttop;
+ bleft = tleft;
+ if (!bm.cfg.anatomy) {
+ // 해부 숫자는 서버에서만 나온다 — 여기서 추정하지 않는다 (b안, 2026-07-25).
+ // 도착 전까지 경계선은 숨겨져 있고 프리뷰는 원본 그대로다.
+ refreshAnatomy();
+ }
+ if (!e0.breathe && !beforeCfg && bm.histPos <= 0) {
+ const sib = run.states
+ .map((s) => (s.name !== stateName && entries[s.name] ? entries[s.name].breathe : null))
+ .find((b) => b && typeof b.depth === "number");
+ if (sib) {
+ bm.cfg.depth = sib.depth;
+ bm.cfg.depth_x = sib.depth_x == null ? null : sib.depth_x;
+ bm.cfg.breaths = sib.breaths;
+ bm.cfg.lag = sib.lag;
+ }
+ if (bm.histPos === 0) bm.hist[0] = { enabled: bm.enabled, cfg: clone(bm.cfg) };
+ }
+ bm.geomReady = true;
+ syncLines();
+ renderTick();
+ commit(); // 오픈 = truth 동기화 — enabled 승계, 꺼진 행을 강제로 켜지 않는다 (Esc 복원 가능)
+ rebuildStrip();
+ return true;
+ }
+ // 캐노니컬 이미지 미로드 = 아직 못 잰다 — 재시도 경로가 처리한다.
+ // (폴백 금지: 표시용 쌍둥이(compositeCell)는 변형 미적용 + 풋프린트가 달라
+ // 선이 엉뚱한 위치에 놓였다 — 회귀 2026-07-19 maintainer "어떨 때는 이상한 위치".)
+ return false;
+ };
+ // 최종 굽기 필름스트립 (maintainer 요청 2026-07-18 "최종 프레임들을 나열해서"):
+ // 시퀀스×호흡주기 LCM 전개를 그대로 보여준다 — GIF/아틀라스에 구워질 순서.
+ const strip = document.createElement("div");
+ strip.className = "breathe-strip";
+ // 스테이지 플렉스 행(.stage-row) 밖, 그 아래에 — 행 안에 넣으면 스테이지가 눌린다
+ (stage.closest(".stage-row") || stage).insertAdjacentElement("afterend", strip);
+ let stripTimer = null;
+ const rebuildStrip = () => {
+ const play = playList(stateName);
+ const pattern = bm.enabled ? breathePattern(bm.cfg, play.length) : new Array(play.length).fill(0);
+ strip.innerHTML = "";
+ if (!play.length) return;
+ const total = play.length; // 루프 불변 — 시퀀스 그대로 (maintainer 확정)
+ const actualBreaths = breatheFitCount(bm.cfg, play.length);
+ const cap = document.createElement("div");
+ cap.className = "bs-caption";
+ cap.textContent = bm.enabled
+ ? STR[lang].breatheStrip(play.length, actualBreaths)
+ : STR[lang].breatheStripOff(play.length);
+ strip.appendChild(cap);
+ const rowEl = document.createElement("div");
+ rowEl.className = "bs-frames";
+ for (let i = 0; i < total; i++) {
+ const frameIdx = play[i];
+ const phase = pattern[i] || 0;
+ const f = frameOf(stateName, frameIdx);
+ const bakeSrc = f && bakeFrameUrl(stateName, f);
+ const image = bakeSrc ? img(bakeSrc) : null;
+ const cellEl = document.createElement("div");
+ cellEl.className = "bs-cell";
+ const cv = document.createElement("canvas");
+ cv.width = cellW;
+ cv.height = cellH;
+ const cctx = cv.getContext("2d");
+ cctx.imageSmoothingEnabled = false;
+ if (image && image.complete && image.naturalWidth) {
+ const b = document.createElement("canvas");
+ b.width = cellW;
+ b.height = cellH;
+ const bx = b.getContext("2d");
+ bx.imageSmoothingEnabled = false;
+ drawFrameInto(bx, image, getTransform(stateName, frameIdx), cellW, cellH,
+ snapScaleFor(stateName), getPixelOps(stateName, frameIdx));
+ cctx.drawImage(bm.enabled ? breatheComposeForPreview(b, bm.cfg, phase, breatheRef()) : b, 0, 0);
+ }
+ cellEl.appendChild(cv);
+ const capEl = document.createElement("span");
+ capEl.className = "bs-cap";
+ const phaseTxt = Number.isInteger(phase) ? String(phase) : phase.toFixed(1);
+ capEl.textContent = `${frameDisplayName(stateName, frameIdx)} · P${phaseTxt}`;
+ cellEl.appendChild(capEl);
+ rowEl.appendChild(cellEl);
+ }
+ strip.appendChild(rowEl);
+ syncPixelScaling(strip); // 표시 샘플링 판정 = display.js 단일 소유자
+ };
+ const scheduleStrip = () => {
+ clearTimeout(stripTimer);
+ stripTimer = setTimeout(rebuildStrip, 220);
+ };
+
+ const bar = document.createElement("div");
+ bar.className = "breathe-bar";
+ // 호흡 on/off 토글 — 줄 헤더 체크박스와 같은 truth (maintainer 2026-07-19: 확대 재생
+ // 뷰에서도 끄고 켤 수 있게 — 끄면 선/조정 컨트롤이 쉬고 무호흡 재생만 남는다)
+ const onWrap = document.createElement("label");
+ onWrap.className = "unfake-apply breathe-enable";
+ onWrap.title = t("tRowBreathe");
+ const onCheck = document.createElement("input");
+ onCheck.type = "checkbox";
+ onCheck.checked = bm.enabled;
+ onCheck.addEventListener("change", () => {
+ bm.enabled = onCheck.checked;
+ syncBreatheControls();
+ syncLines();
+ commit();
+ pushHist();
+ setStatus(bm.enabled ? STR[lang].breatheOn(stateName) : STR[lang].breatheOff(stateName));
+ });
+ onWrap.appendChild(onCheck);
+ onWrap.appendChild(Object.assign(document.createElement("span"), { textContent: t("rowBreathe") }));
+ bar.appendChild(onWrap);
+ const mkSel = (values, current, fmt, onchange) => {
+ const sel = document.createElement("select");
+ for (const v of values) {
+ const o = document.createElement("option");
+ o.value = String(v);
+ o.textContent = fmt(v);
+ if (v === current) o.selected = true;
+ sel.appendChild(o);
+ }
+ sel.addEventListener("change", () => onchange(parseInt(sel.value, 10)));
+ return sel;
+ };
+ // 강체 경계는 하나뿐이라 +선/−선 버튼이 없다. 경계는 드래그로만 움직이고,
+ // 자동 검출값으로 되돌리는 버튼을 대신 둔다 (수동 override 해제).
+ const autoBtn = document.createElement("button");
+ autoBtn.type = "button";
+ autoBtn.className = "breathe-auto";
+ autoBtn.textContent = t("breatheAuto");
+ autoBtn.title = t("tBreatheAuto");
+ autoBtn.addEventListener("click", () => {
+ bm.cfg.rigid_row = null;
+ bm.cfg.axis_x = null; // 영역 오버라이드도 같은 버튼으로 자동 복귀 (2026-07-30)
+ bm.cfg.torso_half = null;
+ refreshAnatomy();
+ pushHist();
+ });
+ bar.appendChild(autoBtn);
+ // 진폭 = 몸통 높이 비율. px 가 아니라 비율이라 캐릭터가 달라도 같은 뜻을 갖는다.
+ const depthSel = mkSel([3, 4, 5, 6, 8, 10, 12], Math.round((bm.cfg.depth || 0.06) * 100),
+ (v) => `${t("breatheAmp")} ${v}%`,
+ (v) => { bm.cfg.depth = (v || 6) / 100; commit(); pushHist(); });
+ // 가로 독립 진폭 (maintainer 요청 2026-07-30): "따름" = depth 와 동일(레거시), 0 = 가로 끄기.
+ const depthXSel = document.createElement("select");
+ for (const v of ["follow", 0, 3, 4, 5, 6, 8, 10, 12]) {
+ const o = document.createElement("option");
+ o.value = String(v);
+ o.textContent = v === "follow" ? t("breatheAmpXFollow") : `${t("breatheAmpX")} ${v}%`;
+ depthXSel.appendChild(o);
+ }
+ depthXSel.value = bm.cfg.depth_x == null ? "follow" : String(Math.round(bm.cfg.depth_x * 100));
+ if (depthXSel.selectedIndex < 0) depthXSel.value = "follow"; // 목록 밖 수동값 — 표시만 따름으로
+ depthXSel.addEventListener("change", () => {
+ bm.cfg.depth_x = depthXSel.value === "follow" ? null : Number(depthXSel.value) / 100;
+ commit();
+ pushHist();
+ });
+ // 호흡 횟수: 숫자 입력 + −/+ 스텝퍼 (maintainer 2026-07-18 — 약수 셀렉트 대신 자유 입력;
+ // 나눠떨어지지 않으면 fit_breathe_pattern 이 보정하고 스트립 캡션이 알려준다)
+ const breathWrap = document.createElement("span");
+ breathWrap.className = "breathe-count";
+ breathWrap.title = STR[lang].tBreatheCount;
+ const breathLabel = document.createElement("span");
+ breathLabel.textContent = t("breatheCountLabel");
+ const minusBtn = document.createElement("button");
+ minusBtn.type = "button";
+ minusBtn.textContent = "−";
+ const breathInput = document.createElement("input");
+ breathInput.type = "number";
+ breathInput.min = "1";
+ breathInput.step = "1";
+ breathInput.value = String(bm.cfg.breaths || 1);
+ const plusBtn = document.createElement("button");
+ plusBtn.type = "button";
+ plusBtn.textContent = "+";
+ const setBreaths = (v) => {
+ const seqLen = playList(stateName).length || 1;
+ // 상한은 스키마(BREATHE_BREATHS_MAX)와 시퀀스 길이 둘 다 — 스키마를 넘기면 굽기가
+ // loud reject 하므로 컨트롤이 애초에 그 값을 못 만들게 한다.
+ const cap = Math.min(BREATHE_BREATHS_MAX, Math.max(1, seqLen));
+ const clamped = Math.max(1, Math.min(cap, Math.round(Number(v)) || 1));
+ bm.cfg.breaths = clamped;
+ breathInput.value = String(clamped);
+ commit();
+ pushHist();
+ syncFitBadge();
+ };
+ minusBtn.addEventListener("click", () => setBreaths((bm.cfg.breaths || 1) - 1));
+ plusBtn.addEventListener("click", () => setBreaths((bm.cfg.breaths || 1) + 1));
+ breathInput.addEventListener("change", () => setBreaths(breathInput.value));
+ const fitBadge = document.createElement("span");
+ fitBadge.className = "breathe-fit-badge";
+ const syncFitBadge = () => {
+ const seqLen = playList(stateName).length || 1;
+ const fitted = breatheFitCount(bm.cfg, seqLen);
+ const want = bm.cfg.breaths || 1;
+ // 요청 횟수가 루프에 안 나눠떨어지면 실제 적용 횟수를 그 자리에서 보여준다
+ fitBadge.textContent = fitted === want ? "" : STR[lang].breatheFitted(fitted);
+ fitBadge.title = fitted === want ? "" : STR[lang].tBreatheFitted(seqLen);
+ };
+ breathWrap.appendChild(breathLabel);
+ breathWrap.appendChild(minusBtn);
+ breathWrap.appendChild(breathInput);
+ breathWrap.appendChild(plusBtn);
+ breathWrap.appendChild(fitBadge);
+ bar.appendChild(depthSel);
+ bar.appendChild(depthXSel);
+ bar.appendChild(breathWrap);
+ toolbar.appendChild(bar);
+ function syncBreatheControls() {
+ onCheck.checked = bm.enabled;
+ const off = !bm.enabled;
+ for (const el of [autoBtn, depthSel, depthXSel, minusBtn, breathInput, plusBtn]) el.disabled = off;
+ depthSel.value = String(Math.round((bm.cfg.depth || 0.06) * 100));
+ depthXSel.value = bm.cfg.depth_x == null ? "follow" : String(Math.round(bm.cfg.depth_x * 100));
+ if (depthXSel.selectedIndex < 0) depthXSel.value = "follow";
+ breathInput.value = String(bm.cfg.breaths || 1);
+ syncFitBadge();
+ }
+ syncBreatheControls();
+
+ // Esc = 취소 (열기 전 설정으로 복원 — 없었으면 레이어 해제)
+ // 지오메트리 초기화는 스트립/컨트롤 선언 뒤에 — commit→scheduleStrip TDZ 방지
+ syncLines();
+ if (!initSilhouette()) {
+ let geomTries = 0;
+ const retryGeom = () => {
+ if (bm.cancelled || !document.body.contains(stage)) return;
+ if (!initSilhouette() && ++geomTries < 50) setTimeout(retryGeom, 120);
+ };
+ if (bImg) bImg.addEventListener("load", () => initSilhouette(), { once: true });
+ // 지오메트리는 **기준 프레임의 굽기 파일**에서 잰다 — 기다릴 로드도 그 이미지다.
+ // 다른 이미지의 로드를 기다리면 재시도가 엉뚱한 시점에 돌아 선이 안 잡힌다.
+ const geom0 = breatheGeometryFrame(stateName, idx);
+ const canon0 = geom0.url ? img(geom0.url) : null;
+ if (canon0 && !canon0.complete) canon0.addEventListener("load", () => initSilhouette(), { once: true });
+ setTimeout(retryGeom, 120);
+ }
+
+ zoomView.breatheCancel = () => {
+ bm.cancelled = true;
+ e0.breathe = beforeCfg;
+ scheduleSave();
+ rebuildState(stateName);
+ };
+ zoomView.breatheUndo = () => restoreHist(bm.histPos - 1);
+ zoomView.breatheRedo = () => restoreHist(bm.histPos + 1);
+ pushHist(); // 히스토리 바닥 = 오픈 시점 설정
+ zoomView.cleanupBreathe = () => {
+ clearTimeout(bm.timer);
+ clearTimeout(stripTimer);
+ if (!bm.cancelled) rebuildState(stateName); // 줄 미리보기·토글 상태 동기화
+ };
+ }
+
+ wireStage(stage, stateName, idx); // 베이스도 변형 동일 — 저장 시 파일에 굽는다 (maintainer 지시)
+ applyCardTransform(stage, stateName, idx);
+ syncUnfakeControls();
+ syncGridControls();
+ sizePxGrids();
+ document.addEventListener("keydown", onZoomKey);
+}
diff --git a/sprite_gen/serve/serve_compose.py b/sprite_gen/serve/serve_compose.py
new file mode 100644
index 0000000..523440d
--- /dev/null
+++ b/sprite_gen/serve/serve_compose.py
@@ -0,0 +1,445 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: Apache-2.0
+"""Serve the sprite-gen composition canvas — the "blank screen" assembly surface.
+
+This is the pre-run half of curation. The curation webview (`serve_curation.py`)
+edits ONE already-assembled run directory; this surface is what a human uses to
+*assemble* one in the first place, the step that until now only an agent could do
+by arranging a `--pngs-dir` folder and running `unpack_atlas_run`.
+
+The mental model is Obsidian-like: mount a local folder as a read-only candidate
+library, browse its tree, and drag image files onto named rows to compose a
+sprite. The composition is held virtually in the browser session as row->file
+*references* — no bytes are copied and the mounted originals are never touched.
+Materializing that session into a real run dir (the "build" seam that hands off
+to the curation view) is a later slice; this module owns only browse + canvas.
+
+ sprite-gen compose [--dir <folder>]
+
+Separate handler by design (SoC): the curation server is run-dir bound from the
+root (`CurationHandler.run_dir`), and assembly is a different concern that has no
+run dir yet. Keeping it a distinct surface avoids threading an "unbound" branch
+through every run-dir-assuming route.
+
+API:
+ GET / -> composer SPA
+ GET /composer/<asset> -> SPA static asset
+ POST /api/mount -> {dir} set the read-only library root, return its listing
+ GET /api/browse?dir=<abs> -> one directory level under the mounted root (lazy tree)
+ GET /api/browse-img?path= -> serve one image file under the mounted root
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import mimetypes
+import re
+import socket
+import subprocess
+import sys
+import time
+import urllib.request
+import webbrowser
+from functools import partial
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from pathlib import Path
+from urllib.parse import parse_qs, unquote, urlparse
+
+from sprite_gen.frames.unpack_atlas import import_png_groups
+
+# The SPA assets are package data (declared in pyproject's `package-data`), so the one
+# path that finds them is relative to this module — the same place in a repo checkout
+# and in an installed wheel. There is no second location to try.
+COMPOSER_DIR = Path(__file__).resolve().parent / "composer"
+
+IMAGE_SUFFIXES = {".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp"}
+
+CONTENT_TYPES = {
+ ".html": "text/html; charset=utf-8",
+ ".js": "text/javascript; charset=utf-8",
+ ".css": "text/css; charset=utf-8",
+ ".png": "image/png",
+ ".json": "application/json; charset=utf-8",
+}
+
+
+def _is_under(path: Path, root: Path) -> bool:
+ """True iff `path` resolves inside `root`. The traversal guard for browse/img:
+ the client names paths, so every filesystem read is confined to the mounted
+ root. Uses relative_to rather than string prefix so `/a/b2` is not treated as
+ under `/a/b`."""
+ try:
+ path.resolve().relative_to(root)
+ return True
+ except (ValueError, OSError):
+ return False
+
+
+def _list_dir(directory: Path, root: Path) -> dict:
+ """One directory level: subfolders first, then image files. Lazy — the UI
+ expands a folder by calling back with its path, so a deep library is not
+ walked up front. Non-image files and unreadable entries are omitted (the
+ library is a sprite candidate source, not a general file manager)."""
+ directory = directory.resolve()
+ if not _is_under(directory, root):
+ raise PermissionError(f"outside mounted root: {directory}")
+ if not directory.is_dir():
+ raise FileNotFoundError(f"not a directory: {directory}")
+ dirs, images = [], []
+ for entry in sorted(directory.iterdir(), key=lambda p: p.name.lower()):
+ if entry.name.startswith("."):
+ continue
+ try:
+ if entry.is_dir():
+ dirs.append({"name": entry.name, "path": str(entry), "type": "dir"})
+ elif entry.suffix.lower() in IMAGE_SUFFIXES and entry.is_file():
+ images.append({"name": entry.name, "path": str(entry), "type": "image"})
+ except OSError:
+ continue
+ return {"dir": str(directory), "entries": dirs + images}
+
+
+def _sanitize_state(name: str) -> str:
+ """A row name becomes a `frames/<state>` directory, so it must be a safe path
+ segment — no slashes (escape), no spaces. Non `[A-Za-z0-9_-]` runs collapse to
+ a single hyphen; an empty result falls back to `state`."""
+ slug = re.sub(r"[^A-Za-z0-9_-]+", "-", name.strip()).strip("-")
+ return slug or "state"
+
+
+def _build_groups(rows: list[dict], mount_root: Path) -> list[dict]:
+ """Turn the session's rows into `import_png_groups` groups. Empty rows are
+ skipped; every referenced file is re-confirmed under the mounted root (the
+ client names the paths). Sanitized names are de-duplicated so two rows cannot
+ collide onto one frames/<state> directory."""
+ groups: list[dict] = []
+ used: set[str] = set()
+ for row in rows:
+ cells = row.get("cells") or []
+ if not cells:
+ continue
+ paths = []
+ for cell in cells:
+ p = Path(str(cell.get("path", ""))).resolve()
+ if not _is_under(p, mount_root):
+ raise PermissionError(f"outside mounted root: {p}")
+ if p.suffix.lower() not in IMAGE_SUFFIXES or not p.is_file():
+ raise FileNotFoundError(f"not an image file: {p}")
+ paths.append(p)
+ name = _sanitize_state(str(row.get("name", "")))
+ base, n = name, 2
+ while name in used:
+ name, n = f"{base}-{n}", n + 1
+ used.add(name)
+ groups.append({"name": name, "paths": paths, "labels": [p.name for p in paths]})
+ return groups
+
+
+# One osascript per kind — `choose folder` and `choose file` are distinct macOS
+# primitives, and a single dialog that reliably selects both files and folders is
+# not available, so the two entry points map one-to-one instead. `choose file` for
+# images returns a newline-joined list of POSIX paths (multiple selections allowed).
+_PICK_SCRIPTS = {
+ "folder": 'POSIX path of (choose folder with prompt "Open a folder of images")',
+ "image": (
+ 'set picks to (choose file of type {"public.image"} '
+ 'with prompt "Open image(s)" with multiple selections allowed)\n'
+ 'set out to ""\n'
+ 'repeat with f in picks\n'
+ ' set out to out & POSIX path of f & linefeed\n'
+ 'end repeat\n'
+ 'return out'
+ ),
+}
+
+
+def native_pick(kind: str = "folder") -> dict:
+ """Pop the OS chooser and return a folder to mount.
+
+ kind="folder" -> {"dir": <abs path>}; kind="image" -> the picked image(s)'
+ parent folder {"dir": <parent>, "files": [<abs image paths>]} ("grab the
+ image's folder"). Cancel -> {"cancelled": True}. The browser cannot hand a
+ script an absolute path, but this server is local, so it asks the OS. Non-macOS
+ raises NotImplementedError so the caller can fall back explicitly (no silent
+ degradation)."""
+ if sys.platform != "darwin":
+ raise NotImplementedError("native picker is macOS-only")
+ script = _PICK_SCRIPTS.get(kind)
+ if script is None:
+ raise ValueError(f"unknown pick kind: {kind}")
+ proc = subprocess.run(["osascript", "-e", script], capture_output=True, text=True)
+ if proc.returncode != 0:
+ if "-128" in (proc.stderr or ""): # user canceled
+ return {"cancelled": True}
+ raise RuntimeError(proc.stderr.strip() or "osascript failed")
+ if kind == "folder":
+ picked = proc.stdout.strip()
+ return {"dir": picked} if picked else {"cancelled": True}
+ files = [line for line in proc.stdout.splitlines() if line.strip()]
+ if not files:
+ return {"cancelled": True}
+ # Mount the image's containing folder; multiple picks are assumed to share one.
+ return {"dir": str(Path(files[0]).parent), "files": files}
+
+
+def _free_port() -> int:
+ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ s.bind(("127.0.0.1", 0))
+ port = s.getsockname()[1]
+ s.close()
+ return port
+
+
+def _wait_ready(port: int, timeout: float = 12.0) -> bool:
+ deadline = time.time() + timeout
+ while time.time() < deadline:
+ try:
+ with urllib.request.urlopen(f"http://127.0.0.1:{port}/", timeout=1) as r:
+ if r.status == 200:
+ return True
+ except Exception:
+ time.sleep(0.25)
+ return False
+
+
+class ComposeHandler(BaseHTTPRequestHandler):
+ # Set by run(); the read-only library root. A mount replaces it in-process.
+ mount_root: Path | None = None
+ lang: str = "en"
+
+ def log_message(self, *args) -> None: # keep the console quiet
+ pass
+
+ # ── helpers ──────────────────────────────────────────────────────
+ def _send_json(self, payload: dict, code: int = 200) -> None:
+ body = json.dumps(payload).encode("utf-8")
+ self.send_response(code)
+ self.send_header("Content-Type", "application/json; charset=utf-8")
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+ def _send_file(self, path: Path, content_type: str | None = None) -> None:
+ data = path.read_bytes()
+ ctype = content_type or CONTENT_TYPES.get(path.suffix.lower()) \
+ or mimetypes.guess_type(str(path))[0] or "application/octet-stream"
+ self.send_response(200)
+ self.send_header("Content-Type", ctype)
+ self.send_header("Content-Length", str(len(data)))
+ self.end_headers()
+ self.wfile.write(data)
+
+ def _serve_spa_asset(self, rel: str) -> None:
+ # rel is like "src/tree.js" or "composer.css"; confine to COMPOSER_DIR.
+ target = (COMPOSER_DIR / rel).resolve()
+ if not _is_under(target, COMPOSER_DIR) or not target.is_file():
+ self._send_json({"error": "not found", "path": rel}, 404)
+ return
+ self._send_file(target)
+
+ # ── routes ───────────────────────────────────────────────────────
+ def do_GET(self) -> None:
+ path = urlparse(self.path).path
+ if path == "/":
+ index = COMPOSER_DIR / "index.html"
+ if not index.is_file():
+ self._send_json({"error": f"missing composer SPA: {index}"}, 500)
+ return
+ self._send_file(index)
+ return
+ if path == "/api/state":
+ self._send_json({
+ "lang": self.lang,
+ "mount": str(self.mount_root) if self.mount_root else None,
+ })
+ return
+ if path == "/api/browse":
+ query = parse_qs(urlparse(self.path).query)
+ if self.mount_root is None:
+ self._send_json({"error": "no folder mounted"}, 409)
+ return
+ requested = query.get("dir", [str(self.mount_root)])[0]
+ try:
+ self._send_json(_list_dir(Path(unquote(requested)), self.mount_root))
+ except PermissionError as exc:
+ self._send_json({"error": str(exc)}, 403)
+ except FileNotFoundError as exc:
+ self._send_json({"error": str(exc)}, 404)
+ return
+ if path == "/api/browse-img":
+ query = parse_qs(urlparse(self.path).query)
+ if self.mount_root is None:
+ self._send_json({"error": "no folder mounted"}, 409)
+ return
+ requested = query.get("path", [""])[0]
+ target = Path(unquote(requested)).resolve()
+ if not _is_under(target, self.mount_root):
+ self._send_json({"error": "outside mounted root"}, 403)
+ return
+ if target.suffix.lower() not in IMAGE_SUFFIXES or not target.is_file():
+ self._send_json({"error": "not an image", "path": requested}, 404)
+ return
+ self._send_file(target)
+ return
+ if path.startswith("/composer/"):
+ self._serve_spa_asset(path[len("/composer/"):])
+ return
+ # bare "/src/..." and "/composer.css" convenience roots so index.html can
+ # reference assets without the /composer/ prefix (matches curator layout).
+ if path.startswith("/src/") or path == "/composer.css":
+ self._serve_spa_asset(path.lstrip("/"))
+ return
+ self._send_json({"error": "not found", "path": path}, 404)
+
+ def do_POST(self) -> None:
+ path = urlparse(self.path).path
+ if path == "/api/mount":
+ length = int(self.headers.get("Content-Length", 0))
+ try:
+ payload = json.loads(self.rfile.read(length) or b"{}")
+ except json.JSONDecodeError:
+ self._send_json({"error": "invalid JSON body"}, 400)
+ return
+ raw = (payload.get("dir") or "").strip()
+ if not raw:
+ self._send_json({"error": "dir required"}, 400)
+ return
+ candidate = Path(raw).expanduser().resolve()
+ if not candidate.is_dir():
+ self._send_json({"error": f"not a directory: {candidate}"}, 404)
+ return
+ ComposeHandler.mount_root = candidate
+ self._send_json({"mount": str(candidate), **_list_dir(candidate, candidate)})
+ return
+ if path == "/api/pick":
+ kind = parse_qs(urlparse(self.path).query).get("kind", ["folder"])[0]
+ try:
+ self._send_json(native_pick(kind))
+ except NotImplementedError as exc:
+ self._send_json({"error": str(exc), "code": "unsupported-platform"}, 501)
+ except ValueError as exc:
+ self._send_json({"error": str(exc)}, 400)
+ except RuntimeError as exc:
+ self._send_json({"error": str(exc)}, 500)
+ return
+ if path == "/api/build":
+ # Materialize the virtual session into a real run dir via the SSoT
+ # importer (import_png_groups). The session is the unsaved buffer; this
+ # is the one place references become bytes on disk.
+ if self.mount_root is None:
+ self._send_json({"error": "no folder open"}, 409)
+ return
+ length = int(self.headers.get("Content-Length", 0))
+ try:
+ payload = json.loads(self.rfile.read(length) or b"{}")
+ except json.JSONDecodeError:
+ self._send_json({"error": "invalid JSON body"}, 400)
+ return
+ raw_out = (payload.get("outDir") or "").strip()
+ if not raw_out:
+ self._send_json({"error": "outDir required"}, 400)
+ return
+ out_dir = Path(raw_out).expanduser().resolve()
+ if out_dir.exists() and any(out_dir.iterdir()):
+ self._send_json({"error": f"output dir exists and is not empty: {out_dir}",
+ "code": "out-dir-not-empty"}, 409)
+ return
+ try:
+ groups = _build_groups(payload.get("rows") or [], self.mount_root)
+ except PermissionError as exc:
+ self._send_json({"error": str(exc)}, 403)
+ return
+ except FileNotFoundError as exc:
+ self._send_json({"error": str(exc)}, 404)
+ return
+ if not groups:
+ self._send_json({"error": "no rows with files to build"}, 400)
+ return
+ out_dir.mkdir(parents=True, exist_ok=True)
+ try:
+ summary = import_png_groups(out_dir, groups)
+ except Exception as exc: # surface the importer's failure, do not swallow
+ self._send_json({"error": f"build failed: {exc}"}, 500)
+ return
+ self._send_json({"runDir": str(out_dir), "states": summary.get("states", []),
+ "frames": summary.get("frames", 0), "cell": summary.get("cell")})
+ return
+ if path == "/api/open-curation":
+ # Hand off to the curation view: launch a serve_curation process on the
+ # built run dir and return its URL. A curation server is a legitimate
+ # long-lived per-run-dir surface, not a workaround.
+ length = int(self.headers.get("Content-Length", 0))
+ try:
+ payload = json.loads(self.rfile.read(length) or b"{}")
+ except json.JSONDecodeError:
+ self._send_json({"error": "invalid JSON body"}, 400)
+ return
+ run_dir = Path(str(payload.get("runDir", ""))).expanduser().resolve()
+ if not (run_dir / "sprite-request.json").is_file():
+ self._send_json({"error": f"not a run dir (no sprite-request.json): {run_dir}"}, 404)
+ return
+ port = _free_port()
+ subprocess.Popen(
+ [sys.executable, "-m", "sprite_gen.serve.serve_curation",
+ "--run-dir", str(run_dir), "--port", str(port), "--no-open"],
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
+ )
+ if not _wait_ready(port):
+ self._send_json({"error": "curation server did not become ready"}, 504)
+ return
+ self._send_json({"url": f"http://127.0.0.1:{port}/"})
+ return
+ self._send_json({"error": "not found", "path": path}, 404)
+
+
+def add_arguments(parser: argparse.ArgumentParser) -> None:
+ """Argument surface for `sprite-gen compose`, `python -m sprite_gen.serve.serve_compose`,
+ and any wrapper — declared once so no launch form can drift from another."""
+ parser.add_argument("--dir", type=Path, default=None,
+ help="initial folder to mount as the read-only library (optional; can also be mounted in the UI)")
+ parser.add_argument("--host", default="127.0.0.1")
+ parser.add_argument("--port", type=int, default=0, help="0 picks a free port")
+ parser.add_argument("--no-open", action="store_true", help="do not auto-open the browser")
+ parser.add_argument("--lang", choices=["en", "ko"], default="en",
+ help="initial UI language (toggleable in the webview)")
+
+
+def run(*, dir: Path | None = None, host: str = "127.0.0.1", port: int = 0,
+ no_open: bool = False, lang: str = "en") -> int:
+ """Serve the composition canvas until interrupted. Keyword-only, matching the
+ `cli.COMMANDS` run-fn convention (`run_fn(**vars(args))`)."""
+ if not COMPOSER_DIR.is_dir():
+ raise SystemExit(f"missing composer SPA dir: {COMPOSER_DIR}")
+ ComposeHandler.mount_root = dir.expanduser().resolve() if dir else None
+ ComposeHandler.lang = lang
+ if ComposeHandler.mount_root and not ComposeHandler.mount_root.is_dir():
+ raise SystemExit(f"not a directory: {ComposeHandler.mount_root}")
+
+ handler = partial(ComposeHandler)
+ server = ThreadingHTTPServer((host, port), handler)
+ host, port = server.server_address
+ url = f"http://{host}:{port}/"
+ print(f"sprite-gen composition canvas: {url}")
+ print(f" mounted: {ComposeHandler.mount_root or '(none — mount a folder in the UI)'}")
+ print(" Ctrl-C to stop.")
+ if not no_open:
+ webbrowser.open(url)
+ try:
+ server.serve_forever()
+ except KeyboardInterrupt:
+ print("\nstopped.")
+ finally:
+ server.server_close()
+ return 0
+
+
+def main(argv: list[str] | None = None) -> int:
+ """`python -m sprite_gen.serve.serve_compose` entrypoint."""
+ parser = argparse.ArgumentParser(description=__doc__)
+ add_arguments(parser)
+ return run(**vars(parser.parse_args(argv)))
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/sprite_gen/serve/serve_curation.py b/sprite_gen/serve/serve_curation.py
new file mode 100644
index 0000000..f6b3df4
--- /dev/null
+++ b/sprite_gen/serve/serve_curation.py
@@ -0,0 +1,1603 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: Apache-2.0
+"""Serve the sprite-gen curation webview for a single run directory.
+
+Standalone — no server framework, just the standard library plus the dependencies
+the pipeline already declares (Pillow, and NumPy via the `sprite_gen` import
+below that `heal_run` comes from). Launch it against any sprite-gen run folder
+and open the printed URL in a browser to compare frames per state, select/reject
+frames, and apply a non-destructive per-frame transform (rotate/scale/move). All
+edits are persisted to `curation.json` in the run directory; the original frame
+PNGs are never touched. The compose scripts read that sidecar and bake the result.
+
+ sprite-gen curation --run-dir <run-folder>
+
+Three entry forms reach this same module — the console script above, `python -m
+sprite_gen.serve.serve_curation`, and the `scripts/serve_curation.py` wrapper. They
+share one argument declaration (`add_arguments`) and one implementation (`run`),
+so none of them can drift from the others.
+
+This is intentionally a standalone skill tool (not a Studio panel) so it works
+from Claude Code Desktop, the Codex app, or any environment where the skill is
+installed.
+
+API:
+ GET / -> curator SPA
+ GET /api/run -> run state (cell, states, frames, current curation)
+ GET /frames/<state>/<f> -> a frame PNG
+ GET /run/<relpath> -> a file inside the run dir (atlas/qa previews)
+ POST /api/curation -> atomically write curation.json (request body)
+ POST /api/compose -> re-run the atlas compose step, return its result
+"""
+
+from __future__ import annotations
+
+import argparse
+import io
+import json
+import os
+import shutil
+import subprocess
+import sys
+import tempfile
+import threading
+import zipfile
+
+try:
+ from PIL import Image
+except ImportError: # pragma: no cover — 파이프라인 필수 의존성이지만 서버는 살아있게
+ Image = None
+import webbrowser
+from functools import partial
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from pathlib import Path
+from urllib.parse import parse_qs, quote, unquote, urlparse
+
+from sprite_gen.effects.breathe import (DEFAULT_DEPTH, DEFAULT_LAG, freeze_anatomy,
+ reference_key)
+from sprite_gen.curate.curation import (CURATION_FILENAME, SCHEMA_VERSION, effective_logical_height,
+ empty_curation, frame_variant, imported_ref_role,
+ load_curation, load_curation_report, pixel_snap_scale,
+ recolor_pick, run_revision, write_curation_atomic)
+from sprite_gen.frames.extract import heal_run, load_consistent_frames_manifest
+from sprite_gen.spec.layout import frames_dir_rel, raw_rel, row_frame_rel, row_orig_rel, state_frame_total
+from sprite_gen.spec.runio import load_request, publish_guard, read_guard, write_request
+from sprite_gen._modules import qualified
+
+# The SPA assets are package data (declared in pyproject's `package-data`), so the one
+# path that finds them is relative to this module — the same place in a repo checkout and
+# in an installed wheel. There is no second location to try.
+CURATOR_DIR = Path(__file__).resolve().parent / "curator"
+
+
+def _file_stamp(path: Path) -> str:
+ """파일의 정체성 — 크기:mtime_ns. 호흡 기준 프레임 키의 **원본 조각**이다.
+
+ 내용 해시가 더 정확하지만 상태 응답마다 줄의 모든 프레임을 읽어야 한다. 크기+mtime 은
+ 추출기가 파일을 다시 쓰면 반드시 바뀌므로 "기준 프레임이 갈렸나" 판정에 충분하고,
+ 틀리는 방향도 안전하다 — 런을 복사해 mtime 만 바뀌면 시끄럽게 거부하고 한 번 다시 잰다."""
+ st = path.stat()
+ return f"{st.st_size}:{st.st_mtime_ns}"
+
+
+def _url(*parts) -> str:
+ """/-rooted URL with every path segment percent-encoded. base/ref/state/frame names
+ can contain `#`, `%`, space, quotes, non-ASCII — unencoded they break the URL (a `#`
+ becomes a fragment → 404) or leak into HTML attributes. do_GET unquote()s on serving,
+ so this round-trips; unreserved names (e.g. down_walk, frame-0.png) are unchanged."""
+ return "/" + "/".join(quote(str(p), safe="") for p in parts)
+
+CONTENT_TYPES = {
+ ".html": "text/html; charset=utf-8",
+ ".js": "text/javascript; charset=utf-8",
+ ".css": "text/css; charset=utf-8",
+ ".png": "image/png",
+ ".json": "application/json; charset=utf-8",
+}
+
+
+
+# ── 픽셀 격자 자동 측정 ──────────────────────────────────────────────
+# fit.pixel_unfake 계약이 없는 런(예: --pngs-dir 임포트)에서도 격자 오버레이를 켠다:
+# 인접픽셀 색경계 위치가 한 간격의 배수에 몰려 있으면 그 간격이 블록 피치다.
+# 축별 브루트포스(경계 질량 ≥80% 인 최대 간격). 측정 실패한 줄은 격자를 그리지 않는다
+# (가짜 격자 금지). 결과는 (경로, mtime) 키로 캐시.
+_PITCH_CACHE: dict = {}
+_BASE_GRID_CACHE: dict = {} # (base path, mtime_ns) -> /api/base-grid 응답 (검출은 수 초짜리)
+
+
+def _breathe_source_frame(run_dir: Path, state: str):
+ """호흡 해부를 잴 프레임 — **굽기가 보는 것과 같은 픽셀**.
+
+ 굽기는 `apply_pixel_edits` -> `apply_transform` 뒤에 호흡을 얹으므로, 해부도 그
+ 변형 후 프레임에서 재야 한다. 원본 프레임에서 재면 지문이 매번 어긋나 self-heal 이
+ 돌고(동작은 맞지만) 웹뷰가 얼려둔 숫자와 굽기가 쓰는 숫자가 달라진다 — 미리보기와
+ 결과가 갈라지는 바로 그 경로다.
+
+ 해부는 상태 단위 상수라 첫 실재 프레임 하나면 충분하다 — 그리고 굽기도 그 계약을
+ 지킨다(`breathe.resolve_anatomy` 가 줄마다 한 벌만 확정한다). 예전엔 굽기가 프레임마다
+ 다시 재서 이 단언이 거짓이었고 프리뷰와 갈렸다 (validator 실측 2026-07-25)."""
+ from sprite_gen.curate.curation import (apply_pixel_edits, apply_transform, edit_index,
+ source_frame_index, state_pixel_ops, state_plan)
+ manifest = load_consistent_frames_manifest(run_dir, allow_pending_states=True) or {"rows": []}
+ row = next((r for r in manifest.get("rows", []) if r.get("state") == state), None)
+ if not row:
+ # **반환 모양은 하나다.** 한쪽만 맨 `None` 이면 호출부의 `frame, key = ...` 가
+ # `TypeError` 로 터져 의도한 404("no extracted frame") 대신 그 문구로 500 이 나간다
+ # — 추출이 아직 안 끝난 줄에서 호흡을 켜면 도달한다 (validator 실측 2026-07-26).
+ return None, None
+ request = load_request(run_dir)
+ curation = load_curation(run_dir)
+ variant = frame_variant(curation, state)
+ total = state_frame_total(request, state)
+ # 시그니처·키를 굽기(`compose_gif`)와 **같은 모양**으로 읽는다. 예전엔 인자 순서가
+ # 뒤바뀌고(`state_plan(curation, request, state)`) 없는 키(`request["cell_width"]`)를
+ # 읽어 이 라우트가 **항상 HTTP 500** 이었다 — 큐레이터에서 호흡을 켤 수조차 없었고
+ # 7라운드를 살아남은 건 이 경로를 태우는 테스트가 0개였기 때문이다 (validator 2026-07-26).
+ ordered, transforms = state_plan(curation, state, total)
+ cell_spec = request.get("cell", {})
+ cell = (int(cell_spec.get("width") or cell_spec.get("size") or 0),
+ int(cell_spec.get("height") or cell_spec.get("size") or 0))
+ if not all(cell):
+ raise SystemExit(f"breathe-anatomy: sprite-request 에 셀 크기가 없다 (cell={cell_spec!r})")
+ snap = pixel_snap_scale(request) if variant == "pixel" else None
+ for index in (ordered or list(range(total))):
+ # 재생 첫 슬롯이 복제면 그 인덱스로는 파일이 없다 — 원본 인덱스로 해소해야
+ # 굽기가 쓰는 기준 프레임과 같은 인스턴스를 잰다 (복제는 자기 변형을 가질 수 있다).
+ source_index = source_frame_index(curation, state, index, total)
+ candidate = run_dir / row_frame_rel(row, source_index, variant)
+ if not candidate.is_file():
+ continue
+ edit_idx = edit_index(curation, state, index)
+ ops = state_pixel_ops(curation, state).get(edit_idx)
+ with Image.open(candidate) as opened:
+ source = apply_pixel_edits(opened.convert("RGBA"), ops)
+ key = reference_key(state=state, variant=variant,
+ request_stamp=_file_stamp(run_dir / "sprite-request.json"),
+ source_index=source_index, source_stamp=_file_stamp(candidate),
+ pixel_ops=ops, transform=transforms.get(edit_idx))
+ return apply_transform(source, transforms.get(edit_idx), cell, snap_scale=snap), key
+ return None, None
+
+
+def _find_base_path(run_dir: Path):
+ for candidate in sorted(run_dir.glob("base-source.*")):
+ if candidate.suffix.lower() in (".png", ".jpg", ".jpeg", ".webp"):
+ return candidate
+ return None
+
+
+def _base_grid_response(run_dir: Path, base_path: Path) -> dict:
+ """베이스 검출 격자 응답 (mtime 키 캐시). GET /api/base-grid 와 base-edit 의
+ 논리→raw 확장이 같은 절단선을 쓴다 (SSoT — 클라와 서버가 다른 격자를 보면 안 됨)."""
+ cache_key = (str(base_path), base_path.stat().st_mtime_ns)
+ cached = _BASE_GRID_CACHE.get(cache_key)
+ if cached is not None:
+ return cached
+ request = load_request(run_dir)
+ chroma = tuple(request.get("chroma_key", {}).get("rgb") or (255, 0, 255))
+ from sprite_gen.frames.extract import (_grid_edges, detect_pixel_grid,
+ remove_chroma_background_ycbcr, solid_alpha_bbox)
+ with Image.open(base_path) as opened:
+ cleaned = remove_chroma_background_ycbcr(opened.convert("RGBA"), chroma)
+ box = solid_alpha_bbox(cleaned) or cleaned.getbbox()
+ if not box:
+ result = {"grid": None, "note": "base has no content to detect a grid on"}
+ else:
+ tight = cleaned.crop(box)
+ # 여기서 쓰는 위상은 `detect_pixel_grid` 의 히스토그램 위상이고, 추출 스냅이 쓰는
+ # 실측 위상(`_best_phase`)이 아니다. 이 절단선은 표시용이 아니라 **편집기의
+ # 샘플링·역기록 격자**를 겸한다 (위 docstring 의 SSoT 계약): base-editor.js 가
+ # 블록 중심을 raw 에서 샘플해 논리 캔버스를 만들고, space:"logical" ops 가 같은
+ # 절단선으로 raw 블록을 채워 base-source 에 굽는다. 즉 위상이 밀리면 추출 스냅과
+ # 같은 계열의 오배치가 난다. 그럼에도 추출 정책을 강제하지 않는 이유는 대상이
+ # 별개 이미지(base-source)이고 사람이 보며 편집하는 경로이기 때문이며, 이 경로의
+ # 위상 정확도는 별건이다 (docs/pixel-unfake.md "위상은 근사가 아니라 실측으로 고른다").
+ (pitch_x, pitch_y), (phase_x, phase_y) = detect_pixel_grid(tight)
+ if min(pitch_x, pitch_y) < 2.0:
+ result = {"grid": None, "note": "no confident pixel grid detected"}
+ else:
+ x_edges = [box[0] + e for e in _grid_edges(tight.width, pitch_x, phase_x)]
+ y_edges = [box[1] + e for e in _grid_edges(tight.height, pitch_y, phase_y)]
+ result = {"grid": {"xEdges": x_edges, "yEdges": y_edges,
+ "pitch": [round(pitch_x, 2), round(pitch_y, 2)]}}
+ _BASE_GRID_CACHE.clear() # 베이스는 런당 1개 — 이전 세대 항목만 치움
+ _BASE_GRID_CACHE[cache_key] = result
+ return result
+
+
+def _uniform_blocks(px, w, h, k):
+ """이미지가 k×k 단색 블록으로만 이루어졌는가 (정확 판정)."""
+ for by in range(0, h, k):
+ for bx in range(0, w, k):
+ first = px[bx, by]
+ for y in range(by, by + k):
+ for x in range(bx, bx + k):
+ if px[x, y] != first:
+ return False
+ return True
+
+
+def detect_pixel_pitch(path):
+ """이 프레임에서 논리 픽셀 1개가 차지하는 셀 픽셀 수 — **항상 ≥1, 실패 없음**.
+
+ 정확 판정이다(추정 아님): 이미지가 k×k 단색 블록으로만 이루어져 있으면 그건
+ k 배 확대본이고, 조건을 만족하는 **최대 k** 가 답이다. k=1 은 1×1 블록이
+ 자명히 단색이라 언제나 참이므로 이 측정은 **실패할 수 없다** — 즉 "격자를
+ 모른다" 라는 상태 자체가 존재하지 않고, 그래서 격자 컨트롤을 숨길 근거도 없다.
+
+ 왜 추정을 버렸나 (maintainer 2026-07-24, "10번 넘게 말한" 조건부 숨김 버그의 뿌리):
+ 옛 구현은 엣지 자기상관으로 피치를 **추정**하고 2 미만이면 None 으로 접었다.
+ 그 결과 (a) 이미 논리 해상도인 1:1 픽셀아트가 전부 "검출 실패"로 접혀
+ 임포트 런에 격자 버튼이 아예 뜨지 않았고, (b) 실측상 실제 스프라이트
+ 프레임에서도 거의 항상 None 이라 임포트 런은 사실상 격자를 가진 적이 없다.
+ 엔진의 주기성 검출기(`detect_pixel_grid`)도 대안이 못 된다 — 1:1 프레임에
+ 4.99 를 냈다(캐릭터 디자인의 반복 무늬를 격자로 오인).
+ 블록 단색성은 그런 오인이 구조적으로 불가능하다."""
+ if Image is None:
+ return 1
+ try:
+ stat = os.stat(path)
+ except OSError:
+ return 1
+ key = (str(path), stat.st_mtime_ns)
+ if key in _PITCH_CACHE:
+ return _PITCH_CACHE[key]
+ scale = 1
+ try:
+ with Image.open(path) as im:
+ im = im.convert("RGBA")
+ px = im.load()
+ w, h = im.size
+ # 양축을 나누어떨어지게 하는 k 만 후보 (블록이 이미지에 딱 맞아야 한다)
+ for k in range(min(w, h), 1, -1):
+ if w % k or h % k:
+ continue
+ if _uniform_blocks(px, w, h, k):
+ scale = k
+ break
+ except OSError:
+ scale = 1
+ _PITCH_CACHE[key] = scale
+ return scale
+
+
+_REF_DIRECTIONS = ("down45", "up45", "down", "side", "up", "left", "right", "front", "back")
+
+
+def _anchor_views(run_dir: Path, request: dict, curation: dict | None, version: str) -> dict:
+ """방향별 앵커 상태 + 칩 URL. 방향당 한 번만 해석한다 (상태마다 재해석 금지).
+
+ 칩은 **라이브 베이크**(`/api/anchor`)를 가리킨다 — `references/anchors/*.png` 는
+ 생성 직전에 갱신되는 파생 캐시라, 그 파일을 칩으로 보여주면 사용자가 방금 한 편집
+ 이전 모습이 화면에 남는다 (회귀 2026-07-19). `v=` 는 표시 캐시 무효화용이다."""
+ from sprite_gen.curate import anchor as anchor_mod
+
+ views = {}
+ for direction in anchor_mod.directions(request):
+ status = anchor_mod.anchor_status(run_dir, request, curation, direction)
+ url = None
+ if not status.get("error"):
+ url = f"/api/anchor?direction={quote(direction, safe='')}&v={quote(version, safe='')}"
+ views[direction] = {**status, "url": url}
+ return views
+
+
+def _anchor_group_fields(view: dict) -> dict:
+ """directionGroups 항목에 실리는 앵커 필드. `pending`(그 행을 아직 안 뽑았다)은
+ 오류가 아니라 정상 구간이라 뷰가 경고색으로 칠하지 않는다 — 코드로 구분한다."""
+ return {
+ "anchorFrame": ({"state": view["state"], "index": view["index"], "source": view["source"]}
+ if view.get("state") is not None else None),
+ "anchorError": view.get("error"),
+ "anchorErrorCode": view.get("code"),
+ "anchorPending": bool(view.get("pending")),
+ "anchorUrl": view.get("url"), # 라이브 베이크 (파이프라인 트리 썸네일도 이걸 쓴다)
+ }
+
+
+def _state_refs(run_dir, state, request, anchor_views=None):
+ """상태 하나의 생성 레퍼런스 체인(방향 앵커/basis row/레이아웃 가이드).
+
+ directional-anchor 규약의 관례 유도 — run dir 에 실재하는 파일만 노출한다.
+ 앵커만 예외로 라이브 베이크 URL 을 쓴다 (_anchor_views 주석 참조).
+ """
+ refs = []
+ anchor_views = anchor_views or {}
+ direction = None
+ contract_directions = [str(d) for d in ((request.get("directions") or {}).get("set") or [])]
+ # 방향 계약이 있으면 그게 진실이고, 없는 런(임포트 등)만 이름 관례로 추정한다
+ for d in (contract_directions or _REF_DIRECTIONS):
+ if state == d or state.startswith(d + "_"):
+ direction = d
+ break
+ if direction is not None:
+ suffix = str((request.get("directions") or {}).get("anchor_suffix", "idle"))
+ anchor_state_name = f"{direction}_{suffix}"
+ view = anchor_views.get(direction) or {}
+ anchor_rel = raw_rel(request, anchor_state_name)
+ anchor = run_dir / anchor_rel
+ if state != anchor_state_name:
+ if view.get("url"):
+ refs.append({"role": "anchor",
+ "name": f"{view['state']}#{view['index']}"
+ f"{' · picked' if view.get('source') == 'picked' else ''}",
+ "url": view["url"], "anchorFrame": True})
+ elif anchor.is_file():
+ # 앵커 행이 아직 큐레이션/추출 전 — 실재하는 raw 스트립을 그대로 보여준다
+ refs.append({"role": "anchor", "name": anchor.name, "url": _url("run", *anchor_rel.split("/"))})
+ base = state[len(direction) + 1:] if state.startswith(direction + "_") else None
+ if base and direction != "down":
+ basis_rel = raw_rel(request, f"down_{base}")
+ basis = run_dir / basis_rel
+ if basis.is_file():
+ refs.append({"role": "basis", "name": basis.name, "url": _url("run", *basis_rel.split("/"))})
+ guide = run_dir / "references" / "layout-guides" / f"{state}.png"
+ if guide.is_file():
+ refs.append({"role": "guide", "name": guide.name, "url": _url("run", "references", "layout-guides", f"{state}.png")})
+ # imported runs (--pngs-dir): references/imported/<state>/<role>-<name>.png → 생성 재료 칩.
+ # role 파싱 SSoT = curation.imported_ref_role. 미지 role 은 스킵한다 — import 가 fail-loud
+ # 로 걸러 여기 도달하지 않지만, 손으로 놓인 파일도 조용히 guide 로 relabel 하지 않는다.
+ imported_dir = run_dir / "references" / "imported" / state
+ if imported_dir.is_dir():
+ for ref in sorted(imported_dir.glob("*.png")):
+ role = imported_ref_role(ref.name)
+ if role is None:
+ continue
+ refs.append({"role": role, "name": ref.name,
+ "url": _url("run", "references", "imported", state, ref.name)})
+ return refs
+
+
+
+def _read_op_progress(run_dir: Path) -> dict | None:
+ """엔진이 기록한 진행 파일 (.sprite-gen.progress.json) — 없으면 None."""
+ try:
+ return json.loads((run_dir / ".sprite-gen.progress.json").read_text(encoding="utf-8"))
+ except (OSError, ValueError):
+ return None
+
+
+def build_run_state(run_dir: Path) -> dict:
+ """Assemble the run snapshot the SPA needs. Read under the run dir's shared read_guard
+ so a concurrent `--force` re-import (which holds the exclusive publish_guard for its
+ swap) can never expose a half-published state to `/api/run` — the reader sees either
+ the complete prior run or the complete new run (reader isolation)."""
+ with read_guard(run_dir):
+ return _build_run_state_impl(run_dir)
+
+
+def _build_run_state_impl(run_dir: Path) -> dict:
+ """Assemble the run snapshot the SPA needs, from the canonical SSoT files."""
+ request = load_request(run_dir)
+ # No generation yet (no manifest AND no physical frames) → serve the request/state scaffold
+ # (legitimate). A present-but-corrupt/inconsistent manifest, or an orphan (frames without a
+ # manifest), fails loud (load_consistent_frames_manifest raises) and surfaces as HTTP 500 in
+ # do_GET — never a silent empty-rows / stale-frame fallback (No Silent Fallback / Consistency).
+ frames_manifest = load_consistent_frames_manifest(run_dir, allow_pending_states=True) or {"rows": []}
+ rows_by_state = {row["state"]: row for row in frames_manifest.get("rows", [])}
+
+ # 큐레이션은 앵커 해석의 입력이라 상태 루프보다 먼저 읽는다 (앵커 칩이 방향별로
+ # 한 번 해석된 결과를 쓴다 — 상태마다 재해석하면 같은 방향에 다른 답이 나올 수 있다).
+ curation, curation_report = load_curation_report(run_dir)
+ curation = curation or empty_curation()
+ revision = run_revision(run_dir)
+ anchor_views = _anchor_views(run_dir, request, curation, revision)
+
+ cell = request["cell"]
+ cell_state = {
+ "width": int(cell.get("width", cell.get("size", 0))),
+ "height": int(cell.get("height", cell.get("size", 0))),
+ # 안전영역/여백 알림 계산용 (여백 침범 = 정보성, 리롤 대상 아님)
+ "safeMarginX": int(cell.get("safe_margin_x", cell.get("safe_margin", 0))),
+ "safeMarginY": int(cell.get("safe_margin_y", cell.get("safe_margin", 0))),
+ }
+
+ # 픽셀 언페이크 격자: 논리 픽셀 1칸이 셀 픽셀 몇 칸인가. extract 의 pp_scale 과 같은 식이어야
+ # 큐레이터 오버레이가 "실제로 스냅된 격자"를 그린다 (셀 래스터가 아니라).
+ fit = request.get("fit") or {}
+ pixel_unfake = None
+ if fit.get("pixel_unfake"):
+ # 배율·논리 높이는 파생값 SSoT 에서 받는다 — 손으로 복제한 식은 클램프 분기가
+ # 빠져 있었고, 선언값을 그대로 라벨에 쓰면 정수 격자가 반올림한 뒤에도 "48px"
+ # 처럼 거짓 표기가 된다 (maintainer 2026-07-25).
+ scale = pixel_snap_scale(request) or 1
+ logical_height = effective_logical_height(request) or cell_state["height"]
+ pixel_unfake = {"logicalHeight": logical_height, "scale": scale, "source": "request", "label": f"{logical_height}px"}
+
+ states = []
+ # 온디맨드 픽셀 프리뷰 계산 예산 (요청당) — 초과분은 deferred 로 세서 보고한다
+ for state, entry in request["states"].items():
+ row = rows_by_state.get(state, {})
+ files = row.get("files", [])
+ labels = row.get("labels", [])
+ frame_count = state_frame_total(request, state)
+ state_raw_rel = raw_rel(request, state)
+ raw_present = (run_dir / state_raw_rel).is_file()
+ state_frames_rel = frames_dir_rel(request, state)
+ frames = []
+ for index in range(frame_count):
+ # 파일 위치 SSoT = manifest row files (병합 후보 등 비패턴 경로 포함).
+ # row 가 없거나(index 초과 포함) 미생성이면 리졸버의 예약 위치로 표시.
+ row_files = row.get("files") or []
+ if index < len(row_files):
+ rel = row_files[index]
+ else:
+ rel = f"{state_frames_rel}/frame-{index}.png"
+ present = (run_dir / rel).is_file()
+ frame = {"index": index, "url": _url(*rel.split("/")), "present": present}
+ # pp 해제 토글 표시본: 원본 화질(orig/ 고해상본) 우선, 없으면 셀 크기 .plain.png.
+ # 둘 중 하나라도 있으면 큐레이터가 전/후 토글을 켠다.
+ head, _, tail = rel.rpartition("/")
+ orig_rel = f"{head}/orig/{tail}"
+ plain_rel = rel[: -len(".png")] + ".plain.png"
+ if (run_dir / orig_rel).is_file():
+ frame["plainUrl"] = _url(*orig_rel.split("/"))
+ elif (run_dir / plain_rel).is_file():
+ frame["plainUrl"] = _url(*plain_rel.split("/"))
+ # **굽기가 실제로 읽는 파일** — `row_frame_rel(row, i, "plain")` 과 같은 경로다.
+ # 위 `plainUrl` 은 표시 화질용이라 `orig/` 고해상본을 우선하는데, 굽기는 그걸
+ # 절대 안 읽는다. 호흡 프리뷰·신선도 판정이 `plainUrl` 을 쓰면 지문이 **영구
+ # 불일치**라 그 줄의 영상 내보내기가 영구 차단된다 (validator 2026-07-26).
+ if present:
+ frame["stamp"] = _file_stamp(run_dir / rel)
+ if (run_dir / plain_rel).is_file():
+ frame["plainBakeUrl"] = _url(*plain_rel.split("/"))
+ # URL 과 **짝으로** 나간다. 굽기가 읽는 파일이 곧 호흡 기준 프레임 키의
+ # 원본 조각이라, 둘 중 하나만 보내면 웹뷰가 키를 못 만든다.
+ frame["plainBakeStamp"] = _file_stamp(run_dir / plain_rel)
+ # 트윈 없는 프레임의 퍼펙은 클라 렌더러가 측정 k(pixelScale)로 양자화한다
+ # — 서버 추정 스냅 프리뷰 레거시는 표시 격자와 다른 검출기(엔진 주기성,
+ # 1:1 에 4.99)로 스냅해 같은 줄의 프레임마다 다른 진실을 만들었다
+ # (validator R1 기각, plan curator-single-display-pipeline 에서 삭제).
+ if index < len(labels):
+ frame["label"] = labels[index]
+ # 추출이 검출한 실제 절단선 (쌍둥이 셀 좌표) — 원본 화질 뷰의 최종 대응
+ # 격자가 균등 분할 대신 이 선을 그린다 (중간 드리프트 제거)
+ row_grids = row.get("input_grids") or []
+ if index < len(row_grids) and row_grids[index]:
+ frame["inputGrid"] = row_grids[index]
+ if present and Image is not None:
+ # 실제 스프라이트 픽셀 크기(투명 패딩 제외 알파 bbox) — 사이즈 통일 검수용
+ try:
+ with Image.open(run_dir / rel) as im:
+ frame["size"] = [im.width, im.height]
+ alpha = im.getchannel("A") if "A" in im.getbands() else None
+ bbox = alpha.getbbox() if alpha is not None else im.getbbox()
+ if bbox:
+ frame["contentSize"] = [bbox[2] - bbox[0], bbox[3] - bbox[1]]
+ # 최종 픽셀 콘텐츠 bbox(셀 좌표) — 원본 뷰의 "최종 대응 격자"
+ # (칸 수 = 최종 픽셀 수)가 이 상자를 균등 분할해 그린다
+ frame["contentBox"] = list(bbox)
+ except OSError:
+ pass
+ frames.append(frame)
+ state_scale = None
+ if pixel_unfake is not None:
+ state_scale = pixel_unfake["scale"]
+ else:
+ for fr in frames:
+ if fr.get("present"):
+ # measure from the real (decoded) file path, not fr["url"] — the url is
+ # percent-encoded for HTTP, so a special-char state name would point the
+ # measurement at a nonexistent encoded dir → pixelScale silently null.
+ row_files_m = row.get("files") or []
+ rel_m = row_files_m[fr["index"]] if fr["index"] < len(row_files_m) else f"{state_frames_rel}/frame-{fr['index']}.png"
+ state_scale = detect_pixel_pitch(run_dir / rel_m)
+ break
+ if state_scale is None:
+ # 미추출 줄(present 프레임 0)도 계약을 지킨다: pixelScale ≥1, never null
+ # (validator N2). 그릴 스테이지가 없어 표시엔 관성 없지만 계약-코드 정합.
+ state_scale = 1
+ states.append(
+ {
+ "name": state,
+ "rawPresent": raw_present,
+ "pixelScale": state_scale,
+ "refs": _state_refs(run_dir, state, request, anchor_views),
+ "fps": int(entry.get("fps", 6)),
+ "loop": bool(entry.get("loop", True)),
+ "action": entry.get("action", ""),
+ "requestFrames": frame_count,
+ "extractOk": bool(row.get("ok", bool(files))),
+ "frames": frames,
+ # 테이크 선언 (호흡 에디터가 저장된 선/진폭을 복원하는 데 쓴다)
+ "takes": entry.get("takes") or [],
+ }
+ )
+
+ # 방향 계약 런: 뷰가 방향 그룹(앵커 우선)으로 묶고 미러 방향(생성 생략)을 표시한다.
+ directions_cfg = request.get("directions")
+ direction_groups = None
+ if directions_cfg and directions_cfg.get("set"):
+ suffix = directions_cfg.get("anchor_suffix", "idle")
+ direction_groups = []
+ for direction in directions_cfg["set"]:
+ anchor = f"{direction}_{suffix}"
+ members = [s for s in request["states"] if s.startswith(direction + "_")]
+ # 앵커를 그룹 맨 앞으로 (요청 순서 보존, 앵커만 승격)
+ if anchor in members:
+ members = [anchor, *[m for m in members if m != anchor]]
+ # 지금 이 방향의 identity 로 쓰이는 인스턴스 (지정 or 앵커 행 시퀀스 헤드)
+ # — 뷰가 그 카드에 앵커 배지를 붙이고, 해석 실패는 이유를 보여준다.
+ direction_groups.append({
+ "direction": direction,
+ "anchor": anchor if anchor in request["states"] else None,
+ "states": members,
+ **_anchor_group_fields(anchor_views.get(direction) or {}),
+ })
+ for target, source in (directions_cfg.get("mirror") or {}).items():
+ direction_groups.append({"direction": target, "mirrorOf": source, "states": []})
+
+ # 방향 앵커 파일 (references/anchors/*.png) — 파일트리 표시용
+ anchors_dir = run_dir / "references" / "anchors"
+ anchor_files = []
+ if anchors_dir.is_dir():
+ for path in sorted(anchors_dir.glob("*.png")):
+ anchor_files.append({"name": path.name, "url": _url("run", "references", "anchors", path.name)})
+
+ # 원본 베이스(아이덴티티 truth)가 있으면 큐레이터 최상단에 참조 줄로 노출
+ base_url = None
+ for candidate in sorted(run_dir.glob("base-source.*")):
+ if candidate.suffix.lower() in (".png", ".jpg", ".jpeg", ".webp"):
+ base_url = _url("run", candidate.name)
+ break
+ # 뷰 계약 자가 보고 (run-contract.md §3): base 참조 줄 / 생성 재료 칩 / 픽셀 격자
+ # 충족 여부. 셋 다 없으면 "소스 없는 뷰" — 세션마다 경험이 갈라지는 신호.
+ has_base = base_url is not None
+ refs_states = sum(1 for st in states if st.get("refs"))
+ # 격자는 언제나 있다 — `detect_pixel_pitch` 가 실패할 수 없는 정확 판정이라
+ # 모든 상태가 ≥1 의 scale 을 갖는다. 조건부 False 는 곧 컨트롤 숨김이었고
+ # 그게 버그였다 (maintainer 2026-07-24).
+ has_grid = True
+ contract = {
+ "base": has_base,
+ "refs": refs_states > 0,
+ "refsStates": refs_states,
+ "grid": has_grid,
+ # 격자가 보편이 된 뒤로는 판별자가 못 된다 — 항상 참인 항을 or 에 두면
+ # sourceless 가 영원히 False 라 경고가 죽는다. 남은 판별자(base/refs)로만 본다.
+ "sourceless": not (has_base or refs_states > 0),
+ }
+ return {
+ "characterId": request["character"]["id"],
+ "runDir": str(run_dir),
+ "baseUrl": base_url,
+ "cell": cell_state,
+ # 계약 scale(pp 런)이 없으면 줄별 실측이 진실이다 — null 로 접지 않는다.
+ "pixelUnfake": pixel_unfake if pixel_unfake is not None else {
+ "source": "auto", "label": "auto",
+ "scale": min((st["pixelScale"] for st in states if st.get("pixelScale")), default=1)},
+ "schemaVersion": SCHEMA_VERSION,
+ "runRevision": revision,
+ # 호흡 기준 프레임 키의 조각 — 셀 크기·`pixel_snap_scale` 같은 request 파생값을
+ # 웹뷰가 재구현하지 않고 원인 하나로 덮는다 (`breathe.reference_key` 주석).
+ "requestStamp": _file_stamp(run_dir / "sprite-request.json"),
+ "directionGroups": direction_groups,
+ "anchorFiles": anchor_files,
+ "states": states,
+ "curation": curation,
+ # 세대 불일치로 이번 로드에서 무효화(드롭)된 행 — 뷰가 배너로 알린다 (stderr 만으로는
+ # 사용자가 못 본다; 조용한 소실 금지). 백업 파일명은 싣지 않는다: 로드는 아무것도
+ # 쓰지 않고, 원문은 덮이는 순간 writer 가 백업한다 (`write_curation_atomic`).
+ "curationDropped": curation_report["dropped"],
+ "iso": request.get("iso"),
+ "lang": CurationHandler.lang,
+ "hasAtlas": (run_dir / "sprite-sheet-alpha.png").is_file(),
+ # 최종 산출물 섹션 (뷰 맨 아래, 아틀라스+manifest 좌우) — 파일이 실재할 때만.
+ # 아틀라스는 다운로드/합성 시점 산출물이라 mtime 을 실어 시점을 표시한다.
+ "atlas": _atlas_info(run_dir),
+ # 팔레트 스왑 베이크 산출물 (`<run>/variants/`) — 없으면 None (섹션 자체가 안 뜬다).
+ "recolor": _recolor_info(run_dir, curation),
+ "fitPixelUnfake": bool((request.get("fit") or {}).get("pixel_unfake")),
+ # 예산에 밀려 아직 못 만든 온디맨드 픽셀 프리뷰 수 — 0 이 아니면 리로드가 이어서 계산
+ "contract": contract,
+ }
+
+
+def _first_frame_rect(run_dir: Path) -> dict | None:
+ """Where the atlas's first frame sits, from the manifest's `frame_layout`.
+
+ Colourway thumbnails crop to this box: a colour swap reads on a sprite, not on a
+ 1280px strip shrunk to a chip. The rect comes from the layout the compose step
+ wrote — the view does not assume "frame 0 is at the origin", because a layout that
+ ever changes would leave the thumbnails cropping the wrong pixels and looking right.
+ None (no manifest, or no layout in it) means the thumbnails show the whole sheet:
+ there is no frame box to crop to, and inventing one would be a display lie.
+ """
+ try:
+ manifest = json.loads((run_dir / "manifest.json").read_text(encoding="utf-8"))
+ except (OSError, ValueError):
+ return None
+ layout = manifest.get("frame_layout")
+ if not isinstance(layout, dict):
+ return None
+ rows = layout.get("rows")
+ if not isinstance(rows, dict):
+ return None
+ for cells in rows.values():
+ if isinstance(cells, list) and cells and isinstance(cells[0], dict):
+ cell = cells[0]
+ try:
+ return {
+ "x": int(cell["x"]), "y": int(cell["y"]),
+ "w": int(cell["w"]), "h": int(cell["h"]),
+ "sheetWidth": int(layout["sheetWidth"]),
+ "sheetHeight": int(layout["sheetHeight"]),
+ }
+ except (KeyError, TypeError, ValueError):
+ return None
+ return None
+
+
+def _recolor_info(run_dir: Path, curation: dict | None) -> dict | None:
+ """Baked recolor variants + the adopted pick, for the view's variant section.
+
+ None = this run has no bake report (`recolor.load_report` owns that judgement,
+ and fails loud on a foreign file). Everything the section shows comes from the
+ report — the view never re-derives colour counts, so the numbers it prints are
+ the numbers the bake measured.
+
+ A variant sheet whose PNG is missing is reported with `present: false` rather
+ than dropped: a report row without its sheet means the bake was interrupted or
+ the file was deleted, and a silently shorter list would read as "that variant
+ was never baked".
+ """
+ from sprite_gen.effects.recolor import VARIANTS_DIRNAME, load_report
+
+ report = load_report(run_dir)
+ if report is None:
+ return None
+ variants = []
+ for entry in report.get("variants", []):
+ sheet = str(entry.get("sheet") or "")
+ path = run_dir / VARIANTS_DIRNAME / sheet
+ present = bool(sheet) and path.is_file()
+ manifest_name = entry.get("manifest")
+ variants.append({
+ "name": entry.get("name"),
+ "sheet": sheet,
+ # mtime cache-bust: a re-bake rewrites the same filename, and a stale
+ # browser cache would show the previous colourway under the new name.
+ "url": (_url("run", VARIANTS_DIRNAME, sheet) + f"?v={int(path.stat().st_mtime)}") if present else None,
+ "present": present,
+ "substitutedPixels": entry.get("substituted_pixels"),
+ "passthroughPixels": entry.get("passthrough_pixels"),
+ "passthroughColorCount": entry.get("passthrough_color_count"),
+ "unusedSources": [record.get("from") for record in entry.get("unused_sources", [])],
+ "manifestUrl": (_url("run", VARIANTS_DIRNAME, str(manifest_name))
+ if isinstance(manifest_name, str) else None),
+ })
+ base_name = str(report.get("base") or "")
+ base_path = run_dir / base_name if base_name else None
+ base_present = bool(base_name) and base_path.is_file()
+ picked = recolor_pick(curation)
+ return {
+ "dir": VARIANTS_DIRNAME,
+ # 썸네일이 잘라 볼 프레임 상자 (없으면 시트 전체를 보여준다 — _first_frame_rect 참조)
+ "swatch": _first_frame_rect(run_dir),
+ "match": report.get("match"),
+ "tolerance": report.get("tolerance"),
+ "base": {
+ "name": base_name,
+ "url": (_url("run", base_name) + f"?v={int(base_path.stat().st_mtime)}") if base_present else None,
+ "present": base_present,
+ },
+ "variants": variants,
+ "picked": picked,
+ # The pick is stored by name; if the spec dropped that variant the name is
+ # kept and flagged, so the view can say so instead of quietly un-picking.
+ "pickedKnown": picked is not None and any(v["name"] == picked for v in variants),
+ }
+
+
+def _atlas_info(run_dir: Path) -> dict | None:
+ """최종 아틀라스 + 런타임 manifest 존재/시점 정보 (뷰 하단 섹션용)."""
+ atlas_path = run_dir / "sprite-sheet-alpha.png"
+ if not atlas_path.is_file():
+ return None
+ mtime = int(atlas_path.stat().st_mtime)
+ manifest_path = run_dir / "manifest.json"
+ return {
+ "url": _url("run", "sprite-sheet-alpha.png") + f"?v={mtime}",
+ "mtime": mtime,
+ "manifestUrl": (_url("run", "manifest.json") + f"?v={mtime}") if manifest_path.is_file() else None,
+ }
+
+
+_heal_lock = threading.Lock()
+
+
+_HEAL_GRACE_SECONDS = 1.5 # 신선 케이스(해시 비교 ms)는 이 안에 끝난다 — 그 이상이면 장기 heal
+_heal_state: dict = {"thread": None, "pending_report": None, "failed_attempt": None}
+
+
+def _heal_attempt_key(run_dir: Path) -> tuple:
+ """재시도 여부를 가르는 엔진+입력 스냅샷.
+
+ 결정론적으로 실패한 heal 을 같은 입력으로 계속 재실행하면 진행률이 끝에서
+ 0%로 돌아가는 무한 루프가 된다. 엔진이나 실제 재료가 바뀐 경우에만 새
+ 시도로 보도록 request/curation/manifest 와 raw 파일 stat 을 묶는다.
+ """
+ from sprite_gen.frames.extract import engine_revision
+
+ paths = [run_dir / "sprite-request.json", run_dir / "curation.json",
+ run_dir / "frames" / "frames-manifest.json"]
+ raw_dir = run_dir / "raw"
+ if raw_dir.is_dir():
+ paths.extend(path for path in raw_dir.rglob("*") if path.is_file())
+ fingerprints = []
+ for path in sorted(paths, key=lambda item: item.as_posix()):
+ try:
+ stat = path.stat()
+ fingerprints.append((path.relative_to(run_dir).as_posix(),
+ stat.st_mtime_ns, stat.st_size))
+ except OSError:
+ fingerprints.append((path.relative_to(run_dir).as_posix(), None, None))
+ return engine_revision(), tuple(fingerprints)
+
+
+def _durable_failed_heal_report(run_dir: Path, attempt_key: tuple) -> dict | None:
+ """현재 입력으로 이미 실패한 extract 증거가 있으면 재실행하지 않는다.
+
+ extract-failure.json 은 실패한 원자적 배포가 남기는 canonical evidence 다.
+ 실패 파일이 모든 입력보다 새롭고 엔진 리비전도 같으면 서버 재기동 뒤에도
+ 같은 실패를 다시 태우지 않고 이전 세대를 열어 준다.
+ """
+ failure_path = run_dir / "extract-failure.json"
+ try:
+ failure_stat = failure_path.stat()
+ failure = json.loads(failure_path.read_text(encoding="utf-8"))
+ except (OSError, ValueError):
+ return None
+ if failure.get("ok") is not False or failure.get("engine_revision") != attempt_key[0]:
+ return None
+ input_mtimes = [entry[1] for entry in attempt_key[1] if entry[1] is not None]
+ if input_mtimes and failure_stat.st_mtime_ns < max(input_mtimes):
+ return None
+ failed = sorted({str(row.get("state")) for row in failure.get("rows", [])
+ if row.get("state") and row.get("ok") is False})
+ if not failed:
+ failed = sorted({str(error).split(":", 1)[0] for error in failure.get("errors", [])
+ if ":" in str(error)})
+ return {"healed": [], "kept_stale": [], "failed": failed,
+ "notes": ["same engine/input already failed validation; previous frames kept"]}
+
+
+def _run_heal(run_dir: Path, attempt_key: tuple) -> None:
+ attempt_failed = False
+ try:
+ report = heal_run(run_dir)
+ except (Exception, SystemExit) as exc:
+ attempt_failed = True
+ report = {"healed": [], "kept_stale": [], "failed": [],
+ "notes": [f"heal skipped: {exc}"]}
+ with _heal_lock:
+ if report["healed"] or report["kept_stale"] or report.get("failed") or report["notes"]:
+ _heal_state["pending_report"] = report
+ if report.get("failed") or attempt_failed:
+ _heal_state["failed_attempt"] = attempt_key
+ elif _heal_state["failed_attempt"] == attempt_key:
+ _heal_state["failed_attempt"] = None
+ _heal_state["thread"] = None
+
+
+def maybe_heal(run_dir: Path) -> bool:
+ """실시간 계약 (maintainer 확정 2026-07-14): 뷰에 '재추출' 개념이 없다.
+
+ frames/ 는 (raw + request + 현재 엔진 + 큐레이션)의 파생 캐시다 — 요청이
+ 들어올 때마다 행별 engine_revision 을 현재 엔진과 비교해, 다르면 raw 에서
+ 다시 굽는다 (heal_run). 신선하면 해시 비교 몇 ms 로 끝난다.
+
+ 장기 heal 을 요청 핸들러 안에서 동기로 돌리면 첫 탭이 진행률 UI 없이 빈
+ 화면으로 수십 분 멈춘다 (회귀 2026-07-20, plan long-op-loading-ux — 엔진
+ 갱신 후 첫 로드). 그래서 heal 은 백그라운드 스레드로 발사하고 그레이스만
+ 동기 대기한다: 그 안에 끝나면(신선/소규모) 기존과 동일한 동기 경로, 넘으면
+ busy=True 를 반환해 /api/run 이 즉시 진행률 포함 busy 로 응답한다.
+ 단일 비행은 스레드 슬롯이 보장하고(동시 재추출 금지), heal 리포트는 유실
+ 없이 다음 성공 스냅샷에 1회 첨부된다. 실패는 뷰를 죽이지 않고 노트로 남는다.
+
+ 반환: busy 여부 (bool 단일 계약). 리포트는 여기서 소비하지 않는다 — 소비자는
+ take_heal_report() 하나뿐이다 (/api/run 성공 스냅샷 경로). /api/progress
+ 폴링이나 다운로드가 heal 완료 직후 먼저 도착하면 리포트를 먹어버려 다음
+ /api/run 첨부가 유실되던 경쟁을 막는다 (validator validator 재현,
+ 2026-07-20 — 단일 소비자 원칙).
+ """
+ attempt_key = _heal_attempt_key(run_dir)
+ with _heal_lock:
+ thread = _heal_state["thread"]
+ if thread is None or not thread.is_alive():
+ if _heal_state["failed_attempt"] == attempt_key:
+ return False
+ prior_failure = _durable_failed_heal_report(run_dir, attempt_key)
+ if prior_failure is not None:
+ _heal_state["failed_attempt"] = attempt_key
+ if _heal_state["pending_report"] is None:
+ _heal_state["pending_report"] = prior_failure
+ return False
+ thread = threading.Thread(target=_run_heal, args=(run_dir, attempt_key), daemon=True)
+ _heal_state["thread"] = thread
+ thread.start()
+ thread.join(timeout=_HEAL_GRACE_SECONDS)
+ return thread.is_alive()
+
+
+def take_heal_report() -> dict | None:
+ """pending heal 리포트의 유일한 소비자 — /api/run 이 스냅샷을 성공적으로
+ 만든 뒤에만 호출한다 (스냅샷 실패 시 리포트는 남아 다음 성공에 붙는다)."""
+ with _heal_lock:
+ report = _heal_state["pending_report"]
+ _heal_state["pending_report"] = None
+ return report
+
+
+def _zip_paths(base: Path, paths: list[Path]) -> bytes:
+ buffer = io.BytesIO()
+ with zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) as archive:
+ for path in paths:
+ archive.write(path, path.relative_to(base).as_posix())
+ return buffer.getvalue()
+
+
+def build_download(run_dir: Path, kind: str) -> tuple[bytes, str] | dict:
+ """내보내기 버튼 3종 = '지금 보이는 라이브 상태의 다운로드' (maintainer 확정 2026-07-14).
+
+ 게임/어디에 적용한다는 의미가 아니다 — 현재 (프레임 캐시 + 큐레이션)를
+ 합성 스크립트로 계산해 파일로 손에 쥐여준다. 계산 산출물은 런 폴더에도
+ 남는다 (런 폴더 = 작업장, 다운로드 = 핸드오프). 실패 시 dict(에러)."""
+ request = load_request(run_dir)
+ character = str(request.get("character", {}).get("id") or run_dir.name)
+ if kind == "atlas":
+ result = run_compose(run_dir)
+ if not result["ok"]:
+ return result
+ files = [run_dir / "sprite-sheet-alpha.png", run_dir / "manifest.json"]
+ files = [f for f in files if f.is_file()]
+ return _zip_paths(run_dir, files), f"{character}-atlas.zip"
+ if kind == "pngs":
+ result = run_export(run_dir)
+ if not result["ok"]:
+ return result
+ out = run_dir / "curated"
+ return _zip_paths(run_dir, sorted(out.rglob("*.png"))), f"{character}-pngs.zip"
+ if kind == "gifs":
+ result = run_export_gif(run_dir)
+ if not result["ok"]:
+ return result
+ out = run_dir / "exports"
+ return _zip_paths(run_dir, sorted(out.glob("*.gif"))), f"{character}-gifs.zip"
+ if kind.startswith("gif:"):
+ # 한 줄(state) 단건 — 현재 큐레이션 합성 그대로, zip 없이 GIF 원파일로.
+ # 검수/공유용이라 4x 니어리스트를 기본으로 굽는다 (뷰어 확대 보간 뭉갬 방지;
+ # 픽셀 데이터는 그대로). ?scale=1 로 원배율. 게임은 아틀라스를 쓰므로 무관.
+ state, _, scale_part = kind[len("gif:"):].partition(":")
+ scale = max(1, min(8, int(scale_part or 4)))
+ result = run_export_gif(run_dir, state=state, scale=scale)
+ if not result["ok"]:
+ return result
+ gif_path = run_dir / "exports" / f"{state}.gif"
+ if not gif_path.is_file():
+ return {"ok": False, "error": f"gif not produced: {gif_path}"}
+ return gif_path.read_bytes(), f"{character}-{state}.gif"
+ return {"ok": False, "error": f"unknown download kind: {kind}"}
+
+
+def _run_module(name: str, run_dir: Path, *extra: str) -> dict:
+ """Shell out to a pipeline step as a module of this package.
+
+ `-m sprite_gen.<step>` resolves through the interpreter's own import path, so it finds
+ the step wherever the package itself was found. Naming `scripts/<step>.py` instead would
+ tie every one of these routes to a repo checkout: the wrappers under `scripts/` are not
+ installed, so an installed `sprite-gen curation` would 500 on compose/interpolate/reroll/
+ export while still serving the SPA. The wrappers are re-exports of these same modules
+ (`scripts/compose_sprite_atlas.py` -> `sprite_gen.compose.compose_atlas`), so this is the same
+ program, reached by the path that survives installation.
+ """
+ proc = subprocess.run(
+ [sys.executable, "-m", qualified(name), "--run-dir", str(run_dir), *extra],
+ capture_output=True,
+ text=True,
+ )
+ return {
+ "ok": proc.returncode == 0,
+ "returncode": proc.returncode,
+ "stdout": proc.stdout,
+ "stderr": proc.stderr,
+ }
+
+
+def run_compose(run_dir: Path) -> dict:
+ """Re-run the atlas compose step so curation bakes into atlas/manifest."""
+ return _run_module("compose_atlas", run_dir)
+
+
+def run_interpolate(run_dir: Path, state: str, index_a: int, index_b: int,
+ t: float, label: str | None, provider: str = "codex") -> dict:
+ """AI in-between (`sprite_gen.effects.interpolate`): 테이크 기록 + 전체 배치 재추출.
+
+ 생성은 서버 머신의 provider CLI(codex/grok, 머신 로컬 OAuth)가 수행한다 —
+ 브라우저에는 자격증명이 지나가지 않는다. 부분 추출은 제공하지 않는다 —
+ run-wide 팔레트가 추출 배치 구성에 결합돼 있어 (docs/frame-interpolation.md)
+ 단일 행 추출은 그 행만 다른 팔레트로 굽는다."""
+ extra = ["--state", state, "--between", str(index_a), str(index_b),
+ "--provider", provider, "--t", str(t), "--extract"]
+ if label:
+ extra += ["--label", str(label)]
+ return _run_module("interpolate", run_dir, *extra)
+
+
+def run_reroll(run_dir: Path, state: str, provider: str = "codex") -> dict:
+ """행 리롤 (`sprite_gen.effects.reroll`): 새 테이크 생성 + 전체 배치 재추출.
+
+ primary 를 덮지 않는다 — 후보군 병기(테이크)가 계약이다 (maintainer 2026-07-19
+ "리롤버튼 눌러서 후보군에 추가"). 생성은 interpolate 와 같이 서버 머신의
+ provider CLI 가 수행하고, 부분 추출 없이 전체 배치를 재추출한다."""
+ return _run_module("reroll", run_dir,
+ "--state", state, "--provider", provider, "--extract")
+
+
+def run_export(run_dir: Path) -> dict:
+ """Export curated frames back to named PNGs under <run-dir>/curated/."""
+ result = _run_module("export_pngs", run_dir)
+ if result["ok"] and result["stdout"]:
+ try:
+ result["export"] = json.loads(result["stdout"])
+ except json.JSONDecodeError:
+ pass
+ return result
+
+
+def run_export_gif(run_dir: Path, state: str | None = None, scale: int = 1) -> dict:
+ """Export clean transparent GIF(s) under <run-dir>/exports/.
+
+ Reuses `sprite_gen.compose.compose_gif` --run-dir, which applies the same curation
+ selection/order/transform as the atlas compose (curation.py SSoT).
+ `state` limits to one row (`--state`) — the per-row download button path."""
+ extra = (["--state", state] if state else []) + (["--scale", str(scale)] if scale > 1 else [])
+ result = _run_module("compose_gif", run_dir, *extra)
+ if result["ok"] and result["stdout"]:
+ try:
+ result["gif"] = json.loads(result["stdout"])
+ except json.JSONDecodeError:
+ pass
+ return result
+
+
+class CurationHandler(BaseHTTPRequestHandler):
+ run_dir: Path = Path(".")
+ lang: str = "en"
+
+ def log_message(self, *_args): # quieter console
+ pass
+
+ # --- helpers -------------------------------------------------------------
+
+ def _send_json(self, payload: dict, status: int = 200) -> None:
+ body = json.dumps(payload, ensure_ascii=False).encode("utf-8")
+ self.send_response(status)
+ self.send_header("Content-Type", "application/json; charset=utf-8")
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+ def _send_file(self, path: Path) -> None:
+ if not path.is_file():
+ self._send_json({"error": "not found", "path": str(path)}, 404)
+ return
+ data = path.read_bytes()
+ self.send_response(200)
+ self.send_header("Content-Type", CONTENT_TYPES.get(path.suffix, "application/octet-stream"))
+ self.send_header("Content-Length", str(len(data)))
+ self.send_header("Cache-Control", "no-store")
+ self.end_headers()
+ self.wfile.write(data)
+
+ @staticmethod
+ def _safe_path(base: Path, rel: str) -> Path | None:
+ """Resolve `rel` under `base`, refusing anything that escapes it."""
+ base = base.resolve()
+ candidate = (base / unquote(rel)).resolve()
+ try:
+ candidate.relative_to(base)
+ except ValueError:
+ return None
+ return candidate
+
+ def _read_body(self) -> dict:
+ length = int(self.headers.get("Content-Length", 0))
+ raw = self.rfile.read(length) if length else b"{}"
+ return json.loads(raw.decode("utf-8"))
+
+ # --- routes --------------------------------------------------------------
+
+ def do_GET(self) -> None:
+ path = urlparse(self.path).path
+ if path in ("/", "/index.html"):
+ self._send_file(CURATOR_DIR / "index.html")
+ return
+ if path == "/api/run":
+ try:
+ busy = maybe_heal(self.run_dir) # 실시간 계약: 스냅샷 전에 캐시 자가치유
+ if busy:
+ # 장기 heal 진행 중 — 첫 탭부터 진행률 로딩 UI 가 뜨도록 즉답
+ self._send_json({
+ "error": "re-extraction in progress — frames are being "
+ "re-derived for the current engine; the view opens "
+ "automatically when it finishes",
+ "busy": True, "lang": CurationHandler.lang,
+ "progress": _read_op_progress(self.run_dir)}, 503)
+ return
+ snapshot = build_run_state(self.run_dir)
+ heal = take_heal_report() # 스냅샷 성공 뒤에만 소비 (단일 소비자)
+ if heal:
+ snapshot["heal"] = heal
+ self._send_json(snapshot)
+ except (Exception, SystemExit) as exc: # incl. load_frames_manifest fail-loud; no silent fallback
+ # 재추출이 돌고 있으면 request(새 테이크 선언)와 manifest(이전 세대)가
+ # 일시적으로 어긋난다 — corrupt 가 아니라 in-flight 다. 락 보유 중엔
+ # 그렇게 말해준다 (회귀 2026-07-17: 보간 직후 로드가 'corrupt frames
+ # manifest' 로 보여 사용자가 파손으로 오인).
+ if (self.run_dir / ".sprite-gen.lock").exists():
+ self._send_json({"error": "re-extraction in progress — "
+ "the run is being re-derived; reload when it finishes",
+ "busy": True, "progress": _read_op_progress(self.run_dir)}, 503)
+ else:
+ self._send_json({"error": str(exc)}, 500)
+ return
+ if path == "/api/op-progress":
+ # 오래 걸리는 파이프라인(추출 등)의 잘게 쪼갠 진행도 — 큐레이터가 폴링해
+ # 퍼센트 표시 (maintainer 요청 2026-07-18). busy=락 보유 여부, progress=엔진 기록.
+ self._send_json({
+ "busy": (self.run_dir / ".sprite-gen.lock").exists(),
+ "progress": _read_op_progress(self.run_dir),
+ })
+ return
+ if path == "/api/anchor":
+ # 방향 앵커 ref 를 **지금** 큐레이션 진실에서 굽어 그대로 응답한다 (파일 아님).
+ # 생성이 붙이는 `references/anchors/<dir>-anchor-x8.png` 와 같은 함수·같은
+ # 수학이라, 칩에 보이는 것이 다음 생성에 붙는 것이다 (표시/생성 드리프트 0).
+ query = parse_qs(urlparse(self.path).query)
+ direction = (query.get("direction") or [""])[0]
+ try:
+ scale = max(1, min(16, int((query.get("scale") or ["8"])[0])))
+ except ValueError:
+ self._send_json({"error": "scale must be an integer"}, 400)
+ return
+ try:
+ from sprite_gen.curate import anchor as anchor_mod
+ with read_guard(self.run_dir):
+ request = anchor_mod.load_request(self.run_dir)
+ curation = load_curation_report(self.run_dir)[0]
+ image, resolved = anchor_mod.anchor_image(
+ self.run_dir, request, curation, direction, scale)
+ buffer = io.BytesIO()
+ image.save(buffer, format="PNG")
+ except (Exception, SystemExit) as exc:
+ self._send_json({"error": str(exc)}, 404)
+ return
+ data = buffer.getvalue()
+ self.send_response(200)
+ self.send_header("Content-Type", "image/png")
+ self.send_header("Content-Length", str(len(data)))
+ self.send_header("Cache-Control", "no-store")
+ self.send_header("X-Anchor-Frame", f"{resolved['state']}#{resolved['index']}")
+ self.send_header("X-Anchor-Source", str(resolved["source"]))
+ self.end_headers()
+ self.wfile.write(data)
+ return
+ if path == "/api/breathe-anatomy":
+ # 실루엣 해부는 **서버에서만** 돈다 (maintainer 결정 2026-07-25 b안). 웹뷰는 이
+ # 숫자를 받아 워프만 미러링한다 — 눈쌍 대칭 매칭·연결요소·병목 검출을 JS 가
+ # 재구현하면 굽기와 미리보기의 진실이 갈라진다.
+ query = parse_qs(urlparse(self.path).query)
+ state = (query.get("state") or [""])[0]
+ overrides = {}
+ for name in ("rigid_row", "axis_x", "torso_half"):
+ value = (query.get(name) or [""])[0]
+ if value:
+ overrides[name] = int(value)
+ try:
+ frame, key = _breathe_source_frame(self.run_dir, state)
+ if frame is None:
+ self._send_json({"error": f"no extracted frame for state {state!r}"}, 404)
+ return
+ frozen = freeze_anatomy(frame, overrides, key)
+ self._send_json({"anatomy": frozen, "defaults": {
+ "depth": DEFAULT_DEPTH, "lag": DEFAULT_LAG, "breaths": 1}})
+ except (Exception, SystemExit) as exc:
+ self._send_json({"error": str(exc)}, 500)
+ return
+ if path == "/api/base-grid":
+ # 베이스의 검출 픽셀 격자 — 편집기(줌 모달)의 논리 해상도와 base-edit 의
+ # 논리→raw 확장이 같은 절단선을 쓴다 (_base_grid_response, mtime 캐시).
+ try:
+ base_path = _find_base_path(self.run_dir)
+ if base_path is None:
+ self._send_json({"error": "no base-source image in this run"}, 404)
+ return
+ self._send_json(_base_grid_response(self.run_dir, base_path))
+ except (Exception, SystemExit) as exc:
+ self._send_json({"error": str(exc)}, 500)
+ return
+ if path.startswith("/download/"):
+ kind = path[len("/download/"):]
+ if kind == "gif":
+ query = parse_qs(urlparse(self.path).query)
+ state = (query.get("state") or [""])[0]
+ scale = (query.get("scale") or ["4"])[0]
+ kind = f"gif:{state}:{scale}"
+ try:
+ busy = maybe_heal(self.run_dir) # 리포트 미소비 — 소비자는 /api/run 만
+ if busy:
+ self._send_json({
+ "error": "re-extraction in progress — retry the download "
+ "when it finishes",
+ "busy": True,
+ "progress": _read_op_progress(self.run_dir)}, 503)
+ return
+ built = build_download(self.run_dir, kind)
+ except (Exception, SystemExit) as exc:
+ self._send_json({"error": str(exc)}, 500)
+ return
+ if isinstance(built, dict):
+ self._send_json(built, 500)
+ return
+ data, filename = built
+ self.send_response(200)
+ self.send_header("Content-Type",
+ "image/gif" if filename.endswith(".gif") else "application/zip")
+ self.send_header("Content-Disposition", f'attachment; filename="{filename}"')
+ self.send_header("X-Filename", filename)
+ self.send_header("Content-Length", str(len(data)))
+ self.end_headers()
+ self.wfile.write(data)
+ return
+ if path == "/api/progress":
+ # 가벼운 생성 진행 스냅샷 (트리 실시간 갱신용 폴링 대상): 상태별 raw 유무 +
+ # 추출 프레임 수 + 런 세대. /api/run 전체 스냅샷(프레임 이미지 오픈)보다 훨씬 싸다.
+ try:
+ # 페이지가 열린 채 엔진이 바뀌어도 다음 폴에서 자가치유된다 —
+ # 프레임 세대가 바뀌면 runRevision 변화로 클라이언트가 리로드한다.
+ busy = maybe_heal(self.run_dir) # 리포트 미소비 — 소비자는 /api/run 만
+ if busy:
+ # heal 이 publish 락을 쥔 동안 read_guard 에서 행 걸리지 않게 즉답
+ self._send_json({"busy": True,
+ "progress": _read_op_progress(self.run_dir)}, 503)
+ return
+ with read_guard(self.run_dir):
+ request = load_request(self.run_dir)
+ progress = []
+ for state in request["states"]:
+ state_frames = frames_dir_rel(request, state)
+ state_raw = raw_rel(request, state)
+ state_dir = self.run_dir / state_frames
+ count = 0
+ if state_dir.is_dir():
+ count = sum(1 for f in state_dir.glob("frame-*.png") if not f.name.endswith(".plain.png"))
+ progress.append({
+ "name": state,
+ "raw": (self.run_dir / state_raw).is_file(),
+ "frames": count,
+ # 트리 썸네일용 실제 경로 URL (클라이언트 패턴 조립 금지)
+ "rawUrl": _url("run", *state_raw.split("/")),
+ "frame0Url": _url(*f"{state_frames}/frame-0.png".split("/")),
+ "relRaw": state_raw,
+ "relFrames": state_frames,
+ })
+ self._send_json({"states": progress, "runRevision": run_revision(self.run_dir)})
+ except (Exception, SystemExit) as exc:
+ self._send_json({"error": str(exc)}, 500)
+ return
+ if path.startswith("/curator/"):
+ resolved = self._safe_path(CURATOR_DIR, path[len("/curator/"):])
+ if resolved is None:
+ self._send_json({"error": "path escapes curator dir"}, 403)
+ return
+ self._send_file(resolved)
+ return
+ if path.startswith("/frames/") or path.startswith("/run/"):
+ rel = path[len("/run/"):] if path.startswith("/run/") else path[1:]
+ resolved = self._safe_path(self.run_dir, rel)
+ if resolved is None:
+ self._send_json({"error": "path escapes run dir"}, 403)
+ return
+ # read_guard: serve run-dir files under the shared reader lock so a concurrent
+ # publish swap can't 404 a file mid-move (reader isolation, same as /api/run).
+ with read_guard(self.run_dir):
+ self._send_file(resolved)
+ return
+ # bare static asset (curator.js / curator.css served from /)
+ asset = self._safe_path(CURATOR_DIR, path.lstrip("/"))
+ if asset is None:
+ self._send_json({"error": "path escapes curator dir"}, 403)
+ return
+ if asset.is_file():
+ self._send_file(asset)
+ return
+ self._send_json({"error": "not found", "path": path}, 404)
+
+ def do_POST(self) -> None:
+ path = urlparse(self.path).path
+ try:
+ if path == "/api/curation":
+ payload = self._read_body()
+ # Serialize the curation write with a concurrent --force publish (same
+ # publish_guard the swap holds), and reject a payload whose states are no
+ # longer in the current run. So a stale autosave from a webview still on the
+ # pre-re-import run can neither interleave with the swap nor land old-state
+ # curation on the new run (Consistency/Isolation — observable 409, not a
+ # silent overwrite). This uses the rwlock, not the pipeline write lock, so
+ # normal curation edits still never block on a running compose/extract.
+ with publish_guard(self.run_dir):
+ # reject a stale autosave: the POST must echo the runRevision it was
+ # loaded with. If the run generation changed under this session — a
+ # `--force` re-import or a re-extract, even one keeping the same state
+ # names but swapping the candidate images — old selections/transforms
+ # must not apply to the new frames (Consistency: observable 409, not a
+ # silent overwrite). runRevision is a content fingerprint of the frames.
+ stale = payload.get("runRevision") != run_revision(self.run_dir)
+ if not stale:
+ # 엔진-소유 사이드카 필드 보존: 클라이언트 payload 는 자기가 아는
+ # 필드만 싣는다 — 에이전트/엔진이 심어둔 행 필드(frozen 등)가
+ # 클라 저장에 조용히 드랍되면 보호 계약이 사라진다 (회귀
+ # 2026-07-19: hero frozen 마커 소실, validator 무결성 감사 발견).
+ # 계약: 기존 파일에 있고 payload 의 그 행에 없는 화이트리스트
+ # 필드는 이월한다.
+ engine_owned = ("frozen",)
+ # 뷰가 **조건부로만 authoring** 하는 행 필드: 트윈 없는 줄의
+ # `pixel_unfake` 는 buildPayload 가 아예 안 싣는다(그 줄의 퍼펙은
+ # 표시 렌즈라 사이드카에 새로 적으면 안 된다). 생략을 삭제로 받으면
+ # **굽기가 읽는 변종이 바뀐다** — 사이드카에 `pixel_unfake: true` 가
+ # 선언된 트윈 없는 줄이 큐레이터를 한 번 여는 것만으로 `plain` 으로
+ # 뒤집히고, `.plain.png` 가 없으니 굽기가 죽는다. 사용자는 아무것도
+ # 안 눌렀고 알림도 없다 (validator 실측 2026-07-26).
+ view_conditional = ("pixel_unfake",)
+ try:
+ existing = json.loads((self.run_dir / CURATION_FILENAME).read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError):
+ existing = {}
+ # 같은 계약의 최상위 필드: 앵커 프레임 지정. 뷰는 항상 `anchors` 를
+ # (해제 시 빈 객체로) 실어 보내므로 키가 **없을 때만** 이월한다 —
+ # `sprite-gen anchor --pick` 으로 심어둔 지정이 뷰를 모르는 저장
+ # (구 클라이언트/수동 POST)에 조용히 사라지지 않게.
+ if "anchors" in existing and "anchors" not in payload:
+ payload["anchors"] = existing["anchors"]
+ # 채택 컬러웨이도 같은 계약이다. 뷰는 variant 섹션이 있는 런에서만
+ # 이 필드를 authoring 한다 (variants 를 안 구운 런에서는 아예 안 싣는다)
+ # — 생략을 삭제로 받으면 다른 런에서 고른 채택이, 또는 손으로/CLI 로
+ # 심어둔 채택이 무관한 편집 한 번에 조용히 사라진다.
+ if "recolor" in existing and "recolor" not in payload:
+ payload["recolor"] = existing["recolor"]
+ # 런 전역 `pixel_unfake` 도 같은 계약이다 — 뷰는 **트윈 줄이 전부
+ # 같을 때만** 이 필드를 싣는다(혼합/트윈 없음이면 생략). 생략을
+ # 삭제로 받으면 굽기가 읽는 **변종이 바뀐다**(plain→pixel): 사용자는
+ # 아무것도 안 눌렀는데 다른 파일로 구워지고, 뷰의 호흡 기준 프레임
+ # 키도 같이 갈린다. 뷰가 authoring 하지 않은 값은 이월한다.
+ if "pixel_unfake" in existing and "pixel_unfake" not in payload:
+ payload["pixel_unfake"] = existing["pixel_unfake"]
+ for state_name, prev_entry in (existing.get("states") or {}).items():
+ if not isinstance(prev_entry, dict):
+ continue
+ slot = (payload.get("states") or {}).get(state_name)
+ if not isinstance(slot, dict):
+ continue
+ for field in engine_owned + view_conditional:
+ if field in prev_entry and field not in slot:
+ slot[field] = prev_entry[field]
+ write_curation_atomic(self.run_dir, payload)
+ if stale:
+ self._send_json({"error": "curation is from a different run generation "
+ "(the run changed under this session; reload the view)"}, 409)
+ else:
+ self._send_json({"ok": True})
+ return
+ if path == "/api/compare-gif":
+ # 비교 캔버스 캡처 프레임들(PNG dataURL) → 투명 GIF 조립.
+ # 프레임 합성은 클라이언트(큐레이션 상태 합성 경로)가 이미 끝냈다 —
+ # 여기선 조립만 한다 (결정론: 가상 시간 샘플).
+ payload = self._read_body()
+ raw_frames = payload.get("frames")
+ try:
+ duration_ms = max(20, int(payload.get("duration_ms", 100)))
+ except (TypeError, ValueError):
+ duration_ms = 100
+ if not isinstance(raw_frames, list) or not raw_frames or len(raw_frames) > 200:
+ self._send_json({"error": "frames: 1..200 data URLs required"}, 400)
+ return
+ import base64
+ from sprite_gen.util.gif_utils import save_clean_gif
+ images = []
+ try:
+ for entry in raw_frames:
+ head, _, b64 = str(entry).partition(",")
+ if "image/png" not in head:
+ raise ValueError("expected image/png data URLs")
+ images.append(Image.open(io.BytesIO(base64.b64decode(b64))).convert("RGBA"))
+ except (ValueError, OSError) as exc:
+ self._send_json({"error": f"bad frame data: {exc}"}, 400)
+ return
+ # 포맷 선택 (maintainer 2026-07-19 "webm/mp4 로도"): gif=save_clean_gif,
+ # webm=VP9 알파 보존, mp4=x264 (알파 불가 — 화이트 배경 합성).
+ fmt = str(payload.get("format", "gif")).lower()
+ if fmt not in ("gif", "webm", "mp4"):
+ self._send_json({"error": "format: gif|webm|mp4"}, 400)
+ return
+ if fmt != "gif" and shutil.which("ffmpeg") is None:
+ self._send_json({"error": "ffmpeg not found on server machine (webm/mp4 assembly requires it)"}, 500)
+ return
+ with tempfile.TemporaryDirectory() as td:
+ out = Path(td) / f"compare.{fmt}"
+ if fmt == "gif":
+ save_clean_gif(images, out, duration_ms=duration_ms)
+ else:
+ even = lambda v: (v + 1) // 2 * 2 # noqa: E731 — 코덱 짝수 치수 요구
+ for index, im in enumerate(images):
+ if fmt == "mp4":
+ frame = Image.new("RGB", (even(im.width), even(im.height)), (255, 255, 255))
+ frame.paste(im, (0, 0), im)
+ elif im.width % 2 or im.height % 2:
+ frame = Image.new("RGBA", (even(im.width), even(im.height)), (0, 0, 0, 0))
+ frame.paste(im, (0, 0))
+ else:
+ frame = im
+ frame.save(Path(td) / f"f{index:04d}.png")
+ fps = max(1, round(1000 / duration_ms))
+ args = ["ffmpeg", "-y", "-framerate", str(fps), "-i", str(Path(td) / "f%04d.png")]
+ if fmt == "webm":
+ args += ["-c:v", "libvpx-vp9", "-pix_fmt", "yuva420p", "-b:v", "0", "-crf", "28", "-auto-alt-ref", "0"]
+ else:
+ args += ["-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "18"]
+ args.append(str(out))
+ proc = subprocess.run(args, capture_output=True, text=True)
+ if proc.returncode != 0 or not out.exists():
+ self._send_json({"error": f"ffmpeg failed: {proc.stderr[-300:]}"}, 500)
+ return
+ data = out.read_bytes()
+ content_type = {"gif": "image/gif", "webm": "video/webm", "mp4": "video/mp4"}[fmt]
+ self.send_response(200)
+ self.send_header("Content-Type", content_type)
+ self.send_header("X-Filename", f"compare.{fmt}")
+ self.send_header("Content-Disposition", f'attachment; filename="compare.{fmt}"')
+ self.send_header("Content-Length", str(len(data)))
+ self.end_headers()
+ self.wfile.write(data)
+ return
+ if path == "/api/compose":
+ result = run_compose(self.run_dir)
+ self._send_json(result, 200 if result["ok"] else 500)
+ return
+ if path == "/api/base-edit":
+ # 베이스(base-source) 픽셀 편집 — 프레임과 달리 사이드카가 아니라
+ # 파일 자체에 굽는다: 베이스는 생성 identity truth 입력이라, 편집이
+ # 이후 생성(앵커 재파생·행 리롤)에 반영되려면 파일이 바뀌어야 한다
+ # (maintainer 지시 2026-07-17 '베이스를 다르게 해서 뽑고 싶다').
+ # 원본은 최초 1회 <base>.orig 로 백업 (관측 가능, 덮어쓰지 않음).
+ payload = self._read_body()
+ ops = payload.get("ops")
+ transform_req = payload.get("transform")
+ if not isinstance(ops, dict):
+ ops = {}
+ if not ops and not transform_req:
+ self._send_json({"error": 'body needs ops {"x,y": "#rrggbb"|null} and/or transform'}, 400)
+ return
+ base_path = _find_base_path(self.run_dir)
+ if base_path is None:
+ self._send_json({"error": "no base-source image in this run"}, 404)
+ return
+ space = str(payload.get("space") or "raw")
+ grid = None
+ if space == "logical":
+ # 논리 셀 좌표 (줌 모달 편집 공간) — 검출 격자로 raw 블록에 확장.
+ # 격자 SSoT = _base_grid_response (클라 표시와 동일 절단선).
+ grid = _base_grid_response(self.run_dir, base_path).get("grid")
+ if not grid:
+ self._send_json({"error": "logical ops need a detected base grid"}, 422)
+ return
+ elif space != "raw":
+ self._send_json({"error": f"unknown ops space: {space}"}, 400)
+ return
+ request = load_request(self.run_dir)
+ chroma = tuple(request.get("chroma_key", {}).get("rgb") or (255, 0, 255))
+ backup = base_path.with_name(base_path.name + ".orig")
+ if not backup.exists():
+ import shutil as _shutil
+ _shutil.copyfile(base_path, backup)
+ with Image.open(base_path) as opened:
+ image = opened.convert("RGBA")
+ applied = 0
+ for key, value in ops.items():
+ try:
+ x, y = (int(v) for v in str(key).split(","))
+ except ValueError:
+ continue
+ fill: tuple
+ if value:
+ hexv = str(value).lstrip("#")
+ if len(hexv) != 6:
+ continue
+ fill = tuple(int(hexv[i:i + 2], 16) for i in (0, 2, 4)) + (255,)
+ else:
+ fill = chroma + (255,) # 지우개 = 크로마 배경 복원
+ if grid is not None:
+ xe, ye = grid["xEdges"], grid["yEdges"]
+ if not (0 <= x < len(xe) - 1 and 0 <= y < len(ye) - 1):
+ continue
+ for ry in range(ye[y], ye[y + 1]):
+ for rx in range(xe[x], xe[x + 1]):
+ if 0 <= rx < image.width and 0 <= ry < image.height:
+ image.putpixel((rx, ry), fill)
+ applied += 1
+ else:
+ if not (0 <= x < image.width and 0 <= y < image.height):
+ continue
+ image.putpixel((x, y), fill)
+ applied += 1
+ if transform_req:
+ # 변형 굽기 — 프레임 bake 와 같은 순서(픽셀 편집 → 변형), 같은 수학
+ # (curation.apply_transform SSoT). dx/dy 는 논리 px → 검출 피치로
+ # raw 환산. 변형 결과의 바깥은 크로마 배경으로 재합성 (베이스 계약).
+ from sprite_gen.curate.curation import apply_transform as _apply_transform
+ from sprite_gen.curate.curation import normalize_transform as _normalize_transform
+ tnorm = dict(_normalize_transform(transform_req))
+ if grid is not None:
+ tnorm["dx"] = tnorm.get("dx", 0.0) * grid["pitch"][0]
+ tnorm["dy"] = tnorm.get("dy", 0.0) * grid["pitch"][1]
+ moved = _apply_transform(image, tnorm, (image.width, image.height))
+ canvas = Image.new("RGBA", (image.width, image.height), chroma + (255,))
+ canvas.alpha_composite(moved)
+ image = canvas
+ applied += 1
+ image.save(base_path)
+ self._send_json({"ok": True, "applied": applied, "space": space,
+ "backup": backup.name})
+ return
+ if path == "/api/state-fps":
+ # 줄 전체 재생 속도 = state fps (SSoT = sprite-request.json).
+ # 프레임별 지속시간은 프레임 복제가 담당 (maintainer 확정 2026-07-18 —
+ # per-frame duration 이중 진실 금지). fps 는 재생 메타데이터라
+ # 추출/프레임 캐시와 무관하다.
+ payload = self._read_body()
+ state = str(payload.get("state") or "")
+ try:
+ fps = int(payload.get("fps"))
+ except (TypeError, ValueError):
+ self._send_json({"error": "fps:int required"}, 400)
+ return
+ if not 1 <= fps <= 30:
+ self._send_json({"error": f"fps must be 1..30: {fps}"}, 400)
+ return
+ with publish_guard(self.run_dir):
+ # 게이트 경유 (락 안이어도 안전 — 게이트는 읽기만 한다)
+ request = load_request(self.run_dir)
+ if state not in request.get("states", {}):
+ self._send_json({"error": f"unknown state: {state}"}, 400)
+ return
+ request["states"][state]["fps"] = fps
+ # 쓰기도 게이트 경유 — fps 편집이 디스크 스키마를 바꾸지 않는다.
+ write_request(self.run_dir, request)
+ self._send_json({"ok": True, "state": state, "fps": fps})
+ return
+ if path == "/api/interpolate":
+ payload = self._read_body()
+ state = str(payload.get("state") or "")
+ request = load_request(self.run_dir)
+ if state not in request.get("states", {}):
+ self._send_json({"error": f"unknown state: {state}"}, 400)
+ return
+ try:
+ index_a = int(payload["from"])
+ index_b = int(payload["to"])
+ t_value = float(payload.get("t", 0.5))
+ except (KeyError, TypeError, ValueError):
+ self._send_json(
+ {"error": "body needs integer 'from'/'to' (+ optional float 't')"}, 400)
+ return
+ if not 0.0 < t_value < 1.0:
+ self._send_json({"error": f"t must be inside (0, 1): {t_value}"}, 400)
+ return
+ provider = str(payload.get("provider") or "codex")
+ if provider not in ("codex", "grok"):
+ self._send_json({"error": f"unknown provider: {provider}"}, 400)
+ return
+ result = run_interpolate(self.run_dir, state, index_a, index_b,
+ t_value, payload.get("label") or None, provider)
+ self._send_json(result, 200 if result["ok"] else 500)
+ return
+ if path == "/api/reroll":
+ payload = self._read_body()
+ state = str(payload.get("state") or "")
+ request = load_request(self.run_dir)
+ if state not in request.get("states", {}):
+ self._send_json({"error": f"unknown state: {state}"}, 400)
+ return
+ provider = str(payload.get("provider") or "codex")
+ if provider not in ("codex", "grok"):
+ self._send_json({"error": f"unknown provider: {provider}"}, 400)
+ return
+ result = run_reroll(self.run_dir, state, provider)
+ self._send_json(result, 200 if result["ok"] else 500)
+ return
+ if path == "/api/export":
+ result = run_export(self.run_dir)
+ self._send_json(result, 200 if result["ok"] else 500)
+ return
+ if path == "/api/export-gif":
+ result = run_export_gif(self.run_dir)
+ self._send_json(result, 200 if result["ok"] else 500)
+ return
+ except Exception as exc:
+ self._send_json({"error": str(exc)}, 500)
+ return
+ self._send_json({"error": "not found", "path": path}, 404)
+
+
+def add_arguments(parser: argparse.ArgumentParser) -> None:
+ """The webview's argument surface — declared once, for all three launch paths.
+
+ `sprite-gen curation`, `python -m sprite_gen.serve.serve_curation`, and the
+ `scripts/serve_curation.py` wrapper all reach this same declaration, so a flag
+ cannot exist on one form and be missing (or differently defaulted) on another.
+ """
+ parser.add_argument("--run-dir", required=True, type=Path)
+ parser.add_argument("--host", default="127.0.0.1")
+ parser.add_argument("--port", type=int, default=0, help="0 picks a free port")
+ parser.add_argument("--no-open", action="store_true", help="do not auto-open the browser")
+ parser.add_argument("--lang", choices=["en", "ko"], default="en", help="initial UI language (toggleable in the webview)")
+
+
+def run(*, run_dir: Path, host: str = "127.0.0.1", port: int = 0,
+ no_open: bool = False, lang: str = "en") -> int:
+ """Serve the curation webview until interrupted.
+
+ Keyword-only, matching the `cli.COMMANDS` run-fn convention (`run_fn(**vars(args))`),
+ which is also what `main()` below calls — one implementation, no per-entrypoint branch.
+ """
+ run_dir = run_dir.expanduser().resolve()
+ if not (run_dir / "sprite-request.json").is_file():
+ raise SystemExit(f"not a sprite-gen run dir (no sprite-request.json): {run_dir}")
+ if not CURATOR_DIR.is_dir():
+ raise SystemExit(f"missing curator SPA dir: {CURATOR_DIR}")
+
+ handler = partial(CurationHandler)
+ CurationHandler.run_dir = run_dir
+ CurationHandler.lang = lang
+ server = ThreadingHTTPServer((host, port), handler)
+ host, port = server.server_address
+ url = f"http://{host}:{port}/"
+ print(f"sprite-gen curation webview: {url}")
+ print(f" run-dir: {run_dir}")
+ # 뷰 계약 자가 보고 — base 참조 줄 / 생성 재료 칩 / 픽셀 격자 충족 여부를 한 줄로.
+ # 셋 다 없으면 "소스 없는 뷰" 경고 (관측 가능하게 — No Silent Fallback).
+ try:
+ snapshot = build_run_state(run_dir)
+ c = snapshot.get("contract", {})
+ n_states = len(snapshot.get("states", []))
+ print(f" view-contract: base={'yes' if c.get('base') else 'no'} · "
+ f"refs={c.get('refsStates', 0)}/{n_states} states · "
+ f"grid={'yes' if c.get('grid') else 'no'}")
+ if c.get("sourceless"):
+ print(" WARNING: sourceless view — no base-source, no generation-material refs, no pixel grid. "
+ "이 뷰는 세션마다 경험이 갈라진다 (run-contract.md §3/§4: _base/_refs 동봉 또는 fit.pixel_unfake 권장).")
+ except Exception as exc: # 계약 보고 실패는 서빙을 막지 않는다 — 관측만
+ print(f" view-contract: unavailable ({exc})")
+ print(" Ctrl-C to stop.")
+ if not no_open:
+ webbrowser.open(url)
+ try:
+ server.serve_forever()
+ except KeyboardInterrupt:
+ print("\nstopped.")
+ finally:
+ server.server_close()
+ return 0
+
+
+def main(argv: list[str] | None = None) -> int:
+ """`python -m sprite_gen.serve.serve_curation` / `scripts/serve_curation.py` entrypoint."""
+ parser = argparse.ArgumentParser(description=__doc__)
+ add_arguments(parser)
+ return run(**vars(parser.parse_args(argv)))
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/sprite_gen/spec/__init__.py b/sprite_gen/spec/__init__.py
new file mode 100644
index 0000000..9881313
--- /dev/null
+++ b/sprite_gen/spec/__init__.py
@@ -0,0 +1 @@
+# SPDX-License-Identifier: Apache-2.0
diff --git a/sprite_gen/spec/layout.py b/sprite_gen/spec/layout.py
new file mode 100644
index 0000000..0c00f69
--- /dev/null
+++ b/sprite_gen/spec/layout.py
@@ -0,0 +1,111 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Run-dir file taxonomy — 경로 구성의 단일 SSoT.
+
+기본 계약(택소노미, maintainer 확정 2026-07-14): 상태 ID 는 `<direction>_<pose>` 그대로
+두고 **파일 경로만** 방향/자세 폴더로 나눈다. 자세가 늘어나도 flat 폴더가
+비대해지지 않는다:
+
+ raw/<direction>/<pose>.png # 생성 스트립 원본
+ frames/<direction>/<pose>/frame-N.png # 추출 프레임 (+ .plain / orig/)
+ references/layout-guides/<direction>/<pose>.png
+ prompts/<direction>/<pose>.txt
+
+방향 계약(directions)이 없는 런(이펙트 등)은 자세 1단(`raw/<state>.png`)이 곧
+택소노미다. `layout` 필드가 없는 기존 런은 flat 레거시로 계속 동작한다.
+
+프로젝트별 정비 방식이 지침으로 주어지면 그 지침이 우선하고, 이 모듈의 기본
+계약은 지침이 없을 때의 표준이다.
+
+경로 소비 원칙: 이미 추출된 프레임을 읽는 소비자(compose/export/GIF/cycle/뷰)는
+frames-manifest 의 `files` 경로를 따른다(`row_frame_rel`) — 패턴 조립 금지.
+경로를 새로 만드는 쪽(prepare/extract)만 리졸버로 조립한다.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+TAXONOMY = "taxonomy/v1"
+
+
+def is_taxonomy(request: dict[str, Any]) -> bool:
+ """방향 폴더 분리가 활성인 런인가 — layout 계약 + directions 계약 둘 다 필요."""
+ return request.get("layout") == TAXONOMY and bool((request.get("directions") or {}).get("set"))
+
+
+def split_state(request: dict[str, Any], state: str) -> tuple[str | None, str]:
+ """상태 ID -> (direction, pose). 택소노미가 아니거나 방향 접두사가 없으면 (None, state)."""
+ if not is_taxonomy(request):
+ return None, state
+ for direction in request["directions"]["set"]:
+ if state.startswith(direction + "_"):
+ return direction, state[len(direction) + 1:]
+ return None, state
+
+
+def _joined(prefix: str, request: dict[str, Any], state: str, suffix: str) -> str:
+ direction, pose = split_state(request, state)
+ if direction:
+ return f"{prefix}/{direction}/{pose}{suffix}"
+ return f"{prefix}/{state}{suffix}"
+
+
+def raw_rel(request: dict[str, Any], state: str) -> str:
+ return _joined("raw", request, state, ".png")
+
+
+def state_frame_total(request: dict[str, Any], state: str) -> int:
+ """상태의 행 프레임 풀 총량 = primary `frames` + 선언된 테이크들의 `frames` 합.
+
+ 소비자(합성/뷰/검사)가 행 크기를 request 에서 셀 때는 반드시 이 값을 쓴다 —
+ primary 만 세면 takes 가 있는 행이 '초과 프레임'으로 오판된다."""
+ spec = request["states"][state]
+ total = int(spec.get("frames", 0))
+ total += sum(int(take.get("frames", 0)) for take in (spec.get("takes") or []))
+ return total
+
+
+def take_raw_rel(request: dict[str, Any], state: str, label: str) -> str:
+ """추가 테이크(같은 상태의 후보/보강 생성 스트립) 원본 경로.
+
+ 상태의 primary raw 옆 `.takes/` 폴더가 소유한다 — 예: `raw/down/idle.takes/blink.png`
+ (택소노미) / `raw/wave.takes/alt.png` (flat). 테이크는 request
+ `states.<state>.takes: [{label, frames}]` 로 선언되고, 추출이 primary 뒤에
+ 이어붙여 한 행의 프레임 풀을 만든다."""
+ base = raw_rel(request, state)
+ return f"{base[: -len('.png')]}.takes/{label}.png"
+
+
+def frames_dir_rel(request: dict[str, Any], state: str) -> str:
+ return _joined("frames", request, state, "")
+
+
+def guide_rel(request: dict[str, Any], state: str) -> str:
+ return _joined("references/layout-guides", request, state, ".png")
+
+
+def prompt_rel(request: dict[str, Any], state: str) -> str:
+ return _joined("prompts", request, state, ".txt")
+
+
+def row_frame_rel(row: dict[str, Any], index: int, variant: str = "pixel") -> str:
+ """추출된 프레임의 실제 경로 — manifest row 의 files 가 위치의 SSoT.
+
+ 'plain' 은 같은 자리의 .plain.png 쌍둥이. 인덱스가 파일 목록을 벗어나면
+ fail-loud (조용한 패턴 폴백 금지)."""
+ files = row.get("files") or []
+ if index >= len(files):
+ raise SystemExit(
+ f"frame index {index} out of range for state '{row.get('state')}' "
+ f"({len(files)} extracted frames) — stale selection or incomplete generation")
+ rel = files[index]
+ if variant == "plain":
+ return rel[: -len(".png")] + ".plain.png"
+ return rel
+
+
+def row_orig_rel(row: dict[str, Any], index: int) -> str:
+ """원본 화질(orig/) 쌍둥이 경로 — 프레임 파일과 같은 폴더의 orig/ 하위."""
+ rel = row_frame_rel(row, index)
+ head, _, name = rel.rpartition("/")
+ return f"{head}/orig/{name}"
diff --git a/sprite_gen/spec/migrate_breathe.py b/sprite_gen/spec/migrate_breathe.py
new file mode 100644
index 0000000..3615b3e
--- /dev/null
+++ b/sprite_gen/spec/migrate_breathe.py
@@ -0,0 +1,148 @@
+# SPDX-License-Identifier: Apache-2.0
+"""폐기된 분할선 호흡 설정을 봉투 스키마로 옮긴다 (일회성).
+
+`states.<state>.breathe` 의 `splits`/`amplitude`/`subpixel` 은 2026-07-25 에 봉투
+경계로 교체되면서 폐기됐고, `curation.state_breathe` 가 요란하게 거부한다. 이 도구는
+그 거부를 뚫는 우회로가 **아니다** — 사용자가 명시적으로 실행하는 변환이다.
+
+의도적으로 하지 않는 것: 옛 값을 새 값으로 자동 환산하지 않는다.
+
+ · `splits` 는 "이 선 위가 움직인다" 였고 새 `rigid_row` 는 "이 위는 안 움직인다" 다.
+ 반대 개념이라 자리 이동으로 옮길 수 없다. 새 경계는 실루엣에서 자동 검출된다.
+ · `amplitude` 는 정수 px 행 이동이었고 새 `depth` 는 몸통 높이 비율이다. 단위가
+ 비교 불가라 숫자를 옮기면 그럴듯하지만 틀린 값이 된다.
+
+그래서 `breaths` 만 보존하고 나머지는 기본값으로 두며, 무엇을 버렸는지 전부 출력한다.
+호흡 세기는 큐레이터에서 다시 잡는 게 맞다.
+"""
+
+from __future__ import annotations
+
+import math
+
+import argparse
+import json
+from pathlib import Path
+from typing import Any
+
+from sprite_gen.curate.curation import (BREATHE_BREATHS_MAX, BREATHE_DEPTH_MAX, BREATHE_LAG_MAX,
+ CURATION_FILENAME, RETIRED_BREATHE_KEYS)
+from sprite_gen.effects.breathe import DEFAULT_DEPTH, DEFAULT_LAG
+from sprite_gen.spec.runio import atomic_write_text
+
+
+def add_arguments(parser: argparse.ArgumentParser) -> None:
+ parser.add_argument("run_dir", type=Path, help="run directory holding curation.json")
+ parser.add_argument("--apply", action="store_true",
+ help="write the migrated sidecar (default is a dry run)")
+
+
+def migrate_entry(raw: dict[str, Any]) -> tuple[dict[str, Any], list[str]]:
+ """한 상태의 breathe 설정 -> (새 설정, 버린 것 설명)."""
+ dropped = [f"{key}={raw[key]!r} ({reason})"
+ for key, reason in RETIRED_BREATHE_KEYS.items() if key in raw]
+ fresh: dict[str, Any] = {"depth": DEFAULT_DEPTH, "lag": DEFAULT_LAG}
+ # `int(2.7)` 은 **조용히 2** 다 — 그러면 사용자가 적은 값과 다른 값이 마이그레이션
+ # 산출물에 들어가고 `dropped` 엔 한 줄도 안 남는다. `"3.5"` 문자열만 예외로 걸려
+ # 보고되고 실수만 샜다 (validator note 2026-07-26). 굽기(`_exact_int`)와 미러가 이미
+ # 거부하는 값이라, 이 세 번째 구현만 규칙을 안 지키고 있었다.
+ #
+ # `isfinite` 게이트가 **먼저** 와야 한다: `int(nan)` 은 `ValueError` 를 올리고,
+ # `json.loads` 는 기본값으로 `NaN` 리터럴을 받으므로 사이드카에서 실제로 들어온다.
+ # 이 판정을 try 밖으로 빼면 마이그레이션이 트레이스백으로 죽어 "무엇을 버렸는지 전부
+ # 출력한다" 는 모듈 계약이 그 입력에서 깨진다 (노을이 실측 2026-07-26 R2).
+ try:
+ raw_breaths = float(raw.get("breaths", 1))
+ integral = math.isfinite(raw_breaths) and raw_breaths == int(raw_breaths)
+ except (TypeError, ValueError):
+ want = 1
+ dropped.append(f"breaths={raw.get('breaths')!r} (정수가 아니라 1 로 되돌림)")
+ else:
+ if integral:
+ want = int(raw_breaths)
+ else:
+ want = 1
+ dropped.append(f"breaths={raw.get('breaths')!r} (정수가 아니라 1 로 되돌림)")
+ fresh["breaths"] = max(1, min(BREATHE_BREATHS_MAX, want))
+ if fresh["breaths"] != want:
+ # 깎았으면 **말한다.** 조용히 깎으면 모듈 계약("무엇을 버렸는지 전부 출력한다")이
+ # 깨지고, round-5 가 파이썬에서 없앤 조용한 클램프가 여기 남는다.
+ dropped.append(f"breaths={want!r} (범위 1~{BREATHE_BREATHS_MAX} 밖이라 {fresh['breaths']} 로 조정)")
+ # 이월하는 값도 **범위를 확인한다.** 안 하면 마이그레이션 산출물이 굽기에서 거부당한다
+ # (validator 실측 2026-07-25: depth 0.5 를 그대로 이월해 결과 사이드카가 안 구워졌다).
+ for key, lo, hi in (("depth", 0.005, BREATHE_DEPTH_MAX), ("lag", 0.0, BREATHE_LAG_MAX)):
+ if key not in raw:
+ continue
+ try:
+ value = float(raw[key])
+ except (TypeError, ValueError):
+ dropped.append(f"{key}={raw[key]!r} (숫자가 아니라 기본값 {fresh[key]} 사용)")
+ continue
+ if lo <= value <= hi:
+ fresh[key] = value
+ else:
+ dropped.append(f"{key}={value!r} (범위 [{lo}, {hi}] 밖이라 기본값 {fresh[key]} 사용)")
+ if "rigid_row" in raw and raw["rigid_row"] is not None:
+ # 이월 값도 굽기가 받을 수 있어야 한다 — `_exact_int` 가 비정수를 거부한다.
+ try:
+ row = float(raw["rigid_row"])
+ except (TypeError, ValueError):
+ dropped.append(f"rigid_row={raw['rigid_row']!r} (숫자가 아니라 버림 — 자동 검출로 돌아간다)")
+ row = None
+ if row is not None and not math.isfinite(row):
+ # `breaths` 와 **같은 클래스**의 크래시다: `int(nan)` 은 ValueError 라
+ # 마이그레이션이 트레이스백으로 죽고 "무엇을 버렸는지 전부 출력한다" 가 깨진다
+ # (노을이 note 2026-07-26; 이쪽은 본 플랜 base 이전부터 있던 구멍).
+ dropped.append(f"rigid_row={raw['rigid_row']!r} (유한한 수가 아니라 버림 — 자동 검출로 돌아간다)")
+ row = None
+ if row is not None:
+ if row == int(row) and row > 0:
+ fresh["rigid_row"] = int(row)
+ # 상한(콘텐츠 높이)은 마이그레이션 시점에 알 수 없다 — 프레임을 안 읽으니까.
+ # 완전 검증이 불가능하면 **그렇다고 말한다** (모듈 계약: 버린 것 전부 출력).
+ dropped.append(f"rigid_row={int(row)} (이월 — 콘텐츠 높이를 여기서 모르므로 "
+ f"굽기가 범위 밖이라고 다시 거부할 수 있다)")
+ else:
+ dropped.append(f"rigid_row={raw['rigid_row']!r} (정수 양수가 아니라 버림 — 자동 검출)")
+ if "anatomy" in raw:
+ fresh["anatomy"] = raw["anatomy"]
+ return fresh, dropped
+
+
+def run(**kwargs: object) -> int:
+ run_dir = Path(str(kwargs["run_dir"]))
+ apply_changes = bool(kwargs.get("apply"))
+ path = run_dir / CURATION_FILENAME
+ if not path.is_file():
+ print(f"migrate-breathe: {path} 가 없다")
+ return 1
+ data = json.loads(path.read_text(encoding="utf-8"))
+ states = data.get("states")
+ if not isinstance(states, dict):
+ print(f"migrate-breathe: {path} 에 states 가 없다 — 옮길 것이 없다")
+ return 0
+
+ touched = 0
+ for state, entry in states.items():
+ raw = entry.get("breathe") if isinstance(entry, dict) else None
+ if not isinstance(raw, dict):
+ continue
+ if not any(key in raw for key in RETIRED_BREATHE_KEYS):
+ print(f" {state}: 이미 봉투 스키마 — 그대로 둔다")
+ continue
+ fresh, dropped = migrate_entry(raw)
+ touched += 1
+ print(f" {state}: breaths {fresh['breaths']} · depth {fresh['depth']} · lag {fresh['lag']}")
+ for line in dropped:
+ print(f" 버림 {line}")
+ entry["breathe"] = fresh
+
+ if not touched:
+ print("migrate-breathe: 옮길 분할선 설정이 없다")
+ return 0
+ if not apply_changes:
+ print(f"migrate-breathe: dry-run ({touched} 개 상태). 실제로 쓰려면 --apply")
+ return 0
+ atomic_write_text(path, json.dumps(data, ensure_ascii=False, indent=2) + "\n")
+ print(f"migrate-breathe: {path} 갱신 ({touched} 개 상태). 호흡 세기는 큐레이터에서 다시 잡아라.")
+ return 0
diff --git a/sprite_gen/spec/migrate_request.py b/sprite_gen/spec/migrate_request.py
new file mode 100644
index 0000000..6b402d3
--- /dev/null
+++ b/sprite_gen/spec/migrate_request.py
@@ -0,0 +1,79 @@
+# SPDX-License-Identifier: Apache-2.0
+"""은퇴한 `fit` 키를 런의 `sprite-request.json` 에서 현행 키로 옮긴다 (일회성, 명시 실행).
+
+`fit.pixel_perfect` 는 2026-07-25 에 `fit.pixel_unfake` 로 교체됐다. 로더
+(`runio.load_request`) 는 은퇴 키를 **메모리에서만** 현행 키로 읽어 기존 런이 무손실로
+계속 돌게 하고, 디스크 스키마를 실제로 바꾸는 일은 이 명령에서만 한다.
+
+왜 나뉘어 있나: 예전엔 로더가 정규화한 문서를 곧바로 다시 썼고, 그래서 승인된 런에
+`state_revision()` 을 부른 것만으로 그 런의 `sprite-request.json` 이 재기록됐다. 조회가
+canonical 런의 바이트를 바꾸면 `run_revision`(request 바이트를 해싱한다)이 함께 움직이고,
+그 런의 큐레이션 사이드카가 stale 로 떨어진다. 읽는 쪽은 읽기만 하고, 쓰는 일은 사용자가
+부른 명령 안에서만 일어난다 (plan sprite-gen/state-revision-read-mutation).
+
+이 명령이 바꾸는 것은 키 이름 하나뿐이고 값·의미는 그대로다. 다만 파일 바이트가 바뀌므로
+`run_revision` 은 바뀐다 — 큐레이션 사이드카는 행별 `revision` 스탬프로 구제되고
+(`curation.load_curation_report`), 스탬프가 없는 행은 평소 규칙대로 드롭된다. 그 결과를
+쓰기 전에 미리 말한다: 조용히 잃는 것이 없어야 사용자가 실행 시점을 고를 수 있다.
+"""
+
+from __future__ import annotations
+
+import argparse
+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
+
+
+def add_arguments(parser: argparse.ArgumentParser) -> None:
+ parser.add_argument("run_dir", type=Path, help="run directory holding sprite-request.json")
+ parser.add_argument("--apply", action="store_true",
+ help="write the migrated request (default is a dry run)")
+
+
+def _curation_impact(run_dir: Path) -> list[str]:
+ """이관이 큐레이션 사이드카에 무엇을 할지 미리 읽어 보고한다 (읽기 전용).
+
+ 사이드카가 없거나 이미 세대가 어긋나 있으면 이관이 더 잃게 만드는 것이 없다. 지금
+ 세대가 맞는 사이드카만 영향을 받고, 그중 행별 스탬프가 없는 행이 드롭 대상이다."""
+ path = run_dir / CURATION_FILENAME
+ if not path.is_file():
+ return []
+ try:
+ doc = json.loads(path.read_text(encoding="utf-8"))
+ except (OSError, ValueError):
+ return [f"{CURATION_FILENAME} 을 읽을 수 없다 — 이관 후 상태를 미리 볼 수 없다"]
+ if doc.get("run_revision") != run_revision(run_dir):
+ return []
+ unstamped = [name for name, entry in (doc.get("states") or {}).items()
+ if not (isinstance(entry, dict) and entry.get("revision"))]
+ if not unstamped:
+ return [f"{CURATION_FILENAME}: 행별 스탬프로 전부 구제된다"]
+ return [f"{CURATION_FILENAME}: 행별 스탬프가 없어 드롭될 행 — {', '.join(sorted(unstamped))}"]
+
+
+def run(**kwargs: object) -> int:
+ run_dir = Path(str(kwargs["run_dir"]))
+ apply_changes = bool(kwargs.get("apply"))
+ path = run_dir / REQUEST_FILENAME
+ if not path.is_file():
+ 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):
+ print(f"migrate-request: {path} 는 이미 현행 키뿐이다 — 옮길 것이 없다")
+ return 0
+
+ print(f"migrate-request: {path} 의 은퇴 fit 키 이관 ({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 은 움직인다).")
+ return 0
diff --git a/sprite_gen/spec/runio.py b/sprite_gen/spec/runio.py
new file mode 100644
index 0000000..37aa74e
--- /dev/null
+++ b/sprite_gen/spec/runio.py
@@ -0,0 +1,534 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Safe run-dir IO shared by the pipeline scripts.
+
+Two concerns live together here because they answer the same question — "what
+happens when two sprite-gen processes touch the same run dir at once?" (for
+example Claude Code and the Codex app driving the skill in parallel):
+
+- `acquire_run_dir_lock()` — single-writer lock per run dir. SKILL.md forbids
+ two workers writing one character folder; this makes the rule enforced
+ instead of documentation-only. Writers (extract / compose / export / unpack,
+ and the webview's compose/export subprocesses through them) fail loudly with
+ the holder's pid instead of silently interleaving output files.
+- `atomic_write_text()` / `atomic_save_image()` — temp file in the target dir
+ + `os.replace`, so a concurrent reader never observes a half-written
+ atlas/manifest/frame. `atomic_write_set()` extends the same mechanism to a
+ set of files that only makes sense published together (a sheet, its manifest,
+ and the report naming it).
+
+`curation.json` is intentionally NOT under this pipeline write lock: the curation
+surface writes it with the same atomic replace, and the compose scripts read one
+consistent snapshot of it, so a curation edit never blocks on a running
+compose/extract. Concurrent curation edits on one run dir remain last-write-wins
+by design; the lock guards pipeline outputs, not human edit sessions. The curation
+*write* IS serialized against a `--force` re-import publish through the separate
+publish rwlock (`read_guard`/`publish_guard`), and the server rejects a curation
+POST whose echoed run generation (`runRevision`) no longer matches — so a stale edit
+can't apply old selections/transforms to a freshly re-imported run's frames.
+"""
+
+from __future__ import annotations
+
+import atexit
+import contextlib
+import json
+import os
+import sys
+import tempfile
+import time
+from pathlib import Path, PurePath
+
+from PIL import Image
+
+try: # Unix advisory locks. Windows uses LockFileEx below.
+ import fcntl
+except ImportError: # pragma: no cover - non-Unix
+ fcntl = None
+
+
+# Publish isolation requires a cross-process reader/writer lock. POSIX flock
+# supplies shared/exclusive modes; Windows msvcrt.locking is exclusive-only and
+# would silently serialize readers, so the native LockFileEx mapping is used.
+# Both guards read this one availability switch and fail loud when it is absent.
+_LOCK_IMPL: str | None = "fcntl" if fcntl is not None else None
+
+if fcntl is None and os.name == "nt": # pragma: no cover - Windows-only backend
+ try:
+ import ctypes
+ import msvcrt
+ from ctypes import wintypes
+
+ _LOCKFILE_EXCLUSIVE_LOCK = 0x00000002
+ _WIN_LOCK_BYTES = 1
+
+ class _OVERLAPPED(ctypes.Structure):
+ _fields_ = [
+ ("Internal", wintypes.LPVOID),
+ ("InternalHigh", wintypes.LPVOID),
+ ("Offset", wintypes.DWORD),
+ ("OffsetHigh", wintypes.DWORD),
+ ("hEvent", wintypes.HANDLE),
+ ]
+
+ _kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
+ _LockFileEx = _kernel32.LockFileEx
+ _LockFileEx.restype = wintypes.BOOL
+ _LockFileEx.argtypes = [
+ wintypes.HANDLE,
+ wintypes.DWORD,
+ wintypes.DWORD,
+ wintypes.DWORD,
+ wintypes.DWORD,
+ ctypes.POINTER(_OVERLAPPED),
+ ]
+ _UnlockFileEx = _kernel32.UnlockFileEx
+ _UnlockFileEx.restype = wintypes.BOOL
+ _UnlockFileEx.argtypes = [
+ wintypes.HANDLE,
+ wintypes.DWORD,
+ wintypes.DWORD,
+ wintypes.DWORD,
+ ctypes.POINTER(_OVERLAPPED),
+ ]
+ _LOCK_IMPL = "LockFileEx"
+ except (ImportError, OSError, AttributeError):
+ _LOCK_IMPL = None
+
+
+def _lock_fd(fd: int, *, exclusive: bool) -> None:
+ """Block until this handle owns the requested shared/exclusive lock."""
+ if fcntl is not None:
+ fcntl.flock(fd, fcntl.LOCK_EX if exclusive else fcntl.LOCK_SH)
+ return
+ overlapped = _OVERLAPPED()
+ flags = _LOCKFILE_EXCLUSIVE_LOCK if exclusive else 0
+ handle = wintypes.HANDLE(msvcrt.get_osfhandle(fd))
+ if not _LockFileEx(handle, flags, 0, _WIN_LOCK_BYTES, 0, ctypes.byref(overlapped)):
+ raise ctypes.WinError(ctypes.get_last_error())
+
+
+def _unlock_fd(fd: int) -> None:
+ if fcntl is not None:
+ fcntl.flock(fd, fcntl.LOCK_UN)
+ return
+ overlapped = _OVERLAPPED()
+ handle = wintypes.HANDLE(msvcrt.get_osfhandle(fd))
+ if not _UnlockFileEx(handle, 0, _WIN_LOCK_BYTES, 0, ctypes.byref(overlapped)):
+ raise ctypes.WinError(ctypes.get_last_error())
+
+LOCK_FILENAME = ".sprite-gen.lock"
+# Sidecar (beside the run dir) reader/writer coordination lock for the publish swap.
+# It lives outside the run dir so it survives content swaps and is never itself
+# published; a run dir named `foo` uses `.foo.sg-rwlock` in the parent.
+RWLOCK_SUFFIX = ".sg-rwlock"
+# reclaim threshold for locks whose holder pid cannot be verified
+# (unreadable lock file, or a writer on another host of a shared volume)
+STALE_LOCK_SECONDS = 15 * 60
+
+# Lock paths this process already owns. Re-entry from the same process (for
+# example a long-lived MCP server invoking prepare -> extract -> compose against
+# one run dir) must succeed; the single-writer rule is against other processes.
+_HELD_LOCKS: set[Path] = set()
+
+
+def relative_posix(path: PurePath, start: PurePath) -> str:
+ """Return a manifest-safe relative path with POSIX separators."""
+
+ return path.relative_to(start).as_posix()
+
+
+def _pid_alive(pid: int) -> bool:
+ try:
+ os.kill(pid, 0)
+ except ProcessLookupError:
+ return False
+ except PermissionError:
+ return True
+ return True
+
+
+def acquire_run_dir_lock(run_dir: Path, owner: str) -> Path:
+ """Take the single-writer lock for `run_dir`, released automatically at exit.
+
+ Create-exclusive lock file (`.sprite-gen.lock`) holding owner + pid. When
+ another live process holds it, exit loudly instead of interleaving writes.
+ A lock whose pid is dead — or unreadable and older than STALE_LOCK_SECONDS —
+ is reclaimed, so a killed run never wedges the run dir.
+
+ Re-entry from the same process is allowed: the MCP server / freeze binary
+ runs many pipeline steps in one interpreter against the same run dir, and a
+ writer must never block itself.
+
+ Release runs via atexit (normal return, SystemExit, KeyboardInterrupt).
+ A SIGKILL'd holder is covered by the dead-pid reclaim above.
+ """
+ lock_path = (run_dir / LOCK_FILENAME).resolve()
+ if lock_path in _HELD_LOCKS:
+ return lock_path
+ while True:
+ try:
+ fd = os.open(lock_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
+ break
+ except FileExistsError:
+ holder: dict = {}
+ try:
+ holder = json.loads(lock_path.read_text(encoding="utf-8"))
+ except (OSError, ValueError):
+ pass
+ pid = holder.get("pid")
+ if isinstance(pid, int) and _pid_alive(pid):
+ raise SystemExit(
+ f"run dir is locked by {holder.get('owner', 'unknown')} (pid {pid}): {run_dir}\n"
+ f" another sprite-gen process is writing this run dir; wait for it to finish,\n"
+ f" or delete {lock_path} if you are sure that process is gone"
+ )
+ try:
+ age = time.time() - lock_path.stat().st_mtime
+ except OSError:
+ continue # holder released it between our checks; retry the create
+ if isinstance(pid, int) or age > STALE_LOCK_SECONDS:
+ # dead pid, or unverifiable and old: reclaim, then retry the
+ # exclusive create (one winner if two reclaimers race)
+ try:
+ lock_path.unlink()
+ except OSError:
+ pass
+ continue
+ raise SystemExit(
+ f"run dir has a lock whose holder cannot be verified ({age:.0f}s old): {lock_path}\n"
+ f" delete the lock file if no sprite-gen process is running"
+ )
+
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
+ json.dump({"owner": owner, "pid": os.getpid(), "started": time.time()}, handle)
+
+ _HELD_LOCKS.add(lock_path)
+
+ def _release() -> None:
+ try:
+ lock_path.unlink()
+ except OSError:
+ pass
+ _HELD_LOCKS.discard(lock_path)
+
+ atexit.register(_release)
+ return lock_path
+
+
+def release_run_dir_lock(run_dir: Path) -> None:
+ """이 프로세스가 쥔 run-dir 락을 작업 완료 시점에 명시 해제한다.
+
+ atexit 해제만 있으면 장수 프로세스(테스트 러너·MCP 서버·큐레이션 서버)가
+ 한 번의 in-process 추출 뒤 락을 영구 보유해, heal_run 의 서브프로세스
+ 재추출이 산 pid 락에 막힌다. 락은 세션 리스가 아니라 작업 단위 writer-writer
+ 상호배제고, 원자성은 스테이징 통짜 스왑이 보장하므로 작업이 끝나면 놓는 게
+ 맞다. atexit 핸들러는 남아 있어도 멱등이다 (unlink 실패 무시 + discard)."""
+ lock_path = (Path(run_dir).resolve() / LOCK_FILENAME).resolve()
+ if lock_path not in _HELD_LOCKS:
+ return
+ try:
+ lock_path.unlink()
+ except OSError:
+ pass
+ _HELD_LOCKS.discard(lock_path)
+
+
+def _rwlock_path(run_dir: Path) -> Path:
+ run_dir = Path(run_dir).resolve()
+ return run_dir.parent / f".{run_dir.name}{RWLOCK_SUFFIX}"
+
+
+class RWLockUnavailable(RuntimeError):
+ """Publish reader/writer isolation could not be established on this platform.
+
+ Raised (fail-loud) instead of degrading the guard to a no-op. A no-op guard would be a
+ *failover that changes canonical truth*: a reader could observe a half-published run
+ (old/new file mix or a missing file) mid-swap. The isolation contract permits an
+ availability failover only when it stays observable AND does not change canonical truth
+ — a silent old-or-new-abandoning no-op fails the second half, so we refuse to proceed
+ without isolation rather than serve a partial run.
+ """
+
+
+def _rwlock_unavailable(run_dir: Path, why: str) -> "RWLockUnavailable":
+ return RWLockUnavailable(
+ f"publish reader/writer isolation unavailable ({why}) for {run_dir}: cannot "
+ f"guarantee a reader the complete old-or-new snapshot across a --force re-import / "
+ f"re-extract swap. Refusing to proceed rather than expose a partial run (a failover "
+ f"must not change canonical truth). Locks use fcntl on macOS/Linux and LockFileEx "
+ f"on Windows; ensure the run dir's parent is writable for the "
+ f".<name>{RWLOCK_SUFFIX} sidecar."
+ )
+
+
+def read_guard(run_dir: Path):
+ """Shared (reader) lock on the run dir's publish rwlock. While a publish holds the
+ exclusive lock for its content swap, a reader inside this guard blocks — so it never
+ observes a half-published run (no old/new file mix, no missing file). If the platform
+ has no shared/exclusive backend or the sidecar cannot be created, the guard **fails
+ loud** (`RWLockUnavailable`) rather than degrading to a no-op."""
+ if _LOCK_IMPL is None:
+ raise _rwlock_unavailable(run_dir, "no shared/exclusive file-lock backend")
+ try:
+ fd = os.open(_rwlock_path(run_dir), os.O_RDWR | os.O_CREAT, 0o644)
+ except OSError as exc:
+ raise _rwlock_unavailable(run_dir, f"cannot create rwlock sidecar: {exc}") from exc
+ try:
+ _lock_fd(fd, exclusive=False)
+ try:
+ yield
+ finally:
+ _unlock_fd(fd)
+ finally:
+ os.close(fd)
+
+
+def publish_guard(run_dir: Path):
+ """Exclusive (writer) lock on the run dir's publish rwlock — held only around the
+ content swap so concurrent readers block briefly and never see a partial publish.
+ Same sidecar file as read_guard. **Fails loud** (`RWLockUnavailable`, see read_guard)
+ if no lock backend is available or the sidecar can't be created — never a no-op, because a
+ no-op publish would swap canonical frames while readers are unguarded."""
+ if _LOCK_IMPL is None:
+ raise _rwlock_unavailable(run_dir, "no shared/exclusive file-lock backend")
+ try:
+ fd = os.open(_rwlock_path(run_dir), os.O_RDWR | os.O_CREAT, 0o644)
+ except OSError as exc:
+ raise _rwlock_unavailable(run_dir, f"cannot create rwlock sidecar: {exc}") from exc
+ try:
+ _lock_fd(fd, exclusive=True)
+ try:
+ yield
+ finally:
+ _unlock_fd(fd)
+ finally:
+ os.close(fd)
+
+
+def _atomic_replace(target: Path, write_payload) -> None:
+ fd, tmp_name = tempfile.mkstemp(dir=str(target.parent), prefix=f".{target.name}.", suffix=".tmp")
+ try:
+ write_payload(fd, tmp_name)
+ os.replace(tmp_name, target)
+ except BaseException:
+ if os.path.exists(tmp_name):
+ os.unlink(tmp_name)
+ raise
+
+
+def atomic_write_text(target: Path, text: str) -> None:
+ """Write text via temp file + os.replace so readers never see a torn file."""
+
+ def payload(fd: int, _tmp_name: str) -> None:
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
+ handle.write(text)
+
+ _atomic_replace(target, payload)
+
+
+def atomic_save_image(image: Image.Image, target: Path) -> None:
+ """Save a PIL image via temp file + os.replace (format from target suffix)."""
+ fmt = (target.suffix.lstrip(".") or "png").upper()
+ fmt = {"JPG": "JPEG"}.get(fmt, fmt)
+
+ def payload(fd: int, tmp_name: str) -> None:
+ os.close(fd)
+ image.save(tmp_name, format=fmt)
+
+ _atomic_replace(target, payload)
+
+
+def atomic_write_set(payloads: "dict[Path, bytes | str]") -> None:
+ """Publish a whole set of files: stage every payload first, then rename them in.
+
+ The single-file writers above make each artifact appear whole, which is all a
+ stage that publishes one file needs. A stage that publishes a *set* — a sheet,
+ its manifest, and the report that says which sheets are current — needs the
+ set to appear together: a mid-loop `ENOSPC` on the second sheet would
+ otherwise leave the first one published with no report naming it.
+
+ Phase 1 writes each payload to a temp file beside its target and fsyncs it.
+ That is the phase that allocates, so any failure there has published nothing
+ and removes its own temps. Phase 2 is one `os.replace` per target — a rename
+ inside a directory whose blocks are already allocated.
+
+ This is not a filesystem transaction (POSIX has no multi-file commit): a
+ power loss between two renames can still land a subset. What it removes is
+ the failure this code can actually observe and act on — a write error partway
+ through a publish reporting success over a half-published set.
+
+ Parent directories must already exist; the caller owns the layout.
+ """
+ staged: list[tuple[str, Path]] = []
+ try:
+ for target, payload in payloads.items():
+ data = payload.encode("utf-8") if isinstance(payload, str) else payload
+ fd, tmp_name = tempfile.mkstemp(
+ dir=str(target.parent), prefix=f".{target.name}.", suffix=".tmp")
+ # Tracked before it is written: a failure mid-write must still clean
+ # up this temp, not just the ones that completed.
+ staged.append((tmp_name, target))
+ with os.fdopen(fd, "wb") as handle:
+ handle.write(data)
+ handle.flush()
+ os.fsync(handle.fileno())
+ except BaseException:
+ for tmp_name, _target in staged:
+ with contextlib.suppress(OSError):
+ os.unlink(tmp_name)
+ raise
+ for index, (tmp_name, target) in enumerate(staged):
+ try:
+ os.replace(tmp_name, target)
+ except BaseException:
+ for pending, _target in staged[index:]:
+ with contextlib.suppress(OSError):
+ os.unlink(pending)
+ raise
+
+
+# --- sprite-request.json 단일 로드 게이트 ------------------------------------
+# 18곳이 각자 `json.loads((run_dir / "sprite-request.json").read_text())` 하던 것을 하나로
+# 모은다 (`load_curation` 이 큐레이션 사이드카에 대해 그렇게 하는 것과 같은 이유). 게이트가
+# 하나면 스키마 이관을 걸 자리도 하나다 — 열여덟 곳에 같은 이관 코드를 흩뿌리면 그중 하나가
+# 빠진 날 조용히 두 진실이 생긴다.
+REQUEST_FILENAME = "sprite-request.json"
+
+# 은퇴한 키 -> 현행 키. "pixel perfect" 는 광의 통용어(UI 정합·충돌판정)의 오용이었고, 이
+# 파이프라인이 실제로 하는 일의 정확한 명칭은 커뮤니티 속칭 "unfake"(unfake.js 유래)다
+# — 격자 스냅/재양자화로 가짜 픽셀아트를 되돌린다
+# 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 도 같이 쓴다 (키 매핑이
+ 두 벌 생기지 않게)."""
+ 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
+ return moved
+
+
+# 은퇴 키를 안은 런을 한 프로세스에서 처음 읽을 때만 이관 안내를 낸다. `state_revision`
+# 이 뷰 요청마다 로더를 부르므로 매번 찍으면 로그가 안내가 아니라 소음이 된다. 로그
+# 중복 억제이지 진실 저장소가 아니다 — 여기 무엇이 들어 있든 판독 결과는 같다.
+_RETIRED_KEY_NOTICED: set[str] = set()
+
+
+def _read_request_document(run_dir: Path) -> tuple[Path, dict, bool]:
+ """`sprite-request.json` 을 읽어 (경로, 정규화된 문서, 은퇴 키가 있었나) 를 돌려준다.
+
+ request 파일을 실제로 여는 곳은 여기 하나다 — 읽기 게이트와 이관 writer 가 같은 판독
+ (두 키 hard fail 포함)을 쓰게 하려면 파싱이 한 벌이어야 한다."""
+ path = Path(run_dir) / REQUEST_FILENAME
+ 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))
+
+
+def load_request(run_dir: Path) -> dict:
+ """런의 numeric SSoT (`sprite-request.json`) 를 읽는 **유일한 게이트**. 읽기만 한다.
+
+ 은퇴한 키(`fit.pixel_perfect`)는 현행 키(`fit.pixel_unfake`)로 **메모리에서만** 정규화
+ 되고 파일은 바이트 그대로 남는다. 두 키가 동시에 있으면 hard fail.
+
+ 합성 회귀는 이 함수가 정규화한 문서를 디스크에 다시 쓰면 조회만으로
+ `sprite-request.json` 과 `run_revision` 이 움직여 큐레이션 사이드카를 stale 로
+ 떨어뜨리는 SRP 위반이 생김을 고정한다 (plan sprite-gen/state-revision-read-mutation).
+
+ 디스크 스키마 이관은 사용자가 명시적으로 부르는 단일 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:
+ _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)
+ return request
+
+
+def migrate_request_file(run_dir: Path, *, apply: bool = False) -> bool:
+ """은퇴한 `fit` 키를 디스크에서 현행 키로 옮긴다 — request 스키마의 **유일한 이관 writer**.
+
+ Returns True 면 옮길 것이 있었다는 뜻이다 (`apply=False` 인 dry run 에서도 True).
+ 이미 현행 키뿐이면 False (멱등 — 두 번째 실행은 아무것도 쓰지 않는다).
+
+ Isolation: `sprite-request.json` 의 read-modify-write 는 **편집 writer 와 같은 격리
+ 도메인**(`publish_guard` 배타락) 안에서만 일어난다 — 락 획득 **후** fresh 재독하고
+ 원자 교체한다. 예전엔 락 **밖에서** 문서를 읽고 나서 `.sprite-gen.lock`(파이프라인 단계용
+ 단일 writer 락)을 잡았다. 그건 두 가지가 동시에 틀렸다: (a) read-then-lock 이라 읽은
+ 뒤 잡기 전 사이의 편집을 stale 문서로 덮고, (b) 편집 writer(`reroll.record_take` ·
+ `interpolate.write_take` · 뷰 fps POST)는 `publish_guard` 를 쓰므로 **서로 배제하지 않는
+ 두 도메인**이었다 — 리롤이 기록한 테이크를 이관이 통째로 잃거나(반대 방향이면 이관이
+ 조용히 되돌아간다) 하는 lost update 가 가능했다. 한 자원에 격리 도메인은 하나다.
+
+ 파이프라인 락(`.sprite-gen.lock`)은 잡지 않는다: 그 락이 지키는 것은 프레임·아틀라스
+ 같은 파이프라인 산출물이고 request 파일이 아니다 (추출·굽기는 request 를 쓰지 않는다).
+ 안 만지는 자원의 락을 잡으면 보호받는다는 착시만 남고 실제 경쟁자는 그대로다.
+
+ dry run(`apply=False`)은 판정만 하는 읽기라 락을 잡지 않는다 — 조회가 편집을 막지
+ 않아야 한다 (`load_request` 가 락을 안 보는 것과 같은 이유).
+ """
+ run_dir = Path(run_dir)
+ if not apply:
+ return _read_request_document(run_dir)[2]
+ 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
+ atomic_write_text(path, json.dumps(request, ensure_ascii=False, indent=2) + "\n")
+ _RETIRED_KEY_NOTICED.discard(str(path))
+ return True
+
+
+def write_request(run_dir: Path, request: dict) -> None:
+ """편집한 request 를 원자적으로 다시 쓴다 — **디스크의 키 형태를 보존한다**.
+
+ take 기록·fps 편집처럼 스키마와 무관한 편집도 로더가 정규화해 준 문서를 통째로 되쓴다.
+ 그대로 쓰면 그 편집이 은퇴 키를 조용히 현행 키로 바꿔, 스키마 이관이 다시 "아무 명령이나
+ 하는 김에 하는 일" 이 된다. 로더가 메모리에서 편 것을 쓰기 직전에 되접으면, 디스크
+ 스키마를 바꾸는 곳은 `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 = {} # 첫 발행이거나 읽을 수 없다 — 되접을 형태가 없으니 그대로 쓴다
+ fit = request.get("fit")
+ if isinstance(fit, dict):
+ restore = {current: legacy for legacy, current in LEGACY_FIT_KEYS.items()
+ if legacy in on_disk_fit and current in fit}
+ if restore:
+ # 되접는 것은 **키 이름뿐**이고, 순서는 로더가 정규화해 준 dict 의 순서를 그대로
+ # 따른다 — 디스크의 원래 순서와 다를 수 있다. 정규화가 은퇴 키를 pop 해서 현행
+ # 키로 다시 넣기 때문이다: 디스크 `{pixel_perfect, logical_height}` 는 편집 후
+ # `{logical_height, pixel_perfect}` 로 쓰인다 (이름은 보존, 자리는 이동).
+ request = {**request, "fit": {restore.get(key, key): value
+ for key, value in fit.items()}}
+ atomic_write_text(path, json.dumps(request, ensure_ascii=False, indent=2) + "\n")
diff --git a/sprite_gen/spec/subject.py b/sprite_gen/spec/subject.py
new file mode 100644
index 0000000..75c7b80
--- /dev/null
+++ b/sprite_gen/spec/subject.py
@@ -0,0 +1,86 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Subject profile — resolution-aware sparse-frame validation defaults.
+
+The sparse-frame floor exists to catch empty frames and extraction debris.
+"How many opaque pixels count as debris" is a property of the *subject*, not
+of arithmetic: a character is expected to occupy more pixels than an effect,
+but neither expectation is an absolute number independent of resolution.
+
+`sprite-request.json` declares `"subject": "character" | "effect"`; no field
+means character. The floor is derived from the cell geometry:
+
+ equivalent_side = ceil(sqrt(width * height))
+ character floor = equivalent_side
+ effect floor = ceil(equivalent_side / 2)
+
+The geometric mean extends the same rule to rectangular cells without picking
+one axis as truth. It deliberately uses the declared cell rather than safe
+margins: integer margin rounding can grow by two pixels when a cell grows by
+one, which would make a supposedly resolution-scaled floor decrease. Scaling a
+cell by k scales the floor by k, not k². An explicit `--min-used-pixels` always
+wins.
+"""
+
+from __future__ import annotations
+
+from math import isqrt
+from typing import Any
+
+SUBJECT_DEFAULT = "character"
+SUBJECTS = ("character", "effect")
+
+# Multipliers over the cell's equivalent side. Effect is half the character
+# floor at the formula level; integer ceilings can differ by 1.
+SUBJECT_FLOOR_RATIOS = {"character": (1, 1), "effect": (1, 2)}
+
+
+def subject_kind(request: dict[str, Any]) -> str:
+ """The run's declared subject; absent field = character (legacy)."""
+ kind = request.get("subject", SUBJECT_DEFAULT)
+ if kind not in SUBJECTS:
+ raise SystemExit(
+ f"unknown subject kind: {kind!r} (expected one of {', '.join(SUBJECTS)})"
+ )
+ return kind
+
+
+def cell_area(request: dict[str, Any]) -> int:
+ """Declared cell area, validated without a silent clamp."""
+ cell = request.get("cell")
+ if not isinstance(cell, dict):
+ raise SystemExit("sprite-request.json cell must be an object")
+ width = int(cell.get("width", cell.get("size", 0)))
+ height = int(cell.get("height", cell.get("size", 0)))
+ if width <= 0 or height <= 0:
+ raise SystemExit("sprite-request.json cell width/height must be positive")
+ return width * height
+
+
+def _ceil_ratio_sqrt(area: int, numerator: int, denominator: int) -> int:
+ """Return ceil(numerator/denominator * sqrt(area)) with integer math."""
+ scaled = area * numerator * numerator
+ root = isqrt(scaled)
+ if root * root < scaled:
+ root += 1
+ return (root + denominator - 1) // denominator
+
+
+def default_min_used_pixels(request: dict[str, Any]) -> int:
+ kind = subject_kind(request)
+ numerator, denominator = SUBJECT_FLOOR_RATIOS[kind]
+ return _ceil_ratio_sqrt(cell_area(request), numerator, denominator)
+
+
+def sparse_frame_error(index: int, nontransparent: int, floor: int, kind: str) -> str:
+ """Failure text that names the remedy — an unexplained rejection reads as a
+ generation failure and gets the run abandoned (measured: 7 effect runs)."""
+ remedy = (
+ 'small-subject run? declare "subject": "effect" in sprite-request.json, '
+ "or pass --min-used-pixels"
+ if kind == SUBJECT_DEFAULT
+ else "pass --min-used-pixels if this frame is legitimate"
+ )
+ return (
+ f"frame {index:02d} is empty or too sparse "
+ f"({nontransparent} pixels < {floor}, {kind} profile floor — {remedy})"
+ )
diff --git a/sprite_gen/util/__init__.py b/sprite_gen/util/__init__.py
new file mode 100644
index 0000000..9881313
--- /dev/null
+++ b/sprite_gen/util/__init__.py
@@ -0,0 +1 @@
+# SPDX-License-Identifier: Apache-2.0
diff --git a/sprite_gen/util/gif_utils.py b/sprite_gen/util/gif_utils.py
new file mode 100644
index 0000000..14aeb60
--- /dev/null
+++ b/sprite_gen/util/gif_utils.py
@@ -0,0 +1,90 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Shared GIF helpers for sprite-gen.
+
+GIF previews must not leak the previous frame through transparent pixels. Use a
+fresh transparent palette index per frame and GIF disposal method 2, so each
+frame clears before the next one is drawn.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+from typing import Iterable
+
+from PIL import Image, ImageSequence
+
+
+def delay_ticks_to_duration_ms(delay_ticks: int) -> int:
+ """Convert ImageMagick/GIF delay ticks (1/100 sec) to PIL milliseconds."""
+ if delay_ticks <= 0:
+ raise ValueError("delay_ticks must be positive")
+ return delay_ticks * 10
+
+
+def _prepare_transparent_frame(frame: Image.Image, alpha_threshold: int) -> Image.Image:
+ rgba = frame.convert("RGBA")
+ alpha = rgba.getchannel("A")
+
+ # Keep invisible RGB out of the adaptive palette; otherwise transparent
+ # source pixels can steal palette entries and produce colored fringe.
+ rgb = Image.new("RGB", rgba.size, (0, 0, 0))
+ rgb.paste(rgba.convert("RGB"), mask=alpha)
+
+ paletted = rgb.convert("P", palette=Image.ADAPTIVE, colors=255)
+ palette = paletted.getpalette() or []
+ if len(palette) < 768:
+ palette.extend([0] * (768 - len(palette)))
+ palette[255 * 3 : 255 * 3 + 3] = [0, 0, 0]
+ paletted.putpalette(palette)
+
+ transparent_mask = Image.eval(alpha, lambda value: 255 if value <= alpha_threshold else 0)
+ paletted.paste(255, transparent_mask)
+ paletted.info["transparency"] = 255
+ paletted.info["disposal"] = 2
+ return paletted
+
+
+def save_clean_gif(
+ frames: Iterable[Image.Image],
+ output_path: Path,
+ *,
+ duration_ms: int,
+ loop: int = 0,
+ alpha_threshold: int = 8,
+) -> None:
+ """Save RGBA frames as a clean transparent GIF.
+
+ `loop=0` means infinite loop in GIF/Pillow terminology.
+ """
+ if duration_ms <= 0:
+ raise ValueError("duration_ms must be positive")
+ prepared = [_prepare_transparent_frame(frame, alpha_threshold) for frame in frames]
+ if not prepared:
+ raise ValueError("at least one frame is required")
+ output_path.parent.mkdir(parents=True, exist_ok=True)
+ prepared[0].save(
+ output_path,
+ save_all=True,
+ append_images=prepared[1:],
+ duration=duration_ms,
+ loop=loop,
+ disposal=2,
+ transparency=255,
+ )
+
+
+def gif_report(path: Path) -> dict[str, object]:
+ """Return frame count, delay list, loop, transparency, and disposal values."""
+ with Image.open(path) as image:
+ frames = list(ImageSequence.Iterator(image))
+ delays = [int(frame.info.get("duration", 0) / 10) for frame in frames]
+ alpha_extrema = [frame.convert("RGBA").getchannel("A").getextrema() for frame in frames]
+ disposal = [getattr(frame, "disposal_method", None) for frame in frames]
+ return {
+ "path": str(path),
+ "frames": len(frames),
+ "delay_ticks": delays,
+ "loop": image.info.get("loop", 0),
+ "transparent": all(min_alpha < 255 for min_alpha, _max_alpha in alpha_extrema),
+ "disposal": disposal,
+ }
diff --git a/tests/compose/test_export_aseprite.py b/tests/compose/test_export_aseprite.py
new file mode 100644
index 0000000..e36f557
--- /dev/null
+++ b/tests/compose/test_export_aseprite.py
@@ -0,0 +1,109 @@
+# SPDX-License-Identifier: Apache-2.0
+from __future__ import annotations
+
+import json
+import subprocess
+import sys
+from pathlib import Path
+
+from conftest import run_script
+from sprite_gen import cli
+from sprite_gen.compose import export_aseprite
+from sprite_gen.compose.export_aseprite import aseprite_json, split_state_jsons
+
+ROOT = Path(__file__).resolve().parents[2]
+FRAME_KEYS = {"filename", "frame", "rotated", "trimmed", "spriteSourceSize", "sourceSize", "duration"}
+
+
+def _manifest() -> dict:
+ return {
+ "game_input": "sprite-sheet-alpha.png",
+ "animation": {"rows": {
+ "idle": {"fps": 8, "durations_ms": [125, 125], "loop": True},
+ "walk": {"fps": 11, "durations_ms": [90, 90, 90], "loop": True},
+ }},
+ "frame_layout": {
+ "sheetWidth": 128,
+ "sheetHeight": 128,
+ "cellWidth": 64,
+ "cellHeight": 64,
+ "rows": {
+ "idle": [{"x": 0, "y": 0, "w": 64, "h": 64}, {"x": 64, "y": 0, "w": 64, "h": 64}],
+ "walk": [{"x": 0, "y": 64, "w": 64, "h": 64}, {"x": 64, "y": 64, "w": 64, "h": 64}, {"x": 0, "y": 64, "w": 64, "h": 64}],
+ },
+ },
+ }
+
+
+def test_aseprite_array_preserves_geometry_tags_and_timing() -> None:
+ data = aseprite_json(_manifest())
+ assert all(set(frame) == FRAME_KEYS for frame in data["frames"])
+ assert [frame["filename"] for frame in data["frames"]] == ["0", "1", "2", "3", "4"]
+ assert [frame["duration"] for frame in data["frames"]] == [125, 125, 90, 90, 90]
+ assert data["frames"][2]["frame"] == data["frames"][4]["frame"]
+ assert data["meta"]["frameTags"] == [
+ {"name": "idle", "from": 0, "to": 1, "direction": "forward"},
+ {"name": "walk", "from": 2, "to": 4, "direction": "forward"},
+ ]
+
+
+def test_flame_split_uses_hashes_and_local_indices() -> None:
+ documents = split_state_jsons(_manifest(), fmt="json-hash")
+ assert list(documents["walk"]["frames"]) == ["0", "1", "2"]
+ assert documents["walk"]["frames"]["0"]["frame"] == documents["walk"]["frames"]["2"]["frame"]
+ assert {doc["meta"]["image"] for doc in documents.values()} == {"sprite-sheet-alpha.png"}
+
+
+def test_manifest_mismatch_fails_loud() -> None:
+ manifest = _manifest()
+ del manifest["animation"]["rows"]["walk"]
+ try:
+ aseprite_json(manifest)
+ except ValueError as exc:
+ assert "disagree" in str(exc)
+ else: # pragma: no cover
+ raise AssertionError("mismatched manifest exported")
+
+
+def test_cli_reuses_exporter_declaration() -> None:
+ _description, add_arguments, run = cli.COMMANDS["export-aseprite"]
+ assert add_arguments is export_aseprite.add_arguments
+ assert run is export_aseprite.run
+
+
+def test_real_composed_run_exports_phaser_and_flame_shapes(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
+
+ command = [sys.executable, "-m", "sprite_gen.cli", "export-aseprite", "--run-dir", str(fixture_run_dir)]
+ result = subprocess.run(command, cwd=ROOT, capture_output=True, text=True)
+ assert result.returncode == 0, result.stdout + result.stderr
+ exported = json.loads((fixture_run_dir / "exports" / "aseprite.json").read_text(encoding="utf-8"))
+ manifest = json.loads((fixture_run_dir / "manifest.json").read_text(encoding="utf-8"))
+ assert exported["meta"]["size"] == {
+ "w": manifest["frame_layout"]["sheetWidth"],
+ "h": manifest["frame_layout"]["sheetHeight"],
+ }
+ assert (fixture_run_dir / exported["meta"]["image"]).is_file()
+
+ result = subprocess.run(command + ["--format", "json-hash", "--split-states"], cwd=ROOT, capture_output=True, text=True)
+ assert result.returncode == 0, result.stdout + result.stderr
+ for state, rects in manifest["frame_layout"]["rows"].items():
+ document = json.loads((fixture_run_dir / "exports" / "aseprite" / f"{state}.json").read_text(encoding="utf-8"))
+ assert list(document["frames"]) == [str(index) for index in range(len(rects))]
+
+
+def test_output_must_stay_inside_run_dir(fixture_run_dir: Path) -> None:
+ assert export_aseprite.run(fixture_run_dir, output="../escape.json") == 1
+ assert not (fixture_run_dir.parent / "escape.json").exists()
+
+
+def test_output_cannot_replace_canonical_run_files_or_exports_root(fixture_run_dir: Path) -> None:
+ manifest = fixture_run_dir / "manifest.json"
+ before = manifest.read_bytes() if manifest.exists() else None
+ assert export_aseprite.run(fixture_run_dir, output="manifest.json") == 1
+ assert (manifest.read_bytes() if manifest.exists() else None) == before
+ assert export_aseprite.run(fixture_run_dir, output=".", split_states=True) == 1
+ assert export_aseprite.run(fixture_run_dir, output="exports", split_states=True) == 1
diff --git a/tests/compose/test_layer_compose.py b/tests/compose/test_layer_compose.py
new file mode 100644
index 0000000..fdfae09
--- /dev/null
+++ b/tests/compose/test_layer_compose.py
@@ -0,0 +1,701 @@
+# 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",
+ "motion_phase_guides": False,
+ "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_composite_bake_is_byte_identical_across_runs(tmp_path: Path) -> None:
+ """Same run, same bytes — the determinism claim the whole feature rests on."""
+ run_dir = _build_run(tmp_path)
+
+ compose_layers.bake(run_dir)
+ first = {path.name: _digest(path) for path in sorted(_layers_dir(run_dir).iterdir())}
+ compose_layers.bake(run_dir)
+ 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_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, 1, 2, 63, 127, 128, 200, 254, 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."""
+ 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"))
+
+ compose_layers.bake(run_dir)
+ manifest = json.loads(
+ (_layers_dir(run_dir) / "walk_with_can.manifest.json").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"
+
+
+def test_a_composite_states_it_has_no_alpha_report_instead_of_naming_another_kind(
+ tmp_path: Path) -> None:
+ """`sprite_sheet_alpha_report` names THIS sheet's alpha report — a composite has none.
+
+ The key stays (key-set parity above) 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"))
+
+ 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 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
+
+
+def test_base_manifest_gains_rig_and_track_only_for_a_rig_run(tmp_path: Path) -> None:
+ """Landmarks reach the runtime as atlas-absolute integers, one per play position."""
+ run_dir = _build_run(tmp_path)
+ assert run_script("compose_sprite_atlas.py", "--run-dir", str(run_dir)).returncode == 0
+ manifest = json.loads((run_dir / "manifest.json").read_text(encoding="utf-8"))
+
+ assert manifest["rig"]["profile"] == "humanoid_biped"
+ for state in ("walk", "hold", "can"):
+ rects = manifest["frame_layout"]["rows"][state]
+ entries = manifest["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 manifest["animation"]["rows"]["can"]["track"] == "prop_effect"
+ assert manifest["animation"]["rows"]["walk"]["track"] == "base"
+
+
+# ---------------------------------------------------------- 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:
+ """Determinism 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 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"]
+
+
[email protected]("value", ["", "walk_with_can,", "a,,b", " "])
+def test_the_cli_refuses_a_malformed_names_list(tmp_path: Path, value: str) -> None:
+ """An empty entry is a typo, never "all" — silently dropping it bakes another set."""
+ run_dir = _build_run(tmp_path)
+
+ result = _cli(run_dir, "--names", value)
+
+ assert result.returncode != 0
+ assert "--names expects a comma-separated list" in result.stderr
+ assert not _layers_dir(run_dir).exists()
+
+
[email protected]("value", ["walk_with_can,walk_with_can", "nope,walk_with_can,nope"])
+def test_the_cli_refuses_a_repeated_name(tmp_path: Path, value: str) -> 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", value)
+
+ 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()
+
+
+def test_the_cli_refuses_a_non_layer_run_by_name(tmp_path: Path) -> None:
+ """"Not a layer run" and "nothing to compose" are different answers."""
+ request = _request()
+ del request["rig"]
+ del request["layers"]
+ for entry in request["states"].values():
+ entry.pop("track")
+ run_dir = _build_run(tmp_path, request)
+
+ result = _cli(run_dir)
+
+ assert result.returncode != 0
+ assert "not a layer run" 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
new file mode 100644
index 0000000..13e2d1c
--- /dev/null
+++ b/tests/compose/test_layer_contract.py
@@ -0,0 +1,630 @@
+# 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_valid_stack_has_no_errors() -> None:
+ assert layers.validate_layer_request(_request()) == []
+
+
+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"
+
+
+def test_unknown_track_kind_is_rejected() -> None:
+ request = _request()
+ request["states"]["walk"]["track"] = "torso_only"
+
+ errors = layers.validate_layer_request(request)
+ assert any("states.walk.track" in e for e in errors)
+
+
+def test_humanoid_requires_crown_on_every_frame() -> None:
+ request = _request()
+ del request["rig"]["landmarks"]["walk"]["1"]["crown"]
+
+ errors = layers.validate_layer_request(request)
+ assert any("crown" in e and "[1]" in e for e in errors)
+
+
[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
+
+
[email protected]("profile", sorted(layers.PROFILES))
+def test_required_landmarks_reads_profile_and_track_together(profile: str) -> None:
+ 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.
+
+UNKNOWN_PROFILES = [
+ pytest.param("mecha", id="unknown-string"),
+ pytest.param(None, id="null"),
+ pytest.param(3, id="number"),
+ pytest.param(True, id="bool"),
+ pytest.param(["humanoid_biped"], id="list-unhashable"),
+ pytest.param({"profile": "humanoid_biped"}, id="dict-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)
+
+
[email protected]("coordinate", [[True, 8], [32, False]])
+def test_boolean_landmark_coordinates_are_rejected(coordinate: list) -> 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"] = coordinate
+
+ errors = layers.validate_layer_request(request)
+ assert any("crown" in e and "integers" in e for e in errors), errors
+
+
+def test_unknown_profile_is_rejected() -> None:
+ request = _request()
+ request["rig"]["profile"] = "mecha"
+
+ assert any("rig.profile" in e for e in layers.validate_layer_request(request))
+
+
+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", "yes"), ("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", "motion_phase_guides", "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 test_prepare_emits_the_documented_non_layer_request_surface(tmp_path: Path) -> None:
+ out_dir = tmp_path / "run"
+ result = run_script("prepare_sprite_run.py", "--out-dir", str(out_dir),
+ "--character-id", "rigbot")
+ 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 layers.has_layer_contract(request) is False
+
+
+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/conftest.py b/tests/conftest.py
new file mode 100644
index 0000000..822e103
--- /dev/null
+++ b/tests/conftest.py
@@ -0,0 +1,49 @@
+# SPDX-License-Identifier: Apache-2.0
+import os
+import re
+import shutil
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+
+REPO_ROOT = Path(__file__).resolve().parents[1]
+SCRIPTS_DIR = REPO_ROOT / "scripts"
+FIXTURE_RUN = Path(__file__).resolve().parent / "fixtures" / "run"
+
+
+def help_options(*argv: str) -> set[str]:
+ """Return flags advertised by ``<argv> --help`` without ANSI styling.
+
+ Python 3.14 colorizes argparse output when the surrounding environment asks
+ for color. These tests compare the declared option surface, so they pin the
+ interpreter-specific override rather than depending on the invoking shell.
+ """
+ env = {**os.environ, "PYTHON_COLORS": "0"}
+ proc = subprocess.run(
+ [sys.executable, *argv, "--help"],
+ cwd=REPO_ROOT,
+ capture_output=True,
+ text=True,
+ env=env,
+ )
+ assert proc.returncode == 0, proc.stderr
+ return set(re.findall(r"(?<![\w-])--[a-z][\w-]*", proc.stdout))
+
+
+def run_script(name: str, *args: str) -> subprocess.CompletedProcess[str]:
+ """Invoke a pipeline script exactly as the quickstart does."""
+ return subprocess.run(
+ [sys.executable, str(SCRIPTS_DIR / name), *args],
+ capture_output=True,
+ text=True,
+ )
+
+
+def fixture_run_dir(tmp_path: Path) -> Path:
+ """A throwaway copy of the golden fixture run dir."""
+ run_dir = tmp_path / "run"
+ shutil.copytree(FIXTURE_RUN, run_dir)
+ return run_dir
diff --git a/tests/curate/test_anchor_selection.py b/tests/curate/test_anchor_selection.py
new file mode 100644
index 0000000..27c55e4
--- /dev/null
+++ b/tests/curate/test_anchor_selection.py
@@ -0,0 +1,708 @@
+# SPDX-License-Identifier: Apache-2.0
+"""방향 앵커 = 승인된 프레임 (maintainer 2026-07-25).
+
+- 기본 앵커 = 그 방향 앵커 행의 **큐레이션 시퀀스 첫 인스턴스** (index 0 이 아니다) 이고,
+ 베이크는 픽셀 편집·변형까지 태운 결과다 — raw 크롭이 아니다.
+- 사용자가 큐레이션 뷰/CLI 로 **어떤 프레임이 앵커인지 지정**할 수 있다 (같은 방향의
+ 다른 행, 시퀀스에 없는 후보 풀 프레임도 가능).
+- 사라진 인스턴스를 가리키는 지정은 fail-loud (조용한 기본값 복귀 금지).
+- 리롤/생성 플랜/뷰 칩이 같은 앵커 진실을 쓴다.
+"""
+
+from __future__ import annotations
+
+import json
+import sys
+from pathlib import Path
+
+import pytest
+from PIL import Image
+
+ROOT = Path(__file__).resolve().parents[2]
+
+from sprite_gen.curate import anchor as anchor_mod # noqa: E402
+from sprite_gen.frames import extract as extract_module # noqa: E402
+from sprite_gen.curate.curation import (anchor_choices, load_curation, state_instances, # noqa: E402
+ write_curation_atomic)
+
+MAGENTA = (255, 0, 255)
+PITCH = 8
+LOGICAL = (20, 36)
+GAP = 40
+
+
+def _frame_art(seed: int) -> Image.Image:
+ """결정론 합성 프레임 — 논리 픽셀 노이즈(격자 검출이 가능한 밀도)를 PITCH 배 확대.
+
+ 단색 블록은 내부 경계가 없어 피치 검출이 실패한다 (실측: "empty or too sparse")
+ — test_takes_heal 과 같은 노이즈 방식을 쓴다."""
+ import random
+
+ rng = random.Random(seed)
+ art = Image.new("RGB", LOGICAL, MAGENTA)
+ for y in range(LOGICAL[1]):
+ for x in range(LOGICAL[0]):
+ if rng.random() < 0.55:
+ art.putpixel((x, y), (rng.randrange(30, 220), rng.randrange(30, 220),
+ rng.randrange(30, 220)))
+ return art.resize((LOGICAL[0] * PITCH, LOGICAL[1] * PITCH), Image.Resampling.NEAREST)
+
+
+def _strip(frames: int, seed0: int) -> Image.Image:
+ frame = _frame_art(seed0) # 한 행의 프레임들은 같은 그림 (앵커 판정은 인덱스로 한다)
+ strip = Image.new("RGB", (frame.width * frames + GAP * (frames + 1),
+ frame.height + GAP * 2), MAGENTA)
+ for i in range(frames):
+ strip.paste(frame, (GAP + i * (frame.width + GAP), GAP))
+ return strip
+
+
+def _build_direction_run(root: Path, extract_states: str | None = "all") -> Path:
+ """down/side 방향 계약 + pp 추출 런 (방향별 idle 앵커 행 4프레임 + walk 행 3프레임).
+
+ `extract_states` 로 생성 진행 구간을 고른다: `"all"`(완전 추출) ·
+ `"down_idle,side_idle"`(stage-1: 앵커 행만) · `None`(추출 전)."""
+ run_dir = root / "run"
+ request = {
+ "version": 1,
+ "kind": "sprite-gen-request",
+ "engine": "component-row",
+ "character": {"id": "anchorbot", "description": "anchor fixture", "base_image": None},
+ "cell": {"shape": "square", "width": 96, "height": 96, "safe_margin_x": 8,
+ "safe_margin_y": 8, "size": 96, "safe_margin": 8},
+ "chroma_key": {"name": "magenta", "hex": "#FF00FF", "rgb": [255, 0, 255],
+ "selection": "fallback"},
+ "layout": "taxonomy/v1",
+ "directions": {"set": ["down", "side"], "mirror": {}, "anchor_suffix": "idle"},
+ "states": {
+ "down_idle": {"frames": 4, "fps": 4, "loop": True, "action": "anchor row"},
+ "side_idle": {"frames": 4, "fps": 4, "loop": True, "action": "anchor row"},
+ "down_walk": {"frames": 3, "fps": 8, "loop": True, "action": "action row"},
+ "side_walk": {"frames": 3, "fps": 8, "loop": True, "action": "action row"},
+ },
+ "fit": {"pixel_unfake": True, "logical_height": 48},
+ }
+ (run_dir / "raw" / "down").mkdir(parents=True)
+ (run_dir / "raw" / "side").mkdir(parents=True)
+ _strip(4, seed0=1).save(run_dir / "raw" / "down" / "idle.png")
+ _strip(4, seed0=60).save(run_dir / "raw" / "side" / "idle.png")
+ _strip(3, seed0=20).save(run_dir / "raw" / "down" / "walk.png")
+ _strip(3, seed0=40).save(run_dir / "raw" / "side" / "walk.png")
+ Image.new("RGB", (64, 64), (10, 200, 10)).save(run_dir / "base-source.png")
+ (run_dir / "sprite-request.json").write_text(
+ json.dumps(request, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
+ if extract_states is not None:
+ assert extract_module.run(run_dir=run_dir, states=extract_states) == 0
+ return run_dir
+
+
+def _save_curation(run_dir: Path, states: dict, anchors: dict | None = None) -> None:
+ payload = {"version": 1, "kind": "sprite-gen-curation", "states": states}
+ if anchors is not None:
+ payload["anchors"] = anchors
+ write_curation_atomic(run_dir, payload)
+
+
+def _pins(doc: dict | None) -> dict:
+ """지정의 **의미만** 비교 (state/index) — `revision` 세대 스탬프는 구현 세부다."""
+ return {d: {"state": p["state"], "index": p["index"]} for d, p in anchor_choices(doc).items()}
+
+
+def _request(run_dir: Path) -> dict:
+ return json.loads((run_dir / "sprite-request.json").read_text(encoding="utf-8"))
+
+
+def direction_run(tmp_path: Path) -> Path:
+ return _build_direction_run(tmp_path)
+
+
+def stage1_run(tmp_path: Path) -> Path:
+ """**워크플로 stage-1 그대로**: 방향 앵커 행만 생성·추출됐고 액션 행은 아직 없다.
+
+ 앵커 소비자는 정의상 이 구간에서 돈다 (stage-2 행을 생성하려면 그 방향 앵커 ref 가
+ 먼저 필요하다). 플랜 초기 픽스처가 전부 '완전 추출된 런'이라 이 구간을 한 건도
+ 덮지 않았고, 그래서 `require_frames_manifest`(완성 소비자 게이트) 오사용이
+ 테스트를 통과했다 — validator 검증 2026-07-25 reject 의 근본 원인."""
+ return _build_direction_run(tmp_path, extract_states="down_idle,side_idle")
+
+
+def ungenerated_run(tmp_path: Path) -> Path:
+ """방향 계약만 선언되고 추출이 아예 없는 런 (생성 이전 구간)."""
+ return _build_direction_run(tmp_path, extract_states=None)
+
+
+# --- 기본값: 시퀀스 첫 인스턴스 + 후처리 반영 ---------------------------------
+
+def test_default_anchor_is_the_curated_sequence_head_not_index_zero(direction_run: Path) -> None:
+ run_dir = direction_run
+ request = _request(run_dir)
+ # 사용자가 앞 두 프레임을 기각(보관)하고 3,2 순서로 재정렬
+ _save_curation(run_dir, {"down_idle": {"deleted": [0, 1], "selected": [3, 2]}})
+ resolved = anchor_mod.resolve_anchor(request, load_curation(run_dir), "down")
+ assert resolved == {"direction": "down", "state": "down_idle", "index": 3, "source": "default"}
+
+
+def test_anchor_bake_carries_pixel_edits_and_transform(direction_run: Path) -> None:
+ """앵커 재료 = 승인된 모습. 픽셀 편집이 앵커 ref 에 실제로 들어있어야 한다."""
+ run_dir = direction_run
+ request = _request(run_dir)
+ _save_curation(run_dir, {"down_idle": {
+ "selected": [0, 1, 2, 3],
+ # 셀 좌표 픽셀 편집 (한 논리 블록 전체를 덮는 8x8 은 아니어도 색은 나타난다)
+ "pixels": {"0": {f"{x},{y}": "#ff0000" for x in range(40, 48) for y in range(40, 48)}},
+ }})
+ image, resolved = anchor_mod.anchor_image(run_dir, request, load_curation(run_dir), "down")
+ assert resolved["state"] == "down_idle" and resolved["index"] == 0
+ colors = {px[:3] for px in image.convert("RGBA").getdata() if px[3] > 0}
+ assert (255, 0, 0) in colors, "픽셀 편집이 앵커 ref 에 반영되지 않았다 (raw 를 구웠다)"
+
+
+def test_materialize_writes_ref_and_removes_legacy_snapshot(direction_run: Path) -> None:
+ run_dir = direction_run
+ legacy = run_dir / "references" / "anchors" / "down-idle-x8.png"
+ legacy.parent.mkdir(parents=True, exist_ok=True)
+ legacy.write_bytes(b"stale")
+ out = anchor_mod.materialize(run_dir, "down")
+ assert out == run_dir / "references" / "anchors" / "down-anchor-x8.png"
+ assert out.is_file()
+ assert not legacy.exists(), "앵커가 idle 행에 묶여 있던 시절의 파일이 남아 두 진실이 됐다"
+ with Image.open(out) as im:
+ assert im.width % 8 == 0 and im.height % 8 == 0 # x8 니어리스트 확대
+
+
+# --- 생성 도중 구간 (앵커 소비자가 실제로 도는 시점) ---------------------------
+# 회귀 고정: 앵커 진입점이 `require_frames_manifest`(완성된 생성물 소비자 게이트)를
+# 물면 request 의 *모든* 행에 매니페스트 행을 요구해서, "행 생성 직전에 매번 돌려라"
+# 라는 계약이 **항상** corrupt-manifest 로 죽는다 (validator 검증 2026-07-25 실측).
+
+def test_stage1_run_serves_the_anchor_ref(stage1_run: Path, capsys) -> None:
+ """앵커 행만 추출된 시점에 액션 행의 identity ref 가 나와야 한다 (그게 유일한 용도다)."""
+ run_dir = stage1_run
+ assert anchor_mod.run(run_dir=run_dir, for_state="side_walk") == 0
+ printed = capsys.readouterr().out.strip()
+ assert printed == "references/anchors/side-anchor-x8.png"
+ assert (run_dir / printed).is_file()
+ assert anchor_mod.run(run_dir=run_dir, direction="down") == 0
+ assert anchor_mod.run(run_dir=run_dir, all_directions=True) == 0
+ for direction in ("down", "side"):
+ assert (run_dir / f"references/anchors/{direction}-anchor-x8.png").is_file()
+
+
+def test_stage1_run_pick_persists_and_bakes(stage1_run: Path) -> None:
+ run_dir = stage1_run
+ assert anchor_mod.run(run_dir=run_dir, pick="down_idle#2") == 0
+ assert _pins(load_curation(run_dir))["down"] == {"state": "down_idle", "index": 2}
+ assert (run_dir / "references" / "anchors" / "down-anchor-x8.png").is_file()
+
+
+def test_ungenerated_run_pick_is_refused_not_half_saved(ungenerated_run: Path) -> None:
+ """추출 전 런에서는 지정 자체가 거부된다 (본 적 없는 프레임 + 지문 계산 불가).
+
+ 옛 계약은 "지정은 저장하고 ref 만 나중에" 였는데, 그렇게 저장된 스탬프 없는 핀이 다음
+ 로드에서 '재생성됐다' 로 오분류돼 그 방향 생성을 막았다 (validator 5차 기각 2)."""
+ with pytest.raises(anchor_mod.AnchorUnavailable) as excinfo:
+ anchor_mod.run(run_dir=ungenerated_run, pick="down_idle#1")
+ assert excinfo.value.kind == "row-not-extracted"
+ assert _pins(load_curation(ungenerated_run)) == {}
+ assert not (ungenerated_run / "references" / "anchors").exists()
+
+
+def test_ungenerated_run_for_state_fails_loud_with_the_real_reason(ungenerated_run: Path) -> None:
+ """ref 를 **요구**하는 진입점은 조용히 넘어가지 않고, 원인을 정확히 말해야 한다."""
+ with pytest.raises(anchor_mod.AnchorUnavailable) as excinfo:
+ anchor_mod.run(run_dir=ungenerated_run, for_state="down_walk")
+ assert excinfo.value.kind in anchor_mod.AnchorUnavailable.PENDING_KINDS
+ assert excinfo.value.pending is True
+ assert "corrupt" not in str(excinfo.value)
+
+
+# --- 실패 메시지가 **프로세스 stderr 까지** 도달하는가 -------------------------
+# 회귀 고정: 분류 슬러그를 `SystemExit.code` 에 얹으면 인터프리터가 그걸 stderr 에 찍어
+# 안내문이 통째로 사라진다 (실측: `anchor --for-state` 추출 전 호출의 stderr = "no-frames").
+# 예외 객체의 `str()` 만 보는 테스트는 이 사각을 못 본다 — CLI 를 **서브프로세스로** 돈다.
+
+def _cli(run_dir: Path, *args: str):
+ import subprocess
+
+ return subprocess.run([sys.executable, "-m", "sprite_gen.cli", "anchor",
+ "--run-dir", str(run_dir), *args],
+ capture_output=True, text=True, cwd=str(ROOT))
+
+
[email protected]("args,needle", [
+ (("--for-state", "down_walk"), "generate and extract"),
+ (("--direction", "down"), "generate and extract"),
+])
+def test_cli_pending_failure_prints_the_guidance(ungenerated_run: Path, args, needle) -> None:
+ proc = _cli(ungenerated_run, *args)
+ assert proc.returncode != 0
+ assert needle in proc.stderr, proc.stderr
+ assert proc.stderr.strip() not in anchor_mod.AnchorUnavailable.PENDING_KINDS
+
+
+def test_cli_broken_pin_failure_prints_the_guidance(direction_run: Path) -> None:
+ _save_curation(direction_run, {"down_idle": {"deleted": [3], "selected": [0, 1, 2]}},
+ anchors={"down": {"state": "down_idle", "index": 3}})
+ proc = _cli(direction_run, "--for-state", "down_walk")
+ assert proc.returncode != 0
+ assert "no longer exists" in proc.stderr, proc.stderr
+ assert "re-pick the anchor frame" in proc.stderr
+ assert proc.stderr.strip() != "pick-missing"
+
+
+def test_all_bakes_every_bakeable_direction_before_failing(tmp_path: Path) -> None:
+ """벌크(`--all`)는 끝까지 돌고 한 번에 보고한다 — 중간에 죽으면 재실행 지점이 모호하다."""
+ run_dir = _build_direction_run(tmp_path, extract_states="side_idle")
+ with pytest.raises(anchor_mod.AnchorUnavailable) as excinfo:
+ anchor_mod.run(run_dir=run_dir, all_directions=True)
+ assert "1 of 2 direction(s)" in str(excinfo.value)
+ assert (run_dir / "references" / "anchors" / "side-anchor-x8.png").is_file()
+ assert not (run_dir / "references" / "anchors" / "down-anchor-x8.png").exists()
+
+
+def test_cli_pick_direction_mismatch_is_reported(direction_run: Path) -> None:
+ """지정 방향과 명시 `--direction` 이 어긋나면 조용히 다른 방향을 굽지 않는다."""
+ proc = _cli(direction_run, "--pick", "side_idle#0", "--direction", "down")
+ assert proc.returncode == 0, proc.stderr
+ assert "does not own 'side_idle'" in proc.stdout
+ assert _pins(load_curation(direction_run)) == {"side": {"state": "side_idle", "index": 0}}
+ for d in ("down", "side"):
+ assert (direction_run / f"references/anchors/{d}-anchor-x8.png").is_file()
+
+
+def test_invalid_pick_writes_nothing(direction_run: Path) -> None:
+ """커밋 전 검증 (Atomicity): 잘못된 지정은 사이드카에 잔류하지 않는다."""
+ run_dir = direction_run
+ with pytest.raises(anchor_mod.AnchorUnavailable) as excinfo:
+ anchor_mod.run(run_dir=run_dir, pick="down_idle#99")
+ assert excinfo.value.kind == "pick-missing"
+ assert _pins(load_curation(run_dir)) == {}
+
+
+def test_stage1_view_reports_no_anchor_error(stage1_run: Path) -> None:
+ """작업 중간 런은 멀쩡한 상태다 — 뷰에 오류가 뜨면 안 된다."""
+ from sprite_gen.serve.serve_curation import build_run_state
+
+ snapshot = build_run_state(stage1_run)
+ for group in snapshot["directionGroups"]:
+ if group.get("mirrorOf"):
+ continue
+ assert group["anchorError"] is None, group
+ assert group["anchorPending"] is False
+ assert group["anchorFrame"]["state"] == f"{group['direction']}_idle"
+ walk = next(s for s in snapshot["states"] if s["name"] == "side_walk")
+ assert [r for r in walk["refs"] if r["role"] == "anchor"], "앵커 칩이 사라졌다"
+
+
+def test_pending_and_broken_are_different_states(ungenerated_run: Path) -> None:
+ """`pending`(아직 안 뽑음)과 `broken`(사람이 고쳐야 함)은 뷰에서 다르게 취급된다."""
+ from sprite_gen.serve.serve_curation import build_run_state
+
+ run_dir = ungenerated_run
+ pending = next(g for g in build_run_state(run_dir)["directionGroups"]
+ if g["direction"] == "down")
+ assert pending["anchorPending"] is True
+ assert pending["anchorErrorCode"] in anchor_mod.AnchorUnavailable.PENDING_KINDS
+ assert pending["anchorUrl"] is None
+
+ _save_curation(run_dir, {}, anchors={"down": {"state": "side_walk", "index": 0}})
+ broken = next(g for g in build_run_state(run_dir)["directionGroups"]
+ if g["direction"] == "down")
+ assert broken["anchorPending"] is False
+ assert broken["anchorErrorCode"] == "pick-wrong-direction"
+
+
+# --- 세대 경계 (행이 재생성된 뒤) ----------------------------------------------
+# 회귀 고정: 사이드카 writer 가 세대 게이트(`load_curation_report`)를 우회해 raw 로 읽으면,
+# `stamp_curation` 이 모든 행에 현재 세대 지문을 다시 찍어 **드롭된 낡은 큐레이션이 부활**
+# 한다 — 그 부활한 selected 가 새 아트의 방향 앵커를 고른다 (validator 3차 기각 실측).
+
+def _regenerate_row(run_dir: Path, direction: str, pose: str, seed: int) -> None:
+ """raw 를 갈아끼우고 그 행만 재추출 = 리롤/재생성 (새 세대)."""
+ _strip(4, seed0=seed).save(run_dir / "raw" / direction / f"{pose}.png")
+ assert extract_module.run(run_dir=run_dir, states=f"{direction}_{pose}") == 0
+
+
+def test_cli_pick_does_not_resurrect_dropped_curation(direction_run: Path) -> None:
+ from sprite_gen.curate.curation import load_curation_report
+
+ run_dir = direction_run
+ _save_curation(run_dir, {"down_idle": {"deleted": [0, 1], "selected": [2, 3],
+ "pixels": {"2": {"10,10": "#ff0000"}}}})
+ _regenerate_row(run_dir, "down", "idle", seed=999)
+ dropped = load_curation_report(run_dir)[1]["dropped"]
+ assert "down_idle" in dropped, "세대 게이트가 낡은 행을 드롭하지 않았다 (전제 실패)"
+
+ # 다른 방향 지정 한 번 — 이것만으로 down_idle 이 되살아나면 안 된다
+ assert anchor_mod.run(run_dir=run_dir, pick="side_idle#0") == 0
+ doc = load_curation_report(run_dir)[0] or {}
+ assert "down_idle" not in (doc.get("states") or {}), "드롭된 큐레이션이 부활했다"
+ assert _pins(doc) == {"side": {"state": "side_idle", "index": 0}}
+ # 그래서 down 앵커는 새 세대의 시퀀스 헤드다 (죽은 selected 의 index 2 가 아니다)
+ resolved = anchor_mod.resolve_anchor(_request(run_dir), doc, "down")
+ assert (resolved["index"], resolved["source"]) == (0, "default")
+
+
+def test_pin_on_a_regenerated_row_fails_loud_instead_of_following(direction_run: Path) -> None:
+ """핀한 **그 행**이 리롤되면 같은 인덱스는 다른 그림이다 — 조용히 따라가지 않는다.
+
+ 따라가면 사용자가 본 적 없는 새 세대 프레임이 방향 identity 가 되어 액션 행 전부에
+ 번진다 (이 플랜이 존재하는 2026-07-19 사고와 같은 형태). 조용히 기본값으로 복귀해서도
+ 안 된다 — 문서 3곳이 "hard error" 로 못박은 계약이다."""
+ from sprite_gen.curate.curation import load_curation_report
+
+ run_dir = direction_run
+ _save_curation(run_dir, {"down_idle": {"selected": [0, 1, 2, 3],
+ "pixels": {"2": {"10,10": "#ff0000"}}},
+ "side_idle": {"selected": [0, 1, 2, 3]}},
+ anchors={"down": {"state": "down_idle", "index": 2}})
+ before = anchor_mod.materialize(run_dir, "down", quiet=True).read_bytes()
+ _regenerate_row(run_dir, "down", "idle", seed=31337)
+
+ doc, report = load_curation_report(run_dir)
+ assert report["anchors_stale"] == ["down"]
+ assert (doc.get("anchors") or {}).get("down"), "지정이 조용히 사라졌다 (기본값 복귀)"
+ with pytest.raises(anchor_mod.AnchorUnavailable) as excinfo:
+ anchor_mod.resolve_anchor(_request(run_dir), doc, "down")
+ assert excinfo.value.kind == "pick-stale-generation"
+ assert excinfo.value.pending is False # 뷰가 오류로 표시해야 한다
+ # 다시 찍으면 풀린다 (그리고 그때 비로소 새 세대 프레임을 굽는다)
+ assert anchor_mod.run(run_dir=run_dir, pick="down_idle#2") == 0
+ after = (run_dir / anchor_mod.anchor_ref_rel("down")).read_bytes()
+ assert after != before, "재지정 후에도 옛 세대 그림이 남았다"
+
+
+def _post_curation(run_dir: Path, body: dict) -> int:
+ """뷰의 저장 경로(HTTP POST /api/curation)를 그대로 태운다 — 서버 writer 검증용."""
+ import json as _json
+ import threading
+ import urllib.request
+ from functools import partial
+ from http.server import ThreadingHTTPServer
+
+ from sprite_gen.serve.serve_curation import CurationHandler
+
+ CurationHandler.run_dir = run_dir
+ CurationHandler.lang = "en"
+ srv = ThreadingHTTPServer(("127.0.0.1", 0), partial(CurationHandler))
+ threading.Thread(target=srv.serve_forever, daemon=True).start()
+ port = srv.server_address[1]
+ try:
+ snapshot = _json.loads(urllib.request.urlopen(f"http://127.0.0.1:{port}/api/run").read())
+ payload = {"version": 1, "kind": "sprite-gen-curation",
+ "runRevision": snapshot["runRevision"], **body}
+ req = urllib.request.Request(f"http://127.0.0.1:{port}/api/curation",
+ data=_json.dumps(payload).encode(), method="POST")
+ with urllib.request.urlopen(req) as res:
+ return res.status
+ finally:
+ srv.shutdown()
+
+
+def test_view_save_cannot_launder_a_stale_pin(direction_run: Path) -> None:
+ """뷰 저장(무관한 편집)이 낡은 핀을 현재 세대로 **세탁하지 못한다**.
+
+ 지문(`revision`)은 엔진 소유다: 뷰 payload 는 `{state, index}` 만 싣고, 저장 시 writer 가
+ 저장된 지문을 이월한다. 이월이 없으면 stamp 단계가 지문 없는 핀에 현재 세대 도장을 찍어
+ 낡은 핀이 유효해지고 오류 배너가 사라진다 — 4차에서 세운 fail-loud 계약이 뷰 저장 한 번에
+ 무효화됐다 (validator 5차 기각 실측)."""
+ from sprite_gen.curate.curation import load_curation_report
+
+ run_dir = direction_run
+ _save_curation(run_dir, {"down_idle": {"selected": [0, 1, 2, 3]},
+ "side_idle": {"selected": [0, 1, 2, 3]}},
+ anchors={"down": {"state": "down_idle", "index": 2}})
+ _regenerate_row(run_dir, "down", "idle", seed=8888)
+ assert load_curation_report(run_dir)[1]["anchors_stale"] == ["down"]
+
+ # 사용자가 재지정은 안 하고 무관한 편집만 저장한다 (뷰는 {state,index} 만 싣는다)
+ assert _post_curation(run_dir, {
+ "anchors": {"down": {"state": "down_idle", "index": 2}},
+ "states": {"side_idle": {"selected": [0, 1]}}}) == 200
+
+ doc, report = load_curation_report(run_dir)
+ assert report["anchors_stale"] == ["down"], "무관한 저장이 낡은 핀을 세탁했다"
+ with pytest.raises(anchor_mod.AnchorUnavailable) as excinfo:
+ anchor_mod.resolve_anchor(_request(run_dir), doc, "down")
+ assert excinfo.value.kind == "pick-stale-generation"
+
+
+def test_explicit_repin_clears_the_stale_pin(direction_run: Path) -> None:
+ """푸는 길은 **명시 재지정**뿐이다 (뷰의 stale 핀 버튼이 `repin: true` 를 싣는다)."""
+ from sprite_gen.curate.curation import load_curation_report
+
+ run_dir = direction_run
+ _save_curation(run_dir, {"down_idle": {"selected": [0, 1, 2, 3]}},
+ anchors={"down": {"state": "down_idle", "index": 2}})
+ _regenerate_row(run_dir, "down", "idle", seed=5150)
+ assert load_curation_report(run_dir)[1]["anchors_stale"] == ["down"]
+
+ assert _post_curation(run_dir, {
+ "anchors": {"down": {"state": "down_idle", "index": 2, "repin": True}},
+ "states": {}}) == 200
+
+ doc, report = load_curation_report(run_dir)
+ assert report["anchors_stale"] == []
+ resolved = anchor_mod.resolve_anchor(_request(run_dir), doc, "down")
+ assert (resolved["index"], resolved["source"]) == (2, "picked")
+ stored = json.loads((run_dir / "curation.json").read_text(encoding="utf-8"))
+ assert "repin" not in stored["anchors"]["down"] # 의도 표식은 저장하지 않는다
+
+
+def test_cannot_pin_a_row_that_is_not_extracted(stage1_run: Path) -> None:
+ """추출 전 행은 핀할 수 없다 — 본 적 없는 프레임이고, 지문도 계산되지 않아 나중에
+ "재생성됐다" 로 오분류돼 그 방향 생성을 막았다 (validator 5차 기각 2)."""
+ from sprite_gen.curate.curation import load_curation
+
+ with pytest.raises(anchor_mod.AnchorUnavailable) as excinfo:
+ anchor_mod.run(run_dir=stage1_run, pick="down_walk#1")
+ assert excinfo.value.kind == "row-not-extracted"
+ assert "not extracted yet" in str(excinfo.value)
+ assert _pins(load_curation(stage1_run)) == {}, "거부된 지정이 디스크에 남았다"
+
+
+def test_unstamped_pin_reports_unverifiable_not_regenerated(direction_run: Path) -> None:
+ """손으로 쓴(스탬프 없는) 핀은 "재생성됨" 이 아니라 "증명 불가" 로 말해야 한다."""
+ from sprite_gen.curate.curation import load_curation_report
+
+ run_dir = direction_run
+ _save_curation(run_dir, {"down_idle": {"selected": [0, 1, 2, 3]}})
+ doc = json.loads((run_dir / "curation.json").read_text(encoding="utf-8"))
+ doc["anchors"] = {"down": {"state": "down_idle", "index": 2}} # 지문 없이 직접 기입
+ doc["run_revision"] = "0" * 16 # fast-path 우회
+ (run_dir / "curation.json").write_text(json.dumps(doc), encoding="utf-8")
+
+ loaded, report = load_curation_report(run_dir)
+ assert report["anchors_stale"] == ["down"]
+ with pytest.raises(anchor_mod.AnchorUnavailable) as excinfo:
+ anchor_mod.resolve_anchor(_request(run_dir), loaded, "down")
+ assert excinfo.value.kind == "pick-unverifiable"
+ assert "no generation stamp" in str(excinfo.value)
+
+
+def test_pin_survives_when_every_curated_row_is_dropped(direction_run: Path) -> None:
+ """전 행이 드롭돼도 지정은 남아야 한다 — 남아 있어야 오류를 낼 수 있다."""
+ from sprite_gen.curate.curation import load_curation_report
+
+ run_dir = direction_run
+ _save_curation(run_dir, {"down_idle": {"selected": [0, 1, 2, 3]}},
+ anchors={"down": {"state": "down_idle", "index": 1}})
+ _regenerate_row(run_dir, "down", "idle", seed=4242)
+ doc, report = load_curation_report(run_dir)
+ assert report["dropped"] == ["down_idle"]
+ assert doc is not None, "지정까지 통째로 사라져 조용히 기본값으로 돌아갔다"
+ assert anchor_choices(doc)["down"]["stale"] is True
+
+
+def test_cli_clear_does_not_resurrect_dropped_curation(direction_run: Path) -> None:
+ from sprite_gen.curate.curation import load_curation_report
+
+ run_dir = direction_run
+ _save_curation(run_dir, {"down_idle": {"deleted": [0], "selected": [1, 2, 3]}},
+ anchors={"side": {"state": "side_idle", "index": 1}})
+ _regenerate_row(run_dir, "down", "idle", seed=777)
+ assert "down_idle" in load_curation_report(run_dir)[1]["dropped"]
+ assert anchor_mod.run(run_dir=run_dir, clear=True, direction="side") == 0
+ doc = load_curation_report(run_dir)[0] or {}
+ assert "down_idle" not in (doc.get("states") or {})
+ assert _pins(doc) == {}
+
+
+# --- 사용자 지정 ---------------------------------------------------------------
+
+def test_picked_frame_overrides_the_default_including_another_row(direction_run: Path) -> None:
+ run_dir = direction_run
+ request = _request(run_dir)
+ _save_curation(run_dir, {"down_idle": {"selected": [0, 1, 2, 3]}},
+ anchors={"down": {"state": "down_walk", "index": 2}})
+ resolved = anchor_mod.resolve_anchor(request, load_curation(run_dir), "down")
+ assert resolved == {"direction": "down", "state": "down_walk", "index": 2, "source": "picked"}
+
+
+def test_picked_frame_may_be_a_pool_candidate(direction_run: Path) -> None:
+ """시퀀스에 없는(선택 안 된) 후보 프레임도 앵커가 될 수 있다 — 포즈가 제일 좋을 수 있다."""
+ run_dir = direction_run
+ request = _request(run_dir)
+ _save_curation(run_dir, {"down_idle": {"selected": [0, 1]}},
+ anchors={"down": {"state": "down_idle", "index": 3}})
+ curation = load_curation(run_dir)
+ assert 3 in state_instances(curation, "down_idle", 4)
+ resolved = anchor_mod.resolve_anchor(request, curation, "down")
+ assert (resolved["index"], resolved["source"]) == (3, "picked")
+
+
+def test_picked_frame_that_vanished_fails_loud(direction_run: Path) -> None:
+ run_dir = direction_run
+ request = _request(run_dir)
+ _save_curation(run_dir, {"down_idle": {"deleted": [3], "selected": [0, 1, 2]}},
+ anchors={"down": {"state": "down_idle", "index": 3}})
+ with pytest.raises(SystemExit) as excinfo:
+ anchor_mod.resolve_anchor(request, load_curation(run_dir), "down")
+ assert "no longer exists" in str(excinfo.value)
+ # 뷰는 죽지 않고 이유를 보여준다
+ status = anchor_mod.anchor_status(run_dir, request, load_curation(run_dir), "down")
+ assert status["state"] is None and "no longer exists" in status["error"]
+
+
+def test_pick_from_another_direction_is_rejected(direction_run: Path) -> None:
+ run_dir = direction_run
+ request = _request(run_dir)
+ _save_curation(run_dir, {}, anchors={"down": {"state": "side_walk", "index": 0}})
+ with pytest.raises(SystemExit) as excinfo:
+ anchor_mod.resolve_anchor(request, load_curation(run_dir), "down")
+ assert "belongs to direction" in str(excinfo.value)
+
+
+# --- CLI ---------------------------------------------------------------------
+
+def test_cli_pick_then_clear_roundtrip(direction_run: Path) -> None:
+ run_dir = direction_run
+ assert anchor_mod.run(run_dir=run_dir, pick="down_idle#2") == 0
+ assert _pins(load_curation(run_dir)) == {"down": {"state": "down_idle", "index": 2}}
+ # 지정만으로 ref 도 갱신된다 (--direction 이 pick 에서 파생)
+ assert (run_dir / "references" / "anchors" / "down-anchor-x8.png").is_file()
+ assert anchor_mod.run(run_dir=run_dir, clear=True, direction="down") == 0
+ assert _pins(load_curation(run_dir)) == {}
+
+
+def test_cli_for_state_prints_the_identity_ref(direction_run: Path, capsys) -> None:
+ run_dir = direction_run
+ # 액션 행 = 방향 앵커 (실제로 구워진 파일)
+ assert anchor_mod.run(run_dir=run_dir, for_state="down_walk") == 0
+ printed = capsys.readouterr().out.strip()
+ assert printed == "references/anchors/down-anchor-x8.png"
+ assert (run_dir / printed).is_file()
+ # 앵커 행 자체 = base-source (앵커 이전 체인)
+ assert anchor_mod.run(run_dir=run_dir, for_state="down_idle") == 0
+ assert capsys.readouterr().out.strip() == "base-source.png"
+
+
+def test_cli_pick_preserves_existing_curation_rows(direction_run: Path) -> None:
+ """지정 쓰기가 사용자의 선택/편집을 덮지 않는다 (fresh 재독 → 갱신)."""
+ run_dir = direction_run
+ _save_curation(run_dir, {"down_idle": {"selected": [1, 2], "transforms": {"1": {"dx": 3}}}})
+ assert anchor_mod.run(run_dir=run_dir, pick="down_idle#1") == 0
+ curation = load_curation(run_dir)
+ assert curation["states"]["down_idle"]["selected"] == [1, 2]
+ assert curation["states"]["down_idle"]["transforms"]["1"]["dx"] == 3
+ assert _pins(curation)["down"] == {"state": "down_idle", "index": 1}
+
+
+# --- 소비자 정합 --------------------------------------------------------------
+
+def test_reroll_identity_ref_uses_the_picked_anchor(direction_run: Path) -> None:
+ """리롤이 붙이는 identity ref = 같은 앵커 진실 (reroll 안에 두 번째 규칙이 없다)."""
+ from sprite_gen.effects import reroll
+
+ run_dir = direction_run
+ request = _request(run_dir)
+ _save_curation(run_dir, {}, anchors={"down": {"state": "down_walk", "index": 1}})
+ ref = reroll.identity_ref(run_dir, "down_walk", request=request, quiet=True)
+ assert ref == run_dir / "references" / "anchors" / "down-anchor-x8.png"
+ baked = anchor_mod.anchor_image(run_dir, request, load_curation(run_dir), "down")[0]
+ with Image.open(ref) as written:
+ assert list(written.convert("RGBA").getdata()) == list(baked.convert("RGBA").getdata())
+
+
+def test_anchor_suffix_other_than_idle_is_honored(direction_run: Path) -> None:
+ """앵커 행 이름은 `anchor_suffix` 계약이 정한다 — `idle` 하드코딩 금지."""
+ run_dir = direction_run
+ request = _request(run_dir)
+ request["directions"]["anchor_suffix"] = "walk"
+ assert anchor_mod.anchor_state(request, "down") == "down_walk"
+ resolved = anchor_mod.resolve_anchor(request, load_curation(run_dir), "down")
+ assert resolved["state"] == "down_walk"
+ # 이제 앵커 행이 된 down_walk 는 base-source 로 생성된다 (자기 자신을 앵커로 붙이지 않는다)
+ assert anchor_mod.identity_ref(run_dir, "down_walk", request=request,
+ quiet=True).name == "base-source.png"
+
+
+def test_view_chip_is_a_live_bake_endpoint(direction_run: Path) -> None:
+ """앵커 칩 = `/api/anchor` 라이브 베이크 (파일 스냅샷이면 편집 직후 낡는다)."""
+ from sprite_gen.serve.serve_curation import build_run_state
+
+ run_dir = direction_run
+ _save_curation(run_dir, {"down_idle": {"deleted": [0], "selected": [1, 2, 3]}})
+ snapshot = build_run_state(run_dir)
+ walk = next(s for s in snapshot["states"] if s["name"] == "down_walk")
+ anchor_chip = next(r for r in walk["refs"] if r["role"] == "anchor")
+ assert anchor_chip["url"].startswith("/api/anchor?direction=down")
+ assert anchor_chip["name"] == "down_idle#1"
+ group = next(g for g in snapshot["directionGroups"] if g["direction"] == "down")
+ assert group["anchorFrame"] == {"state": "down_idle", "index": 1, "source": "default"}
+ assert group["anchorError"] is None
+ # 앵커 행 자체에는 앵커 칩이 붙지 않는다 (자기 자신이 앵커다)
+ idle = next(s for s in snapshot["states"] if s["name"] == "down_idle")
+ assert not [r for r in idle["refs"] if r["role"] == "anchor"]
+
+
+def test_api_anchor_serves_the_baked_png(direction_run: Path) -> None:
+ import threading
+ import urllib.request
+ from functools import partial
+ from http.server import ThreadingHTTPServer
+
+ from sprite_gen.serve.serve_curation import CurationHandler
+
+ run_dir = direction_run
+ _save_curation(run_dir, {}, anchors={"down": {"state": "down_idle", "index": 2}})
+ CurationHandler.run_dir = run_dir
+ CurationHandler.lang = "en"
+ srv = ThreadingHTTPServer(("127.0.0.1", 0), partial(CurationHandler))
+ threading.Thread(target=srv.serve_forever, daemon=True).start()
+ try:
+ with urllib.request.urlopen(
+ f"http://127.0.0.1:{srv.server_address[1]}/api/anchor?direction=down") as res:
+ assert res.status == 200
+ assert res.headers["Content-Type"] == "image/png"
+ assert res.headers["X-Anchor-Frame"] == "down_idle#2"
+ assert res.headers["X-Anchor-Source"] == "picked"
+ assert res.read()[:8] == b"\x89PNG\r\n\x1a\n"
+ finally:
+ srv.shutdown()
+
+
+def test_curation_post_without_anchors_key_keeps_the_pick(direction_run: Path) -> None:
+ """엔진(CLI)이 심은 지정은 그 키를 모르는 저장에 조용히 사라지지 않는다."""
+ import json as _json
+ import threading
+ import urllib.request
+ from functools import partial
+ from http.server import ThreadingHTTPServer
+
+ from sprite_gen.serve.serve_curation import CurationHandler
+
+ run_dir = direction_run
+ assert anchor_mod.run(run_dir=run_dir, pick="down_idle#2") == 0
+ CurationHandler.run_dir = run_dir
+ CurationHandler.lang = "en"
+ srv = ThreadingHTTPServer(("127.0.0.1", 0), partial(CurationHandler))
+ threading.Thread(target=srv.serve_forever, daemon=True).start()
+ port = srv.server_address[1]
+
+ def post(body: dict) -> int:
+ req = urllib.request.Request(f"http://127.0.0.1:{port}/api/curation",
+ data=_json.dumps(body).encode(), method="POST")
+ with urllib.request.urlopen(req) as res:
+ return res.status
+
+ try:
+ revision = _json.loads(
+ urllib.request.urlopen(f"http://127.0.0.1:{port}/api/run").read())["runRevision"]
+ # anchors 키가 없는 저장 → 이월
+ assert post({"version": 1, "kind": "sprite-gen-curation", "runRevision": revision,
+ "states": {"down_idle": {"selected": [0, 1]}}}) == 200
+ assert _pins(load_curation(run_dir))["down"] == {"state": "down_idle", "index": 2}
+ # 빈 anchors 를 명시로 실으면 해제 (뷰의 해제 동작)
+ revision = _json.loads(
+ urllib.request.urlopen(f"http://127.0.0.1:{port}/api/run").read())["runRevision"]
+ assert post({"version": 1, "kind": "sprite-gen-curation", "runRevision": revision,
+ "anchors": {}, "states": {"down_idle": {"selected": [0, 1]}}}) == 200
+ assert _pins(load_curation(run_dir)) == {}
+ assert "anchors" not in _json.loads(
+ (run_dir / "curation.json").read_text(encoding="utf-8"))
+ finally:
+ srv.shutdown()
diff --git a/tests/curate/test_curation_salvage_and_clones.py b/tests/curate/test_curation_salvage_and_clones.py
new file mode 100644
index 0000000..4744e32
--- /dev/null
+++ b/tests/curate/test_curation_salvage_and_clones.py
@@ -0,0 +1,211 @@
+# SPDX-License-Identifier: Apache-2.0
+"""행 단위 큐레이션 보존(salvage) + stale 백업 + 프레임 복제(clones) 계약.
+
+배경 회귀 (2026-07-15, 합성 회귀): 엔진 커밋마다 heal 이 전
+행을 재유도해 frames mtime 이 바뀌고, 런 전체 run_revision 지문이 어긋나 사용자의
+선택/보관함이 통째로 무시된 뒤 다음 autosave 가 기본값으로 영구 덮어썼다 ("계속
+부활"). 계약:
+
+- state_revision = 원료(raw/테이크, 임포트 행은 프레임 내용) 기반 세그먼트 지문 —
+ frames 캐시 mtime 과 엔진 리비전은 지문에 들어가지 않는다.
+- 같은 raw 의 재추출(엔진 업그레이드 heal)은 행 큐레이션을 유지한다.
+- raw 리롤은 그 행만 드롭한다. 드롭은 **로드 판정**이라 그 시점엔 파일이 그대로고
+ (조회는 런에 쓰지 않는다), 원문 전체가 curation.stale-<hash>.json 으로 보존되는 것은
+ 실제로 덮는 writer (`write_curation_atomic`) 한 곳뿐이다.
+- 스탬프 없는 레거시 사이드카는 세대가 어긋나면 전량 드롭 (증명 없는 선택을 새 프레임에
+ 적용하지 않는다) — 백업은 역시 덮는 시점에 난다.
+- clones: 복제 인스턴스는 사이드카 소유(파생 캐시에 파일을 만들지 않음), 자기
+ 변형을 갖고, 굽기 때 원본 프레임 파일을 읽는다.
+"""
+
+import json
+from pathlib import Path
+
+from PIL import Image
+
+from conftest import run_script
+from sprite_gen.curate.curation import (
+ load_curation,
+ load_curation_report,
+ run_revision,
+ source_frame_index,
+ stamp_curation,
+ state_plan,
+ state_revision,
+ write_curation_atomic,
+)
+
+
+def _stale_backups(run: Path) -> list[Path]:
+ return sorted(run.glob("curation.stale-*.json"))
+
+
+def _extract(run: Path) -> None:
+ result = run_script("extract_sprite_row_frames.py", "--run-dir", str(run))
+ assert result.returncode == 0, result.stdout + result.stderr
+
+
+def _write_stamped(run: Path, states: dict) -> dict:
+ payload = stamp_curation(run, {"version": 1, "kind": "sprite-gen-curation", "states": states})
+ (run / "curation.json").write_text(json.dumps(payload), encoding="utf-8")
+ return payload
+
+
+def _reroll_raw(run: Path, state: str) -> None:
+ """리롤 시뮬레이션 — raw 내용을 실제로 바꾼다 (지문은 내용 기반)."""
+ path = run / "raw" / f"{state}.png"
+ with Image.open(path) as im:
+ raw = im.convert("RGBA")
+ raw.putpixel((0, 0), (1, 2, 3, 255))
+ raw.save(path)
+
+
+def test_reextract_same_raw_keeps_curation(fixture_run_dir: Path) -> None:
+ """엔진 업그레이드 heal 시나리오: 같은 raw 재추출 → 선택/보관함 유지."""
+ run = fixture_run_dir
+ _extract(run)
+ stamped = _write_stamped(run, {
+ "idle": {"selected": [2, 0], "deleted": [3], "transforms": {"0": {"dx": 4}}},
+ "walk": {"selected": [1]},
+ })
+ assert stamped["states"]["idle"]["revision"], "행 스탬프가 찍혀야 한다"
+
+ old_run_rev = run_revision(run)
+ _extract(run) # frames 재작성 (mtime 변경) — raw 는 그대로
+ assert run_revision(run) != old_run_rev, "런 전체 지문은 어긋나야 salvage 경로를 탄다"
+
+ doc, report = load_curation_report(run)
+ assert report["dropped"] == []
+ assert _stale_backups(run) == []
+ assert doc is not None
+ assert doc["states"]["idle"]["selected"] == [2, 0]
+ assert doc["states"]["idle"]["deleted"] == [3]
+ assert doc["states"]["walk"]["selected"] == [1]
+
+
+def test_reroll_drops_only_that_state_and_the_save_backs_it_up(fixture_run_dir: Path) -> None:
+ """드롭은 로드 판정, 백업은 덮는 writer — 두 책임이 나뉘어 있다.
+
+ 예전엔 `load_curation_report` 가 드롭을 판정하면서 그 자리에서 백업 파일을 썼다. 조회가
+ 런 디렉터리에 파일을 만든다는 뜻이고, 그건 이 플랜이 request 로더에서 잡은 것과 같은
+ 계열이다. 드롭 시점엔 아직 잃은 것이 없다 (`curation.json` 은 디스크에 그대로다) — 실제로
+ 원문이 사라지는 순간은 저장 한 번뿐이고, 백업은 거기서 난다."""
+ run = fixture_run_dir
+ _extract(run)
+ _write_stamped(run, {
+ "idle": {"selected": [2, 0]},
+ "walk": {"selected": [1]},
+ })
+ original_text = (run / "curation.json").read_text(encoding="utf-8")
+
+ _reroll_raw(run, "walk")
+ _extract(run)
+
+ doc, report = load_curation_report(run)
+ assert report["dropped"] == ["walk"]
+ # 조회는 아무것도 쓰지 않는다 — 백업 파일도, 사이드카 자체도
+ assert _stale_backups(run) == []
+ assert (run / "curation.json").read_text(encoding="utf-8") == original_text
+ assert doc is not None and "walk" not in doc["states"]
+ assert doc["states"]["idle"]["selected"] == [2, 0]
+ # load_curation 은 같은 게이트의 thin wrapper
+ assert "walk" not in (load_curation(run) or {}).get("states", {})
+
+ # 뷰가 구제된 문서를 저장하는 순간 = 원문이 덮이는 순간. 백업은 여기서 난다.
+ backup = write_curation_atomic(run, doc)
+ assert backup and (run / backup).is_file()
+ assert (run / backup).read_text(encoding="utf-8") == original_text
+
+
+def test_legacy_unstamped_sidecar_drops_all_and_the_save_backs_it_up(fixture_run_dir: Path) -> None:
+ run = fixture_run_dir
+ _extract(run)
+ legacy = {"version": 1, "kind": "sprite-gen-curation",
+ "run_revision": run_revision(run),
+ "states": {"idle": {"selected": [1]}}}
+ (run / "curation.json").write_text(json.dumps(legacy), encoding="utf-8")
+ original_text = (run / "curation.json").read_text(encoding="utf-8")
+ # 같은 세대인 동안은 fast path 로 그대로 적용된다
+ doc, report = load_curation_report(run)
+ assert doc is not None and report["dropped"] == []
+
+ _extract(run) # 세대가 어긋나면 스탬프 없는 행은 검증 불가 → 드롭
+ doc, report = load_curation_report(run)
+ assert doc is None
+ assert report["dropped"] == ["idle"]
+ assert _stale_backups(run) == [] # 드롭 판정은 쓰지 않는다
+
+ # 전량 드롭 뒤 뷰가 기본값을 저장하면 그때 원문이 덮이고, 그때 백업된다
+ backup = write_curation_atomic(run, {"version": 1, "kind": "sprite-gen-curation", "states": {}})
+ assert backup and (run / backup).read_text(encoding="utf-8") == original_text
+
+
+def test_take_append_prefix_rule(tmp_path: Path) -> None:
+ """테이크가 뒤에 추가돼도(현재 세그먼트의 접두) 기존 행 큐레이션은 유효하다.
+ takes 는 pixel_perfect 계약이므로 pp 런을 test_takes_heal 과 같은 방식으로 만든다."""
+ from test_takes_heal import _build_run, _strip
+
+ run = _build_run(tmp_path)
+ _extract(run)
+ stamped = _write_stamped(run, {"walk": {"selected": [0]}})
+ stored = stamped["states"]["walk"]["revision"]
+ assert len(stored) == 1
+
+ # 테이크 추가: request 선언 + 테이크 raw 배치 후 재추출
+ request = json.loads((run / "sprite-request.json").read_text(encoding="utf-8"))
+ request["states"]["walk"]["takes"] = [{"label": "alt", "frames": 2}]
+ (run / "sprite-request.json").write_text(json.dumps(request), encoding="utf-8")
+ takes_dir = run / "raw" / "walk.takes"
+ takes_dir.mkdir()
+ _strip(2, seed=11).save(takes_dir / "alt.png")
+ _extract(run)
+
+ current = state_revision(run, "walk")
+ assert current is not None and len(current) == 2
+ assert current[:len(stored)] == stored, "기존 세그먼트 지문은 접두로 보존"
+
+ doc, report = load_curation_report(run)
+ assert report["dropped"] == []
+ assert doc is not None and doc["states"]["walk"]["selected"] == [0]
+
+
+def test_clone_instances_plan_and_bake(fixture_run_dir: Path) -> None:
+ run = fixture_run_dir
+ _extract(run)
+ # idle 물리 4프레임(0..3) + 복제 7→0 (자기만의 flipX 변형), 시퀀스 = [0, 7, 1]
+ _write_stamped(run, {
+ "idle": {
+ "selected": [0, 7, 1],
+ "clones": {"7": 0},
+ "transforms": {"7": {"flipX": 1}},
+ },
+ })
+
+ curation = load_curation(run)
+ ordered, transforms = state_plan(curation, "idle", 4)
+ assert ordered == [0, 7, 1]
+ assert transforms[7]["flipX"] == 1
+ assert source_frame_index(curation, "idle", 7, 4) == 0
+ assert source_frame_index(curation, "idle", 1, 4) == 1
+ # 원본 범위와 겹치거나 소스가 물리 범위 밖인 손상 항목은 무시된다
+ corrupt = {"states": {"idle": {"selected": [0, 2], "clones": {"2": 0, "9": 5}}}}
+ assert state_plan(corrupt, "idle", 4)[0] == [0, 2]
+ assert source_frame_index(corrupt, "idle", 2, 4) == 2
+
+ compose = run_script("compose_sprite_atlas.py", "--run-dir", str(run))
+ assert compose.returncode == 0, compose.stdout + compose.stderr
+ manifest = json.loads((run / "manifest.json").read_text(encoding="utf-8"))
+ assert len(manifest["frame_layout"]["rows"]["idle"]) == 3
+ assert manifest["animation"]["rows"]["idle"]["frames"] == 3
+
+ # 복제 셀(2번째)은 원본 셀(1번째)의 좌우 반전과 일치해야 한다 — 같은 원본을
+ # 읽고 자기 변형만 적용했다는 증명
+ cell = json.loads((run / "sprite-request.json").read_text(encoding="utf-8"))["cell"]
+ cw, ch = int(cell["width"]), int(cell["height"])
+ row_y = 0 # idle 은 첫 행
+ with Image.open(run / "sprite-sheet-alpha.png") as atlas:
+ rgba = atlas.convert("RGBA")
+ source_cell = rgba.crop((0, row_y, cw, row_y + ch))
+ clone_cell = rgba.crop((cw, row_y, cw * 2, row_y + ch))
+ from PIL import ImageOps
+ assert list(clone_cell.getdata()) == list(ImageOps.mirror(source_cell).getdata())
diff --git a/tests/curate/test_directions.py b/tests/curate/test_directions.py
new file mode 100644
index 0000000..c484cf2
--- /dev/null
+++ b/tests/curate/test_directions.py
@@ -0,0 +1,92 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Direction contract: base(=down idle) -> per-direction anchors -> rows.
+
+`--directions` runs scaffold the directional-anchor workflow structurally:
+missing <dir>_idle anchors are synthesized, prompts lock facing per direction
+(anchor rows derive from the base, action rows from their direction anchor),
+mirrored directions are recorded as skipped-by-contract, and the generation
+chain is written to references/generation-plan.json.
+"""
+
+import json
+from pathlib import Path
+
+import pytest
+
+from conftest import run_script
+
+
+def _prepare(tmp_path: Path, *extra: str):
+ out_dir = tmp_path / "run"
+ result = run_script(
+ "prepare_sprite_run.py",
+ "--out-dir", str(out_dir),
+ "--character-id", "dirbot",
+ "--request-json", json.dumps({
+ "states": {
+ "down_walk": {"frames": 6, "fps": 8, "loop": True, "action": "walking toward the viewer"},
+ "side_walk": {"frames": 6, "fps": 8, "loop": True, "action": "walking in side view"},
+ "up_walk": {"frames": 6, "fps": 8, "loop": True, "action": "walking away from the viewer"},
+ },
+ }),
+ *extra,
+ )
+ return out_dir, result
+
+
+def test_directions_scaffold_anchors_and_plan(tmp_path: Path) -> None:
+ out_dir, result = _prepare(tmp_path, "--directions", "down,side,up", "--mirror", "left=side")
+ assert result.returncode == 0, result.stdout + result.stderr
+
+ request = json.loads((out_dir / "sprite-request.json").read_text(encoding="utf-8"))
+ assert request["directions"] == {"set": ["down", "side", "up"], "mirror": {"left": "side"}, "anchor_suffix": "idle"}
+ # 방향 앵커가 합성되어 states 에 존재하고, 택소노미 경로(<dir>/<pose>)에 가이드/프롬프트 생성
+ assert request["layout"] == "taxonomy/v1"
+ for anchor in ("down_idle", "side_idle", "up_idle"):
+ assert anchor in request["states"], anchor
+ d = anchor.split("_", 1)[0]
+ assert (out_dir / "prompts" / d / "idle.txt").is_file()
+ assert (out_dir / "references" / "layout-guides" / d / "idle.png").is_file()
+
+ # 프롬프트 방향 잠금: 앵커는 base 기반 + canonical 문구, 행은 앵커 기반 문구
+ anchor_prompt = (out_dir / "prompts" / "up" / "idle.txt").read_text(encoding="utf-8")
+ assert "CANONICAL DIRECTION ANCHOR" in anchor_prompt
+ assert "facing away from the viewer" in anchor_prompt
+ row_prompt_text = (out_dir / "prompts" / "side" / "walk.txt").read_text(encoding="utf-8")
+ assert "accepted direction anchor" in row_prompt_text
+ assert "pure side profile view facing camera-right" in row_prompt_text
+
+ plan = json.loads((out_dir / "references" / "generation-plan.json").read_text(encoding="utf-8"))
+ assert plan["kind"] == "sprite-gen-generation-plan"
+ stage1, stage2 = plan["order"][0], plan["order"][1]
+ assert [i["state"] for i in stage1["items"]] == ["down_idle", "side_idle", "up_idle"]
+ assert all(i["role"] == "direction-anchor" and "base-source.*" in i["refs"] for i in stage1["items"])
+ walk_item = next(i for i in stage2["items"] if i["state"] == "side_walk")
+ # 액션 행 identity = 결정론 앵커 ref 경로 + 그걸 굽는 커맨드 (산문 지시 금지 —
+ # 워커가 크롭 위치를 판단하면 편집 전 모습이 identity 로 번진다)
+ assert walk_item["refs"][0] == "references/anchors/side-anchor-x8.png"
+ assert walk_item["refs"][1] == "references/layout-guides/side/walk.png"
+ assert walk_item["materialize"] == ("python3 -m sprite_gen.cli anchor --run-dir . "
+ "--direction side") # 기계 소비 필드는 어디서나 도는 형태
+ # 미러 방향은 생성 생략이 계약으로 기록된다 (조용한 누락 금지)
+ assert plan["mirrored_directions"][0]["direction"] == "left"
+ assert plan["mirrored_directions"][0]["mirror_of"] == "side"
+
+
+def test_directions_reject_unprefixed_state(tmp_path: Path) -> None:
+ out_dir = tmp_path / "run"
+ result = run_script(
+ "prepare_sprite_run.py",
+ "--out-dir", str(out_dir),
+ "--character-id", "dirbot",
+ "--request-json", json.dumps({"states": {"wave": {"frames": 4, "fps": 6, "loop": False, "action": "wave"}}}),
+ "--directions", "down,side",
+ )
+ assert result.returncode != 0
+ assert "does not start with a declared direction prefix" in (result.stdout + result.stderr)
+
+
+def test_directions_mirror_source_must_be_generated(tmp_path: Path) -> None:
+ out_dir, result = _prepare(tmp_path, "--directions", "down,side,up", "--mirror", "left=right")
+ assert result.returncode != 0
+ assert "not in directions.set" in (result.stdout + result.stderr)
diff --git a/tests/curate/test_frame_variant.py b/tests/curate/test_frame_variant.py
new file mode 100644
index 0000000..199f21e
--- /dev/null
+++ b/tests/curate/test_frame_variant.py
@@ -0,0 +1,89 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Per-state pixel-perfect variant resolution (curation.frame_variant) + mixed bake.
+
+The curator has a per-row pixel-perfect toggle (states.<state>.pixel_perfect) and a
+toggle-all that writes the run-wide default (top-level pixel_perfect). frame_variant
+is the single resolver every consumer (atlas/GIF/PNG export/cycle) goes through:
+per-state override > run-wide default > pixel.
+"""
+
+import json
+from pathlib import Path
+
+from PIL import Image
+
+from conftest import run_script
+from sprite_gen.curate.curation import frame_variant, run_revision
+
+
+def test_frame_variant_resolution_order() -> None:
+ # absent sidecar -> pixel, with or without a state
+ assert frame_variant(None) == "pixel"
+ assert frame_variant(None, "idle") == "pixel"
+
+ # run-wide default only
+ assert frame_variant({"pixel_unfake": False, "states": {}}) == "plain"
+ assert frame_variant({"pixel_unfake": False, "states": {}}, "idle") == "plain"
+ assert frame_variant({"pixel_unfake": True, "states": {}}, "idle") == "pixel"
+
+ # per-state override beats the run-wide default, both directions
+ mixed = {
+ "pixel_unfake": False,
+ "states": {"idle": {"pixel_unfake": True}, "walk": {}},
+ }
+ assert frame_variant(mixed, "idle") == "pixel" # override wins over global false
+ assert frame_variant(mixed, "walk") == "plain" # no override -> global
+ assert frame_variant(mixed, "unknown") == "plain" # unknown state -> global
+ assert frame_variant(mixed) == "plain" # stateless call -> global only
+
+ over_off = {"states": {"idle": {"pixel_unfake": False}}}
+ assert frame_variant(over_off, "idle") == "plain" # override wins over absent global
+ assert frame_variant(over_off, "walk") == "pixel"
+
+ # a non-bool per-state value is ignored (hand-edited sidecar), not truthy-coerced
+ corrupt = {"states": {"idle": {"pixel_unfake": "yes"}}}
+ assert frame_variant(corrupt, "idle") == "pixel"
+
+
+def test_compose_bakes_mixed_variants_per_state(fixture_run_dir: Path) -> None:
+ """One state toggled off bakes its .plain.png twin while the others bake the
+ canonical frames; the manifest records per-row frame_variant + a 'mixed' summary."""
+ run = fixture_run_dir
+ assert run_script("extract_sprite_row_frames.py", "--run-dir", str(run)).returncode == 0
+
+ request = json.loads((run / "sprite-request.json").read_text(encoding="utf-8"))
+ states = list(request["states"])
+ assert len(states) >= 2
+ plain_state, pixel_state = states[0], states[1]
+
+ # manufacture a distinguishable plain twin for every frame of the toggled-off state
+ # (a solid magenta-ish fill: trivially detectable in the baked atlas row)
+ cell = request["cell"]
+ cw, ch = int(cell.get("width", cell.get("size", 0))), int(cell.get("height", cell.get("size", 0)))
+ marker = (250, 10, 250, 255)
+ count = int(request["states"][plain_state]["frames"])
+ for index in range(count):
+ Image.new("RGBA", (cw, ch), marker).save(run / "frames" / plain_state / f"frame-{index}.plain.png")
+
+ sidecar = {
+ "version": 1,
+ "kind": "sprite-gen-curation",
+ "run_revision": run_revision(run), # .plain.png twins do not shift the revision
+ "states": {plain_state: {"pixel_unfake": False}},
+ }
+ (run / "curation.json").write_text(json.dumps(sidecar), encoding="utf-8")
+
+ compose = run_script("compose_sprite_atlas.py", "--run-dir", str(run))
+ assert compose.returncode == 0, compose.stdout + compose.stderr
+
+ manifest = json.loads((run / "manifest.json").read_text(encoding="utf-8"))
+ assert manifest["frame_variant"] == "mixed"
+ assert manifest["animation"]["rows"][plain_state]["frame_variant"] == "plain"
+ assert manifest["animation"]["rows"][pixel_state]["frame_variant"] == "pixel"
+
+ # the plain row actually baked the marker twin; the pixel row did not
+ row = states.index(plain_state)
+ with Image.open(run / "sprite-sheet-alpha.png") as atlas:
+ assert atlas.convert("RGBA").getpixel((cw // 2, row * ch + ch // 2)) == marker
+ other_row = states.index(pixel_state)
+ assert atlas.convert("RGBA").getpixel((cw // 2, other_row * ch + ch // 2)) != marker
diff --git a/tests/curate/test_logical_height_contract.py b/tests/curate/test_logical_height_contract.py
new file mode 100644
index 0000000..bdc16d7
--- /dev/null
+++ b/tests/curate/test_logical_height_contract.py
@@ -0,0 +1,171 @@
+# SPDX-License-Identifier: Apache-2.0
+"""`fit.logical_height` 계약 — 선언값이 아니라 파생 격자가 진실이다.
+
+회귀 (2026-07-25, 합성 회귀 hero synthetic fixtures): `conform`(눌림)이 제거된 뒤
+`logical_height: 48` 은 셀 64 에서 아무 픽셀도 바꾸지 않는 값이 됐다 (`64//48 == 1`
+== `64//64`). 그런데 남아서 두 가지를 오염시켰다:
+
+1. 큐레이션 행 지문(`state_revision`)이 **선언값**을 물고 있어서, 그 죽은 값을 지우기만
+ 해도 프레임이 바이트 동일한데 14행 큐레이션이 통째로 드롭됐다.
+2. 웹뷰 헤더가 "48px" 라고 거짓 라벨을 띄웠다 (실제 논리 높이는 64).
+
+계약:
+- `effective_logical_height` = 셀 높이 / 파생 배율. 정수 격자가 반올림한 결과가 진실.
+- 행 지문은 파생 배율만 본다 — 출력이 같은 선언 편집은 큐레이션을 살린다.
+- 선언이 적용되지 못하면 추출이 경고로 관측시킨다 (조용히 무시하지 않는다).
+- 배율 식은 한 곳(`pixel_snap_scale`)만 소유한다 — extract·웹뷰가 손으로 복제하지 않는다.
+"""
+from __future__ import annotations
+
+import json
+import random
+import re
+from pathlib import Path
+
+from PIL import Image
+
+import sprite_gen.frames.extract as extract_module
+from sprite_gen.curate.curation import (
+ effective_logical_height,
+ pixel_snap_scale,
+ state_revision,
+)
+
+REPO_ROOT = Path(__file__).resolve().parents[2]
+MAGENTA = (255, 0, 255)
+CELL = 64
+
+
+def _logical_art(width: int, height: int, seed: int) -> Image.Image:
+ rng = random.Random(seed)
+ art = Image.new("RGB", (width, height), MAGENTA)
+ for y in range(height):
+ for x in range(width):
+ if rng.random() < 0.55:
+ art.putpixel((x, y), (rng.randrange(30, 220), rng.randrange(30, 220),
+ rng.randrange(30, 220)))
+ return art
+
+
+def _build_pp_run(root: Path, logical_height: int | None) -> Path:
+ """셀 64 픽셀퍼펙트 런 (정수 피치로 확대한 논리 아트 2프레임)."""
+ run_dir = root / "run"
+ (run_dir / "raw").mkdir(parents=True)
+ pitch = 8
+ frame = _logical_art(20, 36, seed=11).resize((20 * pitch, 36 * pitch),
+ Image.Resampling.NEAREST)
+ gap = 40
+ strip = Image.new("RGB", (frame.width * 2 + gap * 3, frame.height + gap * 2), MAGENTA)
+ strip.paste(frame, (gap, gap))
+ strip.paste(frame, (frame.width + gap * 2, gap))
+ strip.save(run_dir / "raw" / "walk.png")
+ fit: dict = {"pixel_unfake": True}
+ if logical_height is not None:
+ fit["logical_height"] = logical_height
+ request = {
+ "version": 1, "kind": "sprite-gen-request", "engine": "component-row",
+ "character": {"id": "lhbot", "description": "logical height fixture", "base_image": None},
+ "cell": {"shape": "square", "width": CELL, "height": CELL, "size": CELL,
+ "safe_margin_x": 6, "safe_margin_y": 6, "safe_margin": 6},
+ "chroma_key": {"name": "magenta", "hex": "#FF00FF", "rgb": [255, 0, 255],
+ "selection": "fallback"},
+ "states": {"walk": {"frames": 2, "fps": 8, "loop": True, "action": "synthetic"}},
+ "fit": fit,
+ }
+ (run_dir / "sprite-request.json").write_text(json.dumps(request, ensure_ascii=False), encoding="utf-8")
+ return run_dir
+
+
+def _set_fit(run_dir: Path, fit: dict) -> None:
+ path = run_dir / "sprite-request.json"
+ request = json.loads(path.read_text(encoding="utf-8"))
+ request["fit"] = fit
+ path.write_text(json.dumps(request, ensure_ascii=False), encoding="utf-8")
+
+
+def _request(cell: int, **fit) -> dict:
+ return {
+ "cell": {"shape": "square", "size": cell, "width": cell, "height": cell,
+ "safe_margin": 6, "safe_margin_x": 6, "safe_margin_y": 6},
+ "fit": fit,
+ "states": {"idle": {"frames": 4, "fps": 4}},
+ }
+
+
+def test_declaration_that_the_integer_grid_rounds_away_reports_the_effective_height():
+ """셀 64 + 선언 48 = 배율 1 = 유효 논리 높이 64 (선언은 무효)."""
+ assert pixel_snap_scale(_request(64, pixel_unfake=True, logical_height=48)) == 1
+ assert effective_logical_height(_request(64, pixel_unfake=True, logical_height=48)) == 64
+ # 생략 = 셀과 1:1 (권장 기본값)
+ assert effective_logical_height(_request(64, pixel_unfake=True)) == 64
+
+
+def test_a_real_declaration_still_scales():
+ """약수 선언은 그대로 살아있다 — 청키 룩은 기능이지 레거시가 아니다."""
+ assert pixel_snap_scale(_request(64, pixel_unfake=True, logical_height=32)) == 2
+ assert effective_logical_height(_request(64, pixel_unfake=True, logical_height=32)) == 32
+ assert pixel_snap_scale(_request(96, pixel_unfake=True, logical_height=32)) == 3
+ assert effective_logical_height(_request(96, pixel_unfake=True, logical_height=32)) == 32
+
+
+def test_legacy_run_without_pixel_perfect_has_no_logical_grid():
+ assert pixel_snap_scale(_request(64)) is None
+ assert effective_logical_height(_request(64)) is None
+
+
+def test_row_fingerprint_survives_removing_a_dead_declaration(tmp_path: Path):
+ """핵심 회귀: 출력이 같은 선언 편집은 행 지문을 바꾸지 않는다.
+
+ 이게 깨지면 죽은 값을 지우는 순간 큐레이션이 전량 드롭된다 (회귀 synthetic_fixture_b:
+ 프레임이 바이트 동일했는데도 14행이 통째로 날아갔다)."""
+ run = _build_pp_run(tmp_path, logical_height=48) # 셀 64 → 배율 1 → 선언 무효
+ assert extract_module.run(run_dir=run) == 0
+ frames_before = {p.name: p.read_bytes()
+ for p in sorted((run / "frames" / "walk").glob("frame-*.png"))}
+ with_dead_value = state_revision(run, "walk")
+ assert with_dead_value, "행 지문을 계산하지 못했다 — 픽스처 전제가 깨졌다"
+
+ _set_fit(run, {"pixel_unfake": True})
+ assert state_revision(run, "walk") == with_dead_value, (
+ "무효 선언을 지웠을 뿐인데 행 지문이 바뀌었다 — 큐레이션이 통째로 드롭된다")
+
+ # 전제 확인: 그 편집으로 프레임이 실제로 안 바뀐다 (지문 유지가 정당한 이유)
+ assert extract_module.run(run_dir=run) == 0
+ frames_after = {p.name: p.read_bytes()
+ for p in sorted((run / "frames" / "walk").glob("frame-*.png"))}
+ assert frames_after == frames_before, "전제 붕괴: 선언 제거가 픽셀을 바꿨다"
+
+ # 진짜로 격자를 바꾸는 선언은 지문을 바꿔야 한다 (검증이 무력화되면 안 된다)
+ _set_fit(run, {"pixel_unfake": True, "logical_height": CELL // 2})
+ assert state_revision(run, "walk") != with_dead_value, (
+ "배율이 실제로 바뀌는 선언인데 지문이 그대로다 — 낡은 선택이 새 프레임에 적용된다")
+
+
+def test_unhonored_declaration_is_reported_as_a_warning(tmp_path: Path):
+ """조용히 무시하지 않는다 — 요청에 남은 죽은 값은 경고로 보인다 (원칙 6)."""
+ run = _build_pp_run(tmp_path, logical_height=48)
+ assert extract_module.run(run_dir=run) == 0
+ manifest = json.loads((run / "frames" / "frames-manifest.json").read_text(encoding="utf-8"))
+ warnings = " ".join(manifest.get("warnings") or [])
+ assert "logical_height" in warnings and "not applied as declared" in warnings, (
+ f"무효 선언이 관측되지 않았다: {manifest.get('warnings')}")
+
+ # 유효한 선언은 경고하지 않는다 (경고가 노이즈가 되면 아무도 안 본다)
+ quiet = _build_pp_run(tmp_path / "quiet", logical_height=CELL // 2)
+ assert extract_module.run(run_dir=quiet) == 0
+ quiet_manifest = json.loads(
+ (quiet / "frames" / "frames-manifest.json").read_text(encoding="utf-8"))
+ assert not any("not applied as declared" in w for w in (quiet_manifest.get("warnings") or [])), (
+ f"유효한 선언에 경고가 붙었다: {quiet_manifest.get('warnings')}")
+
+
+def test_scale_formula_has_a_single_owner():
+ """extract·웹뷰가 배율 식을 손으로 복제하지 않는다 (원칙 1).
+
+ 복제본은 실제로 갈렸다 — 웹뷰 사본에는 usable-height 클램프 분기가 없었다."""
+ formula = re.compile(r"cell(_state\[.height.\]|_height)\s*//\s*max\(1,\s*logical_height")
+ for rel in ("sprite_gen/frames/extract.py", "sprite_gen/serve/serve_curation.py"):
+ source = (REPO_ROOT / rel).read_text(encoding="utf-8")
+ assert not formula.search(source), (
+ f"{rel} 가 배율 식을 다시 유도한다 — pixel_snap_scale 을 호출해야 한다")
+ assert "pixel_snap_scale" in source, f"{rel} 가 배율 SSoT 를 쓰지 않는다"
diff --git a/tests/curate/test_pixel_snap.py b/tests/curate/test_pixel_snap.py
new file mode 100644
index 0000000..f48b711
--- /dev/null
+++ b/tests/curate/test_pixel_snap.py
@@ -0,0 +1,323 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Pixel-perfect twins share the pp footprint + curated transforms re-snap to the grid.
+
+1. plain/orig twins are fitted into the pixel-perfect frame's content bbox, so the
+ curator's toggle compares pixel quality at the same size (no size jump).
+2. apply_transform(snap_scale=s) re-quantizes a curated move/rotate onto the fixed
+ logical grid — a pixel-variant bake can never produce off-grid smear.
+"""
+
+import json
+import random
+
+from PIL import Image
+
+import sprite_gen.frames.extract as extract_module
+from sprite_gen.curate.curation import apply_transform, pixel_snap_scale
+
+MAGENTA = (255, 0, 255)
+
+
+def _logical_art(width, height, seed):
+ rng = random.Random(seed)
+ art = Image.new("RGB", (width, height), MAGENTA)
+ for y in range(height):
+ for x in range(width):
+ if rng.random() < 0.55:
+ art.putpixel((x, y), (rng.randrange(30, 220), rng.randrange(30, 220), rng.randrange(30, 220)))
+ return art
+
+
+def _build_pp_run(root):
+ """2-frame pixel-perfect fixture: logical art upscaled by an integer pitch."""
+ run_dir = root / "run"
+ (run_dir / "raw").mkdir(parents=True)
+ pitch = 8
+ frame = _logical_art(20, 36, seed=7).resize((20 * pitch, 36 * pitch), Image.Resampling.NEAREST)
+ gap = 40
+ strip = Image.new("RGB", (frame.width * 2 + gap * 3, frame.height + gap * 2), MAGENTA)
+ strip.paste(frame, (gap, gap))
+ strip.paste(frame, (frame.width + gap * 2, gap))
+ strip.save(run_dir / "raw" / "walk.png")
+ request = {
+ "version": 1,
+ "kind": "sprite-gen-request",
+ "engine": "component-row",
+ "character": {"id": "snapbot", "description": "pixel snap fixture", "base_image": None},
+ "cell": {"shape": "square", "width": 96, "height": 96, "safe_margin_x": 8, "safe_margin_y": 8, "size": 96, "safe_margin": 8},
+ "chroma_key": {"name": "magenta", "hex": "#FF00FF", "rgb": [255, 0, 255], "selection": "fallback"},
+ "states": {"walk": {"frames": 2, "fps": 8, "loop": True, "action": "synthetic snap fixture"}},
+ "fit": {"pixel_unfake": True, "logical_height": 48},
+ }
+ (run_dir / "sprite-request.json").write_text(json.dumps(request, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
+ return run_dir
+
+
+def _conform_request(run_dir, conform):
+ """cell 48 (pp_scale=1, cap 42) + logical_height 30 < art's native 36 logical."""
+ import json as _json
+ request = _json.loads((run_dir / "sprite-request.json").read_text(encoding="utf-8"))
+ request["cell"] = {"shape": "square", "width": 48, "height": 48,
+ "safe_margin_x": 6, "safe_margin_y": 6, "size": 48, "safe_margin": 6}
+ request["fit"]["logical_height"] = 30
+ if conform is not None:
+ request["fit"]["conform"] = conform
+ (run_dir / "sprite-request.json").write_text(_json.dumps(request), encoding="utf-8")
+
+
+def _walk_frame0_height(run_dir) -> int:
+ im = Image.open(run_dir / "frames" / "walk" / "frame-0.png").convert("RGBA")
+ bb = im.getchannel("A").getbbox()
+ return bb[3] - bb[1]
+
+
+def test_default_keeps_native_logical_size(tmp_path) -> None:
+ """The output keeps the snapped native logical size (36) even though
+ logical_height is 30 — only the physical cap (42) is enforced.
+
+ There is no contract squeeze to opt into: `fit.conform` was removed
+ (maintainer 2026-07-14/17) and declaring it now fails loudly — see
+ `test_conform_flag_rejected` in this file."""
+ run_dir = _build_pp_run(tmp_path)
+ _conform_request(run_dir, conform=None)
+ assert extract_module.run(run_dir=run_dir) == 0
+ height = _walk_frame0_height(run_dir)
+ assert height > 30, f"native size squeezed by default: {height}"
+def test_pixel_snap_scale_resolution() -> None:
+ assert pixel_snap_scale({"cell": {"size": 64}}) is None # no fit
+ assert pixel_snap_scale({"cell": {"size": 64}, "fit": {"resample": "kcentroid"}}) is None
+ base = {"cell": {"width": 64, "height": 64, "safe_margin_x": 6, "safe_margin_y": 6}}
+ assert pixel_snap_scale({**base, "fit": {"pixel_unfake": True, "logical_height": 48}}) == 1
+ assert pixel_snap_scale({**base, "fit": {"pixel_unfake": True, "logical_height": 32}}) == 2
+ assert pixel_snap_scale({**base, "fit": {"pixel_unfake": True}}) == 1 # logical = cell
+
+
+def _blocks_uniform(image: Image.Image, scale: int) -> bool:
+ px = image.load()
+ for by in range(image.height // scale):
+ for bx in range(image.width // scale):
+ first = px[bx * scale, by * scale]
+ for dy in range(scale):
+ for dx in range(scale):
+ if px[bx * scale + dx, by * scale + dy] != first:
+ return False
+ return True
+
+
+def test_apply_transform_snap_keeps_grid() -> None:
+ """A fractional move + rotation on a 2px-block frame stays block-uniform when snapped."""
+ scale = 2
+ cell = (64, 64)
+ frame = Image.new("RGBA", cell, (0, 0, 0, 0))
+ art = _logical_art(20, 24, seed=3).convert("RGBA").resize((40, 48), Image.Resampling.NEAREST)
+ frame.alpha_composite(art, (12, 10))
+ assert _blocks_uniform(frame, scale)
+
+ moved = apply_transform(frame, {"dx": 0.7, "dy": -1.3, "rotate": 9.0, "scale": 1.05}, cell, snap_scale=scale)
+ assert moved.size == frame.size
+ assert moved.getbbox() is not None
+ assert _blocks_uniform(moved, scale), "snapped bake must stay on the logical grid"
+
+ smeared = apply_transform(frame, {"dx": 0.7, "dy": -1.3, "rotate": 9.0, "scale": 1.05}, cell)
+ assert not _blocks_uniform(smeared, scale), "unsnapped BICUBIC control should break blocks"
+
+
+def test_twins_share_pixel_perfect_footprint(tmp_path) -> None:
+ run_dir = _build_pp_run(tmp_path)
+ assert extract_module.run(run_dir=run_dir) == 0
+
+ manifest = json.loads((run_dir / "frames" / "frames-manifest.json").read_text(encoding="utf-8"))
+ row = manifest["rows"][0]
+ assert row["ok"], row
+ assert row.get("plain_files"), "pixel-perfect run must save plain twins"
+
+ for index in range(2):
+ pixel = Image.open(run_dir / "frames" / "walk" / f"frame-{index}.png").convert("RGBA")
+ plain = Image.open(run_dir / "frames" / "walk" / f"frame-{index}.plain.png").convert("RGBA")
+ pb = pixel.getchannel("A").getbbox()
+ lb = plain.getchannel("A").getbbox()
+ assert pb is not None and lb is not None
+ # same footprint: identical box within grid-rounding tolerance (contain fit)
+ for a, b in zip(pb, lb):
+ assert abs(a - b) <= 2, f"frame {index}: pixel bbox {pb} vs plain bbox {lb}"
+
+ # detected input grid (the actual cut lines) is recorded per frame, mapped into
+ # cell coords: the lattice must cover the plain twin's content bbox.
+ grids = row.get("input_grids")
+ assert grids and len(grids) == 2
+ for index, grid in enumerate(grids):
+ assert grid and grid["x"] and grid["y"], f"frame {index}: missing input grid"
+ plain = Image.open(run_dir / "frames" / "walk" / f"frame-{index}.plain.png").convert("RGBA")
+ lb = plain.getchannel("A").getbbox()
+ assert grid["x"][0] <= lb[0] + 2 and grid["x"][-1] >= lb[2] - 2
+ assert grid["y"][0] <= lb[1] + 2 and grid["y"][-1] >= lb[3] - 2
+ # ~one logical pixel per cut cell: line count tracks the sprite's logical size
+ assert len(grid["x"]) - 1 >= 10 and len(grid["y"]) - 1 >= 20
+ if row.get("orig_files"):
+ orig = Image.open(run_dir / "frames" / "walk" / "orig" / f"frame-{index}.png").convert("RGBA")
+ scale = orig.width // pixel.width
+ assert scale >= 2
+ ob = orig.getchannel("A").getbbox()
+ # 관용치 2 논리픽셀 -> **1** 로 조인다 (실측 근거: 2026-07-25 계측 10조합에서 실제
+ # 어긋남은 0.0 논리픽셀, plan sprite-gen/grid-record-exactness). 0 으로 두지 않는
+ # 이유는 이 파일이 conform/native·물리캡 등 여러 fit 경로를 함께 돌려서다 — 정확
+ # 일치 단정은 경로를 고정한 tests/test_grid_record_exactness.py 가 소유하고,
+ # 여기는 그 경로들 전체의 회귀 안전망으로 1픽셀 여유만 남긴다.
+ for a, b in zip(ob, tuple(v * scale for v in pb)):
+ assert abs(a - b) <= scale, f"frame {index}: orig bbox {ob} vs pixel bbox x{scale}"
+
+
+def test_partial_generation_view_tolerance(tmp_path) -> None:
+ """부분 생성(일부 상태만 추출) 세대: 관찰자(뷰)는 allow_pending_states 로 통과,
+ 소비자 기본 게이트는 여전히 fail-loud."""
+ import json as _json
+ import pytest as _pytest
+ from sprite_gen.frames.extract import load_consistent_frames_manifest
+ run_dir = _build_pp_run(tmp_path)
+ request = _json.loads((run_dir / "sprite-request.json").read_text(encoding="utf-8"))
+ request["states"]["walk2"] = dict(request["states"]["walk"]) # 아직 raw 없는 두 번째 상태
+ (run_dir / "sprite-request.json").write_text(_json.dumps(request), encoding="utf-8")
+ assert extract_module.run(run_dir=run_dir, states="walk") == 0
+ manifest = load_consistent_frames_manifest(run_dir, allow_pending_states=True)
+ assert [r["state"] for r in manifest["rows"]] == ["walk"]
+ with _pytest.raises(SystemExit, match="incomplete generation"):
+ load_consistent_frames_manifest(run_dir)
+
+
+def test_apply_pixel_edits_sidecar() -> None:
+ """픽셀 편집 사이드카: 칠하기/지우기 합성, 원본 불변, 손상 키 무시."""
+ from sprite_gen.curate.curation import apply_pixel_edits
+ frame = Image.new("RGBA", (8, 8), (10, 20, 30, 255))
+ out = apply_pixel_edits(frame, {"1,1": "#ff0000", "2,2": None, "bad": "#000000", "99,0": "#000000"})
+ assert out.getpixel((1, 1)) == (255, 0, 0, 255)
+ assert out.getpixel((2, 2)) == (0, 0, 0, 0)
+ assert out.getpixel((3, 3)) == (10, 20, 30, 255)
+ assert frame.getpixel((1, 1)) == (10, 20, 30, 255) # 원본 불변
+ assert apply_pixel_edits(frame, None) is frame
+
+
+def test_padded_component_no_ghost_bottom_row() -> None:
+ """회귀 2026-07-14 회귀 (down_idle blink 발밑 1px 돌출, maintainer 발견).
+
+ component_group_image 의 4px 투명 패딩 + 위상 추정 노이즈(참 lead 4 를 2.8 로
+ 측정 → _grid_edges 가 0 으로 스냅) 조합이 격자를 패딩만큼 위로 밀었다. 꼬리에
+ 자투리 셀이 생기고, 발바닥 블록의 쪼개진 하단 + 문턱 근처 알파(~134) 프린지가
+ 유령 픽셀로 응고해 최종 프레임 발밑에 1px 이 돌출했다. 스냅 전 알파 bbox 로
+ 조이면(tighten_components) 콘텐츠가 블록 정수배가 되어 격자가 등분으로 떨어진다.
+ """
+ pitch = 13.213
+ blocks_w, blocks_h = 8, 6
+ pad = 4
+ solid_h = round(blocks_h * pitch) - 1 # 마지막 블록의 1px 은 프린지가 채운다 (회귀 기하)
+ width = round(blocks_w * pitch)
+ comp = Image.new("RGBA", (width + pad * 2, solid_h + 1 + pad * 2), (0, 0, 0, 0))
+ for y in range(solid_h):
+ for x in range(width):
+ comp.putpixel((pad + x, pad + y), (60, 90, 180, 255))
+ for x in range(width): # 문턱(128) 살짝 위의 접지 프린지 — 육안으론 거의 안 보인다
+ comp.putpixel((pad + x, pad + solid_h), (60, 90, 180, 134))
+
+ noisy_phase = (2.8, 2.8) # 참 lead=4 인데 lead-스냅 문턱(pitch/4=3.3) 아래로 측정된 회귀 값
+
+ # 버그 경로 재현: 패딩째 스냅하면 유령 바닥 행이 응고한다 (테스트가 무는지 자기검증)
+ buggy = extract_module.grid_snap_downscale(comp, (pitch, pitch), True, noisy_phase)
+ assert buggy.getbbox()[3] > blocks_h
+
+ tight = extract_module.tighten_components([comp])[0]
+ assert tight.size == (width, solid_h + 1)
+ fixed = extract_module.grid_snap_downscale(tight, (pitch, pitch), True, noisy_phase)
+ bbox = fixed.getbbox()
+ assert bbox[3] - bbox[1] == blocks_h, f"ghost row survived: {fixed.size} bbox={bbox}"
+
+
+def test_fringe_does_not_inflate_grid() -> None:
+ """회귀 2026-07-17 회귀 (synthetic_fixture_a pp 부스러기/디테일 뭉개짐, maintainer 발견).
+
+ 크로마 제거가 남긴 sub-128 AA 프린지가 any-alpha `getbbox()` 크롭에 포함되면
+ 격자 원점이 프린지 폭만큼 밀리고 `_grid_edges` 셀 개수 반올림이 한 칸 는다 —
+ 모든 셀이 참 블록을 빗겨 샘플링해 색이 섞이고, 실루엣 밖 부스러기 열이 응고한다.
+ tighten_components 는 solid alpha bbox(α>=128) 로 조여 프린지를 격자 계산
+ 밖으로 밀어낸다 (grid_snap_downscale/binarize_alpha 와 동일 불투명 기준).
+ """
+ pitch = 12
+ blocks_w, blocks_h = 12, 10
+ lut = [(200, 60, 60), (60, 200, 60), (60, 60, 200), (220, 160, 40),
+ (240, 230, 210), (90, 50, 20), (20, 20, 20), (120, 160, 220)]
+
+ def block_color(bx: int, by: int) -> tuple[int, int, int]:
+ return lut[(bx * 7 + by * 3) % len(lut)]
+
+ solid_w, solid_h = blocks_w * pitch, blocks_h * pitch
+ fringe_left, fringe_top = 7, 5
+ comp = Image.new("RGBA", (fringe_left + solid_w, fringe_top + solid_h), (0, 0, 0, 0))
+ for y in range(solid_h):
+ for x in range(solid_w):
+ comp.putpixel((fringe_left + x, fringe_top + y), block_color(x // pitch, y // pitch) + (255,))
+ for y in range(comp.height): # 남는 자리 전부 문턱 미만(α=90) 프린지
+ for x in range(comp.width):
+ if comp.getpixel((x, y))[3] == 0:
+ comp.putpixel((x, y), (30, 30, 30, 90))
+
+ def snap(image: Image.Image) -> Image.Image:
+ grid, phase = extract_module.detect_pixel_grid(image)
+ return extract_module.grid_snap_downscale(image, grid, True, phase)
+
+ def exact(out: Image.Image) -> bool:
+ return out.size == (blocks_w, blocks_h) and all(
+ out.getpixel((bx, by))[:3] == block_color(bx, by)
+ for by in range(blocks_h) for bx in range(blocks_w))
+
+ # 버그 경로 재현: any-alpha bbox 크롭(프린지 포함)은 격자가 부푼다 (테스트가 무는지 자기검증)
+ buggy = snap(comp.crop(comp.getbbox()))
+ assert not exact(buggy), f"buggy path unexpectedly clean: {buggy.size}"
+
+ tight = extract_module.tighten_components([comp])[0]
+ assert tight.size == (solid_w, solid_h), f"tighten kept fringe: {tight.size}"
+ fixed = snap(tight)
+ assert exact(fixed), f"solid-bbox snap not exact: {fixed.size}"
+
+
+def test_shared_palette_preserves_rare_saturated_color() -> None:
+ """회귀 2026-07-17 회귀 (synthetic_fixture_a 금색 머리끈·목걸이 실종, maintainer 발견).
+
+ run-wide 팔레트 기본 24 는 다상태 배치에서 희소 포인트 컬러를 굶겼다 —
+ population median-cut 이 큰 색군들을 쫓느라 0.2% 금색 클러스터를 이웃 박스에
+ 흡수한다 (실측: hero 36상태 배치 24색에서 금색 최근접 ΔRGB 59, 48색 5.5).
+ 기본 48 상향의 회귀 가드: 뚜렷한 색군 30개 + 희소 금색에서 기본 크기가
+ 금색을 보존해야 한다.
+ """
+ frame = Image.new("RGBA", (128, 75), (0, 0, 0, 0))
+ clusters = [((k * 53) % 200, (k * 97) % 200, (k * 151) % 200) for k in range(30)]
+ i = 0
+ for y in range(75):
+ for x in range(128):
+ c = clusters[min(29, (y // 15) * 6 + (x // 22))]
+ j = (i * 31) % 17 - 8
+ frame.putpixel((x, y), tuple(max(0, min(255, v + j)) for v in c) + (255,))
+ i += 1
+ gold = (240, 158, 45)
+ for y in range(4):
+ for x in range(4):
+ frame.putpixel((x, y), gold + (255,))
+
+ def nearest(palette: list, c: tuple) -> float:
+ return min(((e[0] - c[0]) ** 2 + (e[1] - c[1]) ** 2 + (e[2] - c[2]) ** 2) ** 0.5 for e in palette)
+
+ starved = extract_module.build_shared_palette([frame], 24)
+ assert nearest(starved, gold) > 30, "starvation setup lost its bite — recalibrate the fixture"
+ healthy = extract_module.build_shared_palette([frame], 48)
+ assert nearest(healthy, gold) <= 8, f"default-size palette still starves gold: {nearest(healthy, gold):.1f}"
+
+
+def test_conform_flag_rejected(tmp_path) -> None:
+ """maintainer 확정 2026-07-14/17 회귀: fit.conform 은 제거됐다 — 선언되어 있으면 요란한 거부.
+
+ 옵트인 잔재는 제거된 결정(강제 눌림 금지)이 플래그 하나로 되살아나는 회귀
+ 경로였다 (회귀 2026-07-17: 높이 통일 시도가 이 플래그로 재발)."""
+ import pytest as _pytest
+ run_dir = _build_pp_run(tmp_path)
+ request = json.loads((run_dir / "sprite-request.json").read_text(encoding="utf-8"))
+ request["fit"]["conform"] = True
+ (run_dir / "sprite-request.json").write_text(json.dumps(request), encoding="utf-8")
+ with _pytest.raises(SystemExit, match="fit.conform was removed"):
+ extract_module.run(run_dir=run_dir)
diff --git a/tests/curate/test_pixel_unfake_migration.py b/tests/curate/test_pixel_unfake_migration.py
new file mode 100644
index 0000000..3570890
--- /dev/null
+++ b/tests/curate/test_pixel_unfake_migration.py
@@ -0,0 +1,307 @@
+# SPDX-License-Identifier: Apache-2.0
+"""은퇴한 `pixel_perfect` 키 -> 현행 `pixel_unfake` 이관 (plan sprite-gen/pixel-unfake-rename).
+
+용어 근거: "픽셀 퍼펙트" 는 광의
+통용어(UI 정합·충돌판정)의 오용이고, 이 파이프라인이 하는 일의 정확한 명칭은 격자 스냅 /
+재양자화 — 커뮤니티 속칭 **unfake** (unfake.js 유래). 어휘를 코드·스키마까지 통일하되, 기존
+런(retired-key synthetic fixtures)은 일회성 이관으로 무손실 통과해야 한다.
+
+이관 계약: 읽기는 구키를 신키로 **메모리에서만** 정규화하고 파일은 건드리지 않는다 · 디스크
+스키마 이관은 명시 writer (`migrate_request_file` / `sprite-gen migrate-request --apply`)
+에서만 원자적으로 · 두 키 동시 = hard fail · 신키만 있으면 무동작 (멱등).
+
+읽기/쓰기 분리의 근거와 조회 바이트 불변 계약은 `test_request_read_no_mutation.py` 가, 이관
+writer 와 편집 writer 사이의 격리(같은 `publish_guard`, 락 획득 후 fresh 재독)는
+`test_request_write_isolation.py` 가 소유한다 (plan sprite-gen/state-revision-read-mutation).
+"""
+
+from __future__ import annotations
+
+import json
+
+import pytest
+
+from sprite_gen.curate.curation import (CURATION_FILENAME, frame_variant, load_curation_report,
+ run_revision)
+from sprite_gen.spec.runio import load_request, migrate_request_file
+
+
+def _write_request(run_dir, fit: dict) -> None:
+ run_dir.mkdir(parents=True, exist_ok=True)
+ (run_dir / "sprite-request.json").write_text(json.dumps({
+ "version": 1, "kind": "sprite-gen-request", "engine": "component-row",
+ "character": {"id": "migbot", "description": "", "base_image": None},
+ "cell": {"shape": "square", "width": 96, "height": 96, "safe_margin_x": 8,
+ "safe_margin_y": 8, "size": 96, "safe_margin": 8},
+ "chroma_key": {"name": "magenta", "hex": "#FF00FF", "rgb": [255, 0, 255],
+ "selection": "fallback"},
+ "states": {"walk": {"frames": 2, "fps": 8, "loop": True, "action": "x"}},
+ "fit": fit,
+ }, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
+
+
+def test_explicit_migration_rewrites_the_request(tmp_path, capsys) -> None:
+ """구키 런은 **명시 이관**에서만 신키로 재기록된다 — 읽기는 메모리 정규화까지다.
+
+ 쓰기가 사용자가 부른 명령 안에서만 일어나야 조회가 canonical 런을 오염시키지 않는다
+ (plan state-revision-read-mutation). 이관 자체는 값·의미를 보존하고 키 이름만 옮긴다."""
+ run_dir = tmp_path / "run"
+ _write_request(run_dir, {"pixel_perfect": True, "logical_height": 48})
+
+ request = load_request(run_dir)
+ assert request["fit"]["pixel_unfake"] is True
+ assert "pixel_perfect" not in request["fit"]
+ # 읽기는 안내만 낸다 (한 프로세스에서 런당 한 번) — 파일은 그대로다
+ assert "migrate-request" in capsys.readouterr().err
+ assert "pixel_perfect" in json.loads(
+ (run_dir / "sprite-request.json").read_text(encoding="utf-8"))["fit"]
+
+ # dry run 은 옮길 것이 있다고만 답한다
+ assert migrate_request_file(run_dir) is True
+ 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
+ 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
+
+
+def test_both_request_keys_present_fails_loud(tmp_path) -> None:
+ """어느 쪽이 진실인지 코드가 고를 수 없다 — 고르는 순간 그게 조용한 폴백이다."""
+ run_dir = tmp_path / "run"
+ _write_request(run_dir, {"pixel_perfect": False, "pixel_unfake": True})
+ with pytest.raises(SystemExit) as excinfo:
+ load_request(run_dir)
+ assert "two truths" in str(excinfo.value)
+
+
+def test_reading_is_unaffected_by_a_pipeline_writer_lock(tmp_path) -> None:
+ """락이 있든 없든 읽기 결과는 같다 — 읽기가 쓰지 않으니 락을 볼 이유가 없다.
+
+ 예전엔 로더가 락 유무로 재기록 여부를 갈랐고, 그래서 "락이 없을 때만 파일이 바뀐다" 는
+ 상태 의존 부작용이 조회 경로에 있었다."""
+ from sprite_gen.spec.runio import LOCK_FILENAME
+
+ run_dir = tmp_path / "run"
+ _write_request(run_dir, {"pixel_perfect": True})
+ unlocked = load_request(run_dir)
+
+ (run_dir / LOCK_FILENAME).write_text("held by another writer", encoding="utf-8")
+ assert load_request(run_dir) == unlocked
+ assert unlocked["fit"]["pixel_unfake"] is True
+ assert "pixel_perfect" in json.loads(
+ (run_dir / "sprite-request.json").read_text(encoding="utf-8"))["fit"]
+
+
+def _write_curation(run_dir, doc: dict) -> None:
+ """현재 세대 도장을 찍어 둔다 — 스탬프 없는 사이드카는 세대 게이트가 (정상적으로) 드롭해서
+ 이관 여부를 볼 수 없다. 여기서 검증하려는 건 이관이고 세대 판정이 아니다."""
+ run_dir.mkdir(parents=True, exist_ok=True)
+ doc = {**doc, "run_revision": run_revision(run_dir)}
+ (run_dir / CURATION_FILENAME).write_text(json.dumps(doc), encoding="utf-8")
+
+
+def test_legacy_sidecar_keys_are_migrated_on_load(tmp_path) -> None:
+ """사이드카도 같은 계약 — 최상위 + 행별 둘 다."""
+ run_dir = tmp_path / "run"
+ _write_request(run_dir, {"pixel_unfake": True})
+ _write_curation(run_dir, {"version": 1, "kind": "sprite-gen-curation",
+ "pixel_perfect": False,
+ "states": {"walk": {"pixel_perfect": True, "selected": [0]}}})
+ doc = load_curation_report(run_dir)[0]
+ assert doc["pixel_unfake"] is False and "pixel_perfect" not in doc
+ assert doc["states"]["walk"]["pixel_unfake"] is True
+ # 해석 SSoT 도 현행 키를 본다
+ assert frame_variant(doc, "walk") == "pixel"
+ assert frame_variant(doc) == "plain"
+
+
+def test_both_sidecar_keys_present_fails_loud(tmp_path) -> None:
+ run_dir = tmp_path / "run"
+ _write_request(run_dir, {"pixel_unfake": True})
+ _write_curation(run_dir, {"version": 1, "kind": "sprite-gen-curation",
+ "pixel_perfect": True, "pixel_unfake": False, "states": {}})
+ with pytest.raises(SystemExit) as excinfo:
+ load_curation_report(run_dir)
+ assert "two truths" in str(excinfo.value)
+
+
+def test_unrelated_edits_do_not_migrate_the_schema(tmp_path) -> None:
+ """스키마와 무관한 편집(테이크 기록·fps)은 디스크의 키 형태를 그대로 둔다.
+
+ 이 경로들은 로더가 정규화해 준 문서를 통째로 되쓴다. 그대로 쓰면 fps 한 번 바꾼 것이
+ 스키마까지 옮겨, 이관이 다시 "아무 명령이나 하는 김에 하는 일" 이 된다 — 명시 writer
+ 하나만 스키마를 바꾼다는 계약이 그 자리에서 깨진다."""
+ from sprite_gen.spec.runio import write_request
+
+ run_dir = tmp_path / "run"
+ _write_request(run_dir, {"pixel_perfect": True, "logical_height": 48})
+
+ request = load_request(run_dir)
+ assert request["fit"]["pixel_unfake"] is True # 메모리는 현행 키
+ request["states"]["walk"]["fps"] = 12
+ write_request(run_dir, request)
+
+ on_disk = json.loads((run_dir / "sprite-request.json").read_text(encoding="utf-8"))
+ assert on_disk["states"]["walk"]["fps"] == 12 # 편집은 반영되고
+ assert on_disk["fit"] == {"pixel_perfect": True, "logical_height": 48} # 스키마는 그대로
+ assert request["fit"]["pixel_unfake"] is True # 호출부 dict 는 안 건드린다
+
+ # 이미 현행 키인 런은 되접을 것이 없다 (되접기가 신키 런을 구키로 되돌리면 안 된다)
+ fresh_run = tmp_path / "fresh"
+ _write_request(fresh_run, {"pixel_unfake": False})
+ doc = load_request(fresh_run)
+ doc["states"]["walk"]["fps"] = 9
+ write_request(fresh_run, doc)
+ assert json.loads((fresh_run / "sprite-request.json").read_text(
+ encoding="utf-8"))["fit"] == {"pixel_unfake": False}
+
+
+def test_migrate_request_command_is_dry_run_by_default(tmp_path, capsys) -> None:
+ """공개 진입점도 같은 계약이다 — `--apply` 없이는 아무것도 쓰지 않고, 무엇이 바뀔지만
+ 말한다 (`migrate-breathe` 와 같은 모양)."""
+ from sprite_gen.cli import main
+
+ run_dir = tmp_path / "run"
+ _write_request(run_dir, {"pixel_perfect": True, "logical_height": 48})
+
+ assert main(["migrate-request", str(run_dir)]) == 0
+ assert "dry-run" in capsys.readouterr().out
+ assert "pixel_perfect" in json.loads(
+ (run_dir / "sprite-request.json").read_text(encoding="utf-8"))["fit"]
+
+ assert main(["migrate-request", str(run_dir), "--apply"]) == 0
+ assert json.loads((run_dir / "sprite-request.json").read_text(
+ encoding="utf-8"))["fit"] == {"pixel_unfake": True, "logical_height": 48}
+
+ # 멱등: 이미 현행 키뿐이면 옮길 것이 없다고 답하고 끝난다
+ assert main(["migrate-request", str(run_dir), "--apply"]) == 0
+ assert "옮길 것이 없다" in capsys.readouterr().out
+
+
+def test_migrate_request_command_reports_the_curation_cost_before_writing(tmp_path, capsys) -> None:
+ """이관은 request 바이트를 바꾸므로 `run_revision` 이 움직인다 — 행별 스탬프가 없는
+ 큐레이션 행은 다음 로드에서 드롭된다. 쓰기 **전에** 그걸 말한다 (조용히 잃지 않는다)."""
+ from sprite_gen.cli import main
+
+ run_dir = tmp_path / "run"
+ _write_request(run_dir, {"pixel_perfect": True})
+ _write_curation(run_dir, {"version": 1, "kind": "sprite-gen-curation",
+ "states": {"walk": {"selected": [0]}}}) # 행 스탬프 없음
+
+ assert main(["migrate-request", str(run_dir)]) == 0
+ assert "행별 스탬프가 없어 드롭될 행 — walk" in capsys.readouterr().out
+
+
+def test_retired_cli_flag_reports_the_new_name(tmp_path) -> None:
+ """구 플래그는 조용한 별칭이 아니라 안내와 함께 죽는다 (두 이름 공존 금지)."""
+ from sprite_gen.cli import main
+
+ with pytest.raises(SystemExit) as excinfo:
+ main(["prepare", "--out-dir", str(tmp_path / "o"), "--character-id", "x",
+ "--fit-pixel-perfect"])
+ message = str(excinfo.value)
+ assert "--fit-pixel-unfake" in message and "retired" in message
+
+
+def test_reroll_reads_through_the_gate_not_raw(tmp_path) -> None:
+ """레거시 런의 리롤이 **거짓 거부**되지 않는다 (validator 2026-07-26 R1 재현 고정).
+
+ 리롤은 `fit.pixel_unfake` 계약 위에서만 테이크를 병합한다. 그 검사 앞의 request 읽기가
+ 게이트를 우회해 raw 로 읽으면, 아직 이관되지 않은 런(디스크에 은퇴 키만)에서 검사가 항상
+ False 가 되어 "언페이크가 켜진 런"의 리롤을 켜져 있지 않다며 막는다. 리롤은 뷰가 **별도
+ 서브프로세스**로 띄우므로 뷰 프로세스의 in-memory 이관도 넘어오지 않는다 — 그래서 읽기
+ 자체가 게이트 뒤에 있어야 한다 (키 이름만 바꾸는 것으로는 부족하다)."""
+ import random
+
+ from PIL import Image
+
+ from sprite_gen.effects import reroll
+
+ run_dir = tmp_path / "run"
+ (run_dir / "raw").mkdir(parents=True)
+ rng = random.Random(7)
+ art = Image.new("RGB", (20, 36), (255, 0, 255))
+ for y in range(36):
+ for x in range(20):
+ if rng.random() < 0.55:
+ art.putpixel((x, y), (rng.randrange(30, 220), 90, 200))
+ frame = art.resize((160, 288), Image.Resampling.NEAREST)
+ strip = Image.new("RGB", (frame.width * 2 + 120, frame.height + 80), (255, 0, 255))
+ strip.paste(frame, (40, 40))
+ strip.paste(frame, (frame.width + 80, 40))
+ strip.save(run_dir / "raw" / "walk.png")
+ _write_request(run_dir, {"pixel_perfect": True, "logical_height": 48}) # 은퇴 키만
+
+ with pytest.raises(SystemExit) as excinfo:
+ reroll.reroll_state(run_dir, "walk")
+ # pp 계약 검사를 통과해 **다음** 단계(프롬프트 부재)에서 멈춰야 한다
+ assert "require fit.pixel_unfake" not in str(excinfo.value), (
+ "레거시 런이 언페이크 계약 검사에서 거짓 거부됐다 — 읽기가 게이트를 우회한다")
+ assert "prompt file missing" in str(excinfo.value)
+ # 게이트를 지났지만 파일은 그대로다 — 읽기 호환은 디스크를 바꾸지 않고 얻는다
+ assert "pixel_perfect" in json.loads(
+ (run_dir / "sprite-request.json").read_text(encoding="utf-8"))["fit"]
+
+
+def test_no_production_path_reads_the_request_outside_the_gate() -> None:
+ """프로덕션 코드가 `sprite-request.json` 을 게이트 밖에서 읽지 않는다 (구조 단정).
+
+ 이게 이 플랜의 핵심 계약이다. 키 이름만 바꾸고 읽기를 게이트 뒤로 옮기지 않으면, 아직
+ 이관되지 않은 런에서 그 판독부만 조용히 틀린 답을 본다 — 실제로 `reroll.py` 에서 리롤이
+ 거짓 거부되는 회귀가 났고(validator R1), 같은 클래스가 `interpolate.py`·`preview.py` 에도 있었다.
+
+ **AST 로 본다.** 첫 버전은 한 줄 정규식이었고, 실제 회귀 형태(경로를 변수에 담고 다음 줄에서
+ `json.loads(path.read_text())`)를 못 잡았다 — validator가 mutant 로 증명했다(interpolate 를 옛
+ 형태로 되돌려도 548 passed). 그래서 판정 단위를 **함수**로 올린다: 한 함수 안에서 request
+ 파일을 가리키면서(`REQUEST_FILENAME` 또는 리터럴 파일명) `json.load(s)` 를 호출하면 그것이
+ 게이트 우회다. 쓰기 경로는 `json.dumps` 를 쓰므로 걸리지 않는다.
+
+ 테스트 코드는 예외다: 테스트는 "디스크에 실제로 무엇이 쓰였는가" 를 검사해야 한다."""
+ import ast
+ from pathlib import Path as _Path
+
+ REQUEST_MARKERS = {"REQUEST_FILENAME", "sprite-request.json"}
+
+ def _mentions_request(node: ast.AST) -> bool:
+ for child in ast.walk(node):
+ if isinstance(child, ast.Name) and child.id in REQUEST_MARKERS:
+ return True
+ if isinstance(child, ast.Constant) and child.value in REQUEST_MARKERS:
+ return True
+ return False
+
+ root = _Path(__file__).resolve().parents[2]
+ offenders: list[str] = []
+ for path in sorted(list((root / "sprite_gen").glob("*.py")) + list((root / "scripts").glob("*.py"))):
+ if path.name == "runio.py": # 게이트 자신이 사는 곳
+ continue
+ tree = ast.parse(path.read_text(encoding="utf-8"))
+ for node in ast.walk(tree):
+ if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
+ continue
+ # ① 이 함수 안에서 request 경로를 담은 변수 이름들
+ request_vars = set()
+ for child in ast.walk(node):
+ if isinstance(child, ast.Assign) and _mentions_request(child.value):
+ for target in child.targets:
+ if isinstance(target, ast.Name):
+ request_vars.add(target.id)
+ # ② 그 변수(또는 리터럴/상수)를 읽는 json.load(s) 호출만 우회다.
+ # 같은 함수가 curation.json 을 읽는 건 무관하다 (오탐 방지 — 판정 단위를
+ # 함수 전체로 두면 do_POST/heal_run 이 걸린다).
+ for child in ast.walk(node):
+ if not isinstance(child, ast.Call):
+ continue
+ target = child.func
+ if not (isinstance(target, ast.Attribute) and target.attr in {"load", "loads"}
+ and isinstance(target.value, ast.Name) and target.value.id == "json"):
+ continue
+ arg_names = {n.id for n in ast.walk(child) if isinstance(n, ast.Name)}
+ if (arg_names & request_vars) or _mentions_request(child):
+ offenders.append(f"{path.relative_to(root)}:{child.lineno} in {node.name}()")
+ assert not offenders, (
+ "게이트를 우회해 request 를 직접 읽는 프로덕션 경로:\n " + "\n ".join(offenders)
+ + "\n→ `runio.load_request` 를 쓰라 (이관·두 키 hard fail 판정이 그 안에만 있다)")
diff --git a/tests/curate/test_snap_phase_policy.py b/tests/curate/test_snap_phase_policy.py
new file mode 100644
index 0000000..893ac89
--- /dev/null
+++ b/tests/curate/test_snap_phase_policy.py
@@ -0,0 +1,100 @@
+# SPDX-License-Identifier: Apache-2.0
+"""추출 경로가 **어떤 위상으로 스냅하는지**를 고정한다 (헬퍼가 아니라 정책).
+
+회귀 (maintainer 2026-07-25, synthetic_fixture_b down_jump frame-0, plan
+`sprite-gen/frame-pitch-consensus-eats-a-row`): 스냅이 피치 검출의 부산물인 히스토그램
+위상을 쓰면 참 위상에서 pitch/2 까지 밀린다. `refine_edges_to_boundaries` 는 절단선을
+±pitch/3 창 안에서만 당기므로 그 오차는 구조적으로 복구되지 않고, 캐릭터 눈 4행이
+3행으로 병합됐다 (8칸 → 7칸).
+
+`_best_phase` 를 직접 부르는 단위 테스트만으로는 이 회귀를 못 잡는다 — 헬퍼는 그대로 두고
+**스냅 루프가 그 헬퍼를 안 쓰도록** 되돌리면 그런 테스트는 전부 통과한다 (검증자 maintainer
+변이 실측: 스냅 루프를 히스토프램 위상으로 되돌려도 335 passed). 그래서 여기서는 실제
+추출 스크립트를 태워 논리 격자 칸 수가 보존되는지를 본다.
+"""
+import json
+import random
+import shutil
+from pathlib import Path
+
+from PIL import Image
+
+from conftest import run_script
+
+PALETTE = [(240, 210, 175), (60, 40, 30), (40, 90, 180), (230, 225, 200), (150, 90, 50)]
+PITCH = 13
+# 참 위상을 비영으로 만드는 크롭량. 11 은 히스토그램 위상이 칸을 잃는 실측 지점이다.
+PHASE_OFFSET = 11
+MAGENTA = (255, 0, 255)
+
+
+def _logical_art(seed: int = 11) -> Image.Image:
+ """무작위 도트(격자 신호 확보) 위에 2x4 짙은 막대 둘 — 먹혔던 눈의 축소판."""
+ rng = random.Random(seed)
+ width, height = 24, 40
+ art = Image.new("RGBA", (width, height))
+ pixels = art.load()
+ for y in range(height):
+ for x in range(width):
+ pixels[x, y] = (*rng.choice(PALETTE), 255)
+ for left in (6, 14):
+ for x in (left, left + 1):
+ for y in range(12, 16):
+ pixels[x, y] = (10, 8, 6, 255)
+ return art
+
+
+def _build_run(run_dir: Path, frames: int = 2) -> Image.Image:
+ """위상이 비영인 합성 스트립 + 픽셀퍼펙 요청으로 런 디렉토리를 만든다."""
+ (run_dir / "raw").mkdir(parents=True, exist_ok=True)
+ art = _logical_art()
+ upscaled = art.resize((art.width * PITCH, art.height * PITCH), Image.NEAREST)
+ # 첫 칸을 잘라내 참 위상을 격자 시작점에서 떼어놓는다.
+ upscaled = upscaled.crop((PHASE_OFFSET, PHASE_OFFSET, upscaled.width, upscaled.height))
+
+ slot = upscaled.width + 40
+ strip = Image.new("RGBA", (slot * frames, upscaled.height + 40), (*MAGENTA, 255))
+ for index in range(frames):
+ strip.paste(upscaled, (index * slot + 20, 20), upscaled)
+ strip.convert("RGB").save(run_dir / "raw" / "idle.png")
+
+ request = {
+ "version": 1,
+ "kind": "sprite-gen-request",
+ "engine": "component-row",
+ "character": {"id": "phase-probe", "description": "offset-phase probe", "base_image": None},
+ "cell": {"shape": "square", "width": 64, "height": 64,
+ "safe_margin_x": 2, "safe_margin_y": 2, "size": 64, "safe_margin": 2},
+ "chroma_key": {"name": "magenta", "hex": "#FF00FF", "rgb": list(MAGENTA),
+ "selection": "fallback"},
+ "fit": {"pixel_unfake": True},
+ "states": {"idle": {"frames": frames, "fps": 8, "loop": True,
+ "action": "offset-phase probe"}},
+ "style": "synthetic, flat solid shapes on magenta",
+ "motion_phase_guides": False,
+ }
+ (run_dir / "sprite-request.json").write_text(json.dumps(request, indent=2), encoding="utf-8")
+ return art
+
+
+def test_extraction_keeps_every_logical_cell_when_the_true_phase_is_offset(tmp_path: Path) -> None:
+ """위상이 비영인 판을 추출해도 논리 칸 수가 한 칸도 줄지 않아야 한다.
+
+ 스냅이 히스토그램 위상으로 돌아가면 24x40 이 23x39 가 된다 (실측) — 잃은 행에 걸친
+ 2x4 덩어리가 이웃 칸에 병합되는 것이 부모 회귀의 기전이다.
+ """
+ run_dir = tmp_path / "run"
+ if run_dir.exists():
+ shutil.rmtree(run_dir)
+ art = _build_run(run_dir)
+
+ result = run_script("extract_sprite_row_frames.py", "--run-dir", str(run_dir))
+ assert result.returncode == 0, result.stdout[-2000:] + result.stderr[-2000:]
+
+ for index in range(2):
+ frame = Image.open(run_dir / "frames" / "idle" / f"frame-{index}.png").convert("RGBA")
+ bbox = frame.getbbox()
+ logical = frame.crop(bbox) if bbox else frame
+ assert logical.size == art.size, (
+ f"frame {index}: 논리 격자 {logical.size} != {art.size} — "
+ "위상이 밀려 칸이 병합됐다 (스냅이 실측 위상을 안 쓰는 회귀)")
diff --git a/tests/effects/test_breathe.py b/tests/effects/test_breathe.py
new file mode 100644
index 0000000..3c757e0
--- /dev/null
+++ b/tests/effects/test_breathe.py
@@ -0,0 +1,866 @@
+# SPDX-License-Identifier: Apache-2.0
+"""결정론 호흡 레이어(sprite_gen.effects.breathe) 회귀 — 봉투 워프의 불변식.
+
+지키는 것 (구현이 아니라 계약):
+ 1. 강체 구간은 프레임 간 **비트 동일** (근사가 아니라 항등)
+ 2. 가로 사상은 단조 — 접힘 없음
+ 3. 홀짝 보존 — 중심축이 프레임마다 안 튄다
+ 4. 발바닥 고정 · 루프 길이 불변
+ 5. 정규화 기준은 병목이 진짜일 때만 목
+ 6. 행당 변형 상한 초과는 조용히 깎지 않고 멈춘다
+"""
+
+import pytest
+from PIL import Image
+
+from sprite_gen.effects.anatomy import analyze
+from pathlib import Path
+
+from sprite_gen.effects.breathe import (DEFAULT_DEPTH, MAX_ROW_STRAIN, SMOOTH_CYCLE_FRAMES, TAPER,
+ anatomy_report, bake_breathe_sequence, breathe_reads_smoothly,
+ envelope, fit_breathe_pattern, fitted_breath_count,
+ freeze_anatomy, phase_frame, reference_key, resolve_anatomy,
+ recommended_breathe_frames, row_strain, wave)
+from sprite_gen.curate.curation import state_breathe
+from sprite_gen.frames.extract import solid_alpha_bbox
+
+CFG = {"depth": DEFAULT_DEPTH, "breaths": 1, "lag": 0.10}
+
+
+def _humanoid() -> Image.Image:
+ """머리 + 목 병목 + 몸통 + 대칭 눈쌍. 검출 세 경로를 모두 태우는 최소 도형."""
+ im = Image.new("RGBA", (64, 96), (0, 0, 0, 0))
+ body = (90, 60, 30, 255)
+ for y in range(8, 30): # 머리
+ for x in range(22, 42):
+ im.putpixel((x, y), body)
+ for y in range(30, 36): # 목 (병목)
+ for x in range(28, 36):
+ im.putpixel((x, y), body)
+ for y in range(36, 84): # 몸통
+ for x in range(18, 46):
+ im.putpixel((x, y), body)
+ for x0 in (25, 35): # 눈 — 축 좌우 대칭
+ for y in range(14, 20):
+ for x in range(x0, x0 + 4):
+ im.putpixel((x, y), (10, 10, 12, 255))
+ return im
+
+
+def _winged() -> Image.Image:
+ """몸통 + 옆으로 뻗은 얇은 부속 — 부속 보호 경로를 태운다."""
+ im = Image.new("RGBA", (120, 96), (0, 0, 0, 0))
+ body = (60, 40, 120, 255)
+ for y in range(10, 30):
+ for x in range(50, 70):
+ im.putpixel((x, y), body)
+ for y in range(30, 34):
+ for x in range(56, 64):
+ im.putpixel((x, y), body)
+ for y in range(34, 84):
+ for x in range(46, 74):
+ im.putpixel((x, y), body)
+ for y in range(40, 56): # 날개
+ for x in range(6, 114):
+ im.putpixel((x, y), body)
+ return im
+
+
+def _dome(with_face: bool = False) -> Image.Image:
+ """아래로 갈수록 단조 증가하는 돔 — 병목이 없다 (슬라임형).
+
+ `with_face` 면 몸통 한가운데에 대칭 눈쌍을 둔다. 목이 없고 얼굴이 몸통에 있는
+ 가장 어려운 조합이라, 실제 스프라이트를 레포에 넣지 않고도 얼굴 주도 경계
+ 경로를 그대로 태운다 (실 스프라이트는 출처·라이선스가 불분명해 픽스처로 안 넣는다)."""
+ pad = 10 # 셀 여백 — 늘어난 프레임이 나갈 자리
+ im = Image.new("RGBA", (80, 80 + 2 * pad), (0, 0, 0, 0))
+ for y in range(80):
+ half = 4 + int(34 * (y / 79) ** 0.6)
+ for x in range(40 - half, 40 + half):
+ im.putpixel((x, y + pad), (40, 160, 90, 255))
+ if with_face:
+ for x0 in (30, 44):
+ for y in range(44, 52):
+ for x in range(x0, x0 + 6):
+ im.putpixel((x, y + pad), (8, 20, 14, 255))
+ return im
+
+
+def _key(tag: str = "fixture") -> str:
+ """테스트용 기준 프레임 키. 키는 그 프레임을 만드는 **입력**의 정규형이라 픽셀과
+ 무관하다 — 픽스처에서는 태그 하나면 충분하고, 파이썬/JS 일치는
+ `test_breathe_reference_key.py` 가 전수로 본다."""
+ return reference_key(state="idle", variant="plain", request_stamp="1:1", source_index=0,
+ source_stamp=tag, pixel_ops=None, transform=None)
+
+
+def _frames(image: Image.Image, count: int = 12, cfg: dict | None = None):
+ cfg = dict(cfg or CFG)
+ cfg["anatomy"] = freeze_anatomy(image, cfg, _key())
+ return bake_breathe_sequence([image] * count, cfg)
+
+
+# ── 1. 강체 구간 항등 ───────────────────────────────────────────────
+
[email protected]("build", [_humanoid, _winged, lambda: _dome(with_face=True)],
+ ids=["humanoid", "winged", "dome-with-face"])
+def test_rigid_region_is_bit_identical_across_frames(build) -> None:
+ """강체 구간은 프레임 간 비트 동일하다.
+
+ **얼굴 없는 돔(`_dome()`)은 이 계약을 태울 수 없다** — 경계가 4행이고 테이퍼 밴드가
+ 5행이라 강체 구간 높이가 음수다. 병목도 얼굴도 없는 실루엣은 지킬 강체 구간이 애초에
+ 없고, 그건 결함이 아니라 그 분기의 성질이다 (validator note 2026-07-25). 그래서 여기서는
+ 강체 구간이 실재하는 3종만 태운다."""
+ src = build()
+ anat = analyze(src)
+ frames, _ = _frames(src)
+ band = int(max(1.5, TAPER * anat.height)) + 1
+ rigid_h = anat.rigid_row - band
+ assert rigid_h > 0, "테스트 도형이 강체 구간을 갖도록 잡혀야 한다"
+ ref = frames[0]
+ top = solid_alpha_bbox(ref)[1]
+ expect = ref.crop((0, top, ref.width, top + rigid_h)).tobytes()
+ for i, frame in enumerate(frames[1:], 1):
+ t = solid_alpha_bbox(frame)[1]
+ got = frame.crop((0, t, frame.width, t + rigid_h)).tobytes()
+ assert got == expect, f"frame {i}: 강체 구간이 바뀌었다 — 항등이어야 한다"
+
+
+def test_zero_strain_is_byte_identical_to_the_source() -> None:
+ """변형이 0 이면 **원본과 바이트 동일**이어야 한다.
+
+ 프레임끼리 비교하는 테스트는 전 프레임이 똑같이 밀려도 통과한다. 원본 대비로
+ 재야 축 재중심화 같은 전역 오프셋이 잡힌다 (회귀 2026-07-25: bbox 중앙을
+ 기준으로 잡아 축이 중앙과 다른 3/3 픽스처가 변형 0 에서 1px 밀렸다)."""
+ for build in (_humanoid, _winged, _dome):
+ src = build()
+ cfg = dict(CFG)
+ cfg["anatomy"] = freeze_anatomy(src, cfg, _key())
+ rest = phase_frame(src, {**cfg, "lag": 0.0}, 0.0) # lag 0 + 위상 0 = 전 행 g==0
+ assert rest.tobytes() == src.tobytes(), f"{build.__name__}: 변형 0 인데 원본과 다르다"
+
+
+def test_phase_zero_is_not_identity_when_the_wave_travels() -> None:
+ """진행파 지연이 있으면 위상 0 도 변형된 프레임이다.
+
+ 구 분할선 방식에선 위상 0 이 항등이라 소비자가 건너뛰어도 됐다. 봉투에선 윗행이
+ `wave(-lag*u)` 만큼 변형되므로 건너뛰면 그 슬롯만 원본이 되어 아틀라스가 매 루프
+ 시작에서 튀고 GIF 굽기와 그림이 갈린다 (validator 검증 2026-07-25, 실측 353px 차이).
+ 소비자 3곳이 이 계약에 걸려 있다 — `compose_atlas`, `compare.js`, 그리고 확대
+ 편집기(`zoom-editor.js` 재생·필름스트립). 앞의 둘은 `if phase:` 가드였고, 편집기는
+ 호흡을 **끈** 상태에서 위상만 0 으로 넘기던 경로였다(끈 프리뷰가 워프돼 굽기와 달랐다).
+
+ **이 테스트는 성질만 고정한다 — 소비자가 되살아나는 것은 못 잡는다.** 처음엔
+ "어느 쪽이든 되살아나면 여기서 잡힌다"고 적었는데 거짓이었다: `compose_atlas` 의
+ 가드를 옛 형태로 되돌려도 이 파일은 전부 통과한다(validator 변이 검증 2026-07-25).
+ 소비자 가드 자체는 `tests/test_breathe_off_state.py` 가 JS·파이썬 양쪽으로 지킨다."""
+ src = _humanoid()
+ cfg = dict(CFG)
+ cfg["anatomy"] = freeze_anatomy(src, cfg, _key())
+ assert cfg["lag"] > 0, "이 계약은 지연이 있을 때의 이야기다"
+ assert phase_frame(src, cfg, 0.0).tobytes() != src.tobytes(), \
+ "위상 0 이 항등이면 소비자가 건너뛰어도 되는 것처럼 보인다"
+ # 지연이 0 이면 위상 0 은 진짜 항등 — 두 경우의 차이가 계약의 핵심이다
+ assert phase_frame(src, {**cfg, "lag": 0.0}, 0.0).tobytes() == src.tobytes()
+
+
+def _small_outlined() -> Image.Image:
+ """문어 크기대(폭 26px)의 밝은 내부 + 1px 검은 외곽선 — 좁은 머리 + 넓은 몸통.
+
+ 발끝 외곽선 플리커는 **작은 스프라이트**에서만 난다 — forward 밀도매핑의 정수
+ 반올림이 좁은 폭에서 실루엣 양끝 열을 통째로 떨구기 때문이다. 큰 픽스처는 여유가
+ 있어 안 떨어진다. 이 기하(폭 26, 몸통폭 21, depth 0.08)는 fix 없이 24위상에서
+ 수백 건 드롭을 재현한다(탐색으로 확정, 2026-07-30). 내부색(밝음)과 외곽선(검음)을
+ 뚜렷이 갈라 소실을 색으로 검출한다."""
+ pad = 4
+ w = 26
+ im = Image.new("RGBA", (w, 30 + 2 * pad), (0, 0, 0, 0))
+ px = im.load()
+ cx = w // 2
+ for y in range(30):
+ bw = 10 if y < 12 else 21 # 좁은 머리(병목) → 넓은 몸통
+ for x in range(cx - bw // 2, cx - bw // 2 + bw):
+ px[x, y + pad] = (210, 185, 120, 255) # 밝은 내부
+ edge = []
+ for y in range(im.size[1]):
+ for x in range(w):
+ if px[x, y][3] == 0:
+ continue
+ for nx, ny in ((x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)):
+ if nx < 0 or ny < 0 or nx >= w or ny >= im.size[1] or px[nx, ny][3] == 0:
+ edge.append((x, y))
+ break
+ for x, y in edge:
+ px[x, y] = (0, 0, 0, 255) # 1px 검은 외곽선
+ return im
+
+
+def test_side_outline_survives_every_phase() -> None:
+ """가로 축소 위상에서도 좌우 1px 외곽선이 사라지지 않는다 (발끝 플리커 회귀, 2026-07-30).
+
+ forward 밀도매핑이 축소(날숨) 위상에서 실루엣 양끝 열을 통째로 떨궈, 큐레이터
+ 미리보기·굽기 모두에서 발끝 검은 외곽선 1px 가 위상마다 사라졌다 나타났다 했다
+ (실측: 문어 synthetic silhouette idle y25~y28). `_warp` 의 외곽선 보존이 이 행의 최말단 불투명
+ 소스 열(= 외곽선)을 출력 양끝 불투명 픽셀에 실어 막는다. 실루엣 끝에 내부색(밝음)이
+ 노출되면 = 외곽선이 떨어진 것이므로, 전 위상 우측 끝이 어두워야 한다."""
+ src = _small_outlined()
+ cfg = dict(CFG)
+ cfg["depth"] = 0.08
+ cfg["breaths"] = 3
+ cfg["anatomy"] = freeze_anatomy(src, cfg, _key())
+ anat = resolve_anatomy(src, cfg)
+ dark = lambda p: (0.299 * p[0] + 0.587 * p[1] + 0.114 * p[2]) < 96
+ dropped = []
+ for i in range(24):
+ phase = i / 24
+ frame = phase_frame(src, cfg, phase, anat)
+ px = frame.load()
+ w, h = frame.size
+ for y in range(h):
+ rm = next((x for x in range(w - 1, -1, -1) if px[x, y][3] >= 128), None)
+ if rm is not None and not dark(px[rm, y]):
+ dropped.append((round(phase, 3), y, rm))
+ assert not dropped, (
+ f"실루엣 우측 끝에 내부색 노출(1px 외곽선 소실) {len(dropped)}건 — "
+ f"발끝 플리커 회귀: {dropped[:8]}")
+
+
+def test_region_overrides_change_the_anatomy_and_the_bake() -> None:
+ """axis_x/torso_half 사람 오버라이드 (큐레이터 영역 UI, 2026-07-30).
+
+ rigid_row 와 같은 지위: 사이드카의 의도 입력이고 anatomy 는 파생 캐시다.
+ (a) analyze 가 오버라이드를 값으로 받아들이고 관측 warning 을 남긴다,
+ (b) 범위 밖은 조용히 깎지 않고 거부한다,
+ (c) torso_half 를 좁히면 부속 보호가 실제로 걸려 굽기 출력이 달라진다."""
+ src = _winged()
+ auto = analyze(src)
+ manual = analyze(src, axis_x=auto.axis_x + 3, torso_half=5)
+ assert manual.axis_x == auto.axis_x + 3
+ assert manual.torso_half == 5
+ assert any("axis-x-override" in w for w in manual.warnings)
+ assert any("torso-half-override" in w for w in manual.warnings)
+
+ with pytest.raises(SystemExit):
+ analyze(src, axis_x=auto.width + 10)
+ with pytest.raises(SystemExit):
+ analyze(src, torso_half=0)
+
+ # (c) 날개 픽스처: torso_half 를 좁히면 protect() 가 더 넓게 걸려 출력이 달라진다.
+ # 기본 depth 는 정수 반올림에 묻힐 수 있어 크게 잡고 전 위상에서 차이를 찾는다.
+ cfg = dict(CFG)
+ cfg["depth"] = 0.15
+ cfg["anatomy"] = freeze_anatomy(src, cfg, _key())
+ narrow = {**cfg, "torso_half": 4,
+ "anatomy": freeze_anatomy(src, {**cfg, "torso_half": 4}, _key())}
+ assert any(phase_frame(src, cfg, i / 12).tobytes() != phase_frame(src, narrow, i / 12).tobytes()
+ for i in range(12)), "torso_half 오버라이드가 굽기에 아무 효과가 없다"
+
+
+def test_no_intermittent_dark_edge_protrusion() -> None:
+ """변형 프레임의 좌우 실루엣 끝에 1px 어두운 돌출점이 남지 않는다 (안쪽점 기준, 2026-07-30).
+
+ 바깥점 기준 다듬기(초기 구현)는 2점 지점의 바깥점을 선으로 남겨, 이웃 행들과 1px
+ 어긋난 돌출점이 위상마다 나타났다 사라졌다 했다 (maintainer 실기기 판정: "안쪽 검은점
+ 기준이 더 정확하다"). 지금은 바깥 복제분을 제거하고 안쪽 자리에 선을 그린다 —
+ 위아래 행 끝보다 바깥으로 튄 어두운 끝점이 0 이어야 한다. 원본에 없던 돌출만
+ 문제이므로 원본 돌출 수를 기준치로 삼는다."""
+ src = _small_outlined()
+ cfg = dict(CFG)
+ cfg["depth"] = 0.08
+ cfg["breaths"] = 3
+ cfg["anatomy"] = freeze_anatomy(src, cfg, _key())
+ anat = resolve_anatomy(src, cfg)
+
+ def protrusions(frame):
+ px = frame.load()
+ w, h = frame.size
+ dark = lambda p: p[3] >= 128 and (0.299 * p[0] + 0.587 * p[1] + 0.114 * p[2]) < 96
+ opaque = lambda p: p[3] >= 128
+ lo, hi = {}, {}
+ for y in range(h):
+ xs = [x for x in range(w) if opaque(px[x, y])]
+ if xs:
+ lo[y], hi[y] = xs[0], xs[-1]
+ n = 0
+ for y, m in lo.items():
+ if y - 1 in lo and y + 1 in lo and m < lo[y - 1] and m < lo[y + 1] and dark(px[m, y]):
+ n += 1
+ for y, r in hi.items():
+ if y - 1 in hi and y + 1 in hi and r > hi[y - 1] and r > hi[y + 1] and dark(px[r, y]):
+ n += 1
+ return n
+
+ base = protrusions(src)
+ for i in range(24):
+ frame = phase_frame(src, cfg, i / 24, anat)
+ got = protrusions(frame)
+ assert got <= base, (
+ f"위상 {i / 24:.3f}: 어두운 끝 돌출점 {got} > 원본 {base} — 간헐 2줄/돌출점 회귀")
+
+
+def test_thinning_normalizes_warp_doubled_outline(monkeypatch) -> None:
+ """워프가 복제로 두껍게 만든 외곽선을 다듬기가 1px 로 정규화한다 (볼 2줄 회귀, 2026-07-30).
+
+ 세로/가로 정수 복제가 외곽선을 국소적으로 2px 두께로 만들어 "가로 2줄 검은선" 으로
+ 읽혔다 (실측: 문어 idle 왼쪽 볼, maintainer 발견). `_thin_outline_1px` 가 변형 프레임의
+ 두꺼워진 구간을 내부색으로 되돌린다. 외곽선 경로가 꺾이는 정당한 모서리(실루엣 끝
+ 픽셀)는 보호되므로 "모서리 0" 을 단정하지 않는다 — 다듬기 유/무를 같은 위상에서
+ 비교해 (a) 있으면 항상 적거나 같고 (b) 최소 한 위상에서 실제로 줄이는 것을 단정한다.
+ 변형 0 프레임은 다듬지 않으므로 원본 동일 계약과 공존한다 (zero-strain 테스트가 지킴)."""
+ import sprite_gen.effects.breathe as breathe_mod
+
+ src = _small_outlined()
+ cfg = dict(CFG)
+ cfg["depth"] = 0.08
+ cfg["breaths"] = 3
+ cfg["anatomy"] = freeze_anatomy(src, cfg, _key())
+ anat = resolve_anatomy(src, cfg)
+
+ def non_end_dark(frame):
+ """실루엣 끝(외곽선의 정당한 경로)이 아닌 위치의 어두운 픽셀 수.
+
+ 1px 외곽선의 픽셀은 전부 행 끝이거나 열 끝이다. 워프 복제로 두꺼워진 안쪽
+ 분(가로 2줄의 두 번째 줄)만 이 메트릭에 잡힌다. 눈처럼 원래 내부에 있는
+ 어두운 특징도 잡히지만 다듬기 유/무 양쪽에 똑같이 들어가 상쇄된다. 다듬기는
+ 어두운 픽셀을 내부색으로 바꾸기만 하고 알파는 불변이라, 이 메트릭은 다듬기로
+ 단조 감소하며 with/without 프레임의 끝 집합이 동일해 비교가 정확하다."""
+ px = frame.load()
+ w, h = frame.size
+ dark = lambda p: p[3] >= 128 and (0.299 * p[0] + 0.587 * p[1] + 0.114 * p[2]) < 96
+ opaque = lambda p: p[3] >= 128
+ ends = set()
+ for y in range(h):
+ xs = [x for x in range(w) if opaque(px[x, y])]
+ if xs:
+ ends.add((xs[0], y))
+ ends.add((xs[-1], y))
+ for x in range(w):
+ ys = [y for y in range(h) if opaque(px[x, y])]
+ if ys:
+ ends.add((x, ys[0]))
+ ends.add((x, ys[-1]))
+ return sum(1 for y in range(h) for x in range(w)
+ if dark(px[x, y]) and (x, y) not in ends)
+
+ with_thin = [non_end_dark(phase_frame(src, cfg, i / 24, anat)) for i in range(24)]
+ monkeypatch.setattr(breathe_mod, "_thin_outline_1px", lambda out: None)
+ without = [non_end_dark(phase_frame(src, cfg, i / 24, anat)) for i in range(24)]
+ monkeypatch.undo()
+
+ for i, (a, b) in enumerate(zip(with_thin, without)):
+ assert a <= b, f"위상 {i / 24:.3f}: 다듬기가 두꺼운 구간을 오히려 늘렸다 ({a} > {b})"
+ assert sum(with_thin) < sum(without), (
+ f"다듬기가 어떤 위상에서도 두꺼운 외곽선을 줄이지 못했다 "
+ f"(with={sum(with_thin)}, without={sum(without)}) — 볼 2줄 회귀")
+
+
+def test_the_body_axis_column_is_a_fixed_point() -> None:
+ """어떤 위상에서도 몸통 축 열은 제자리 — 이게 좌우 지터를 구조적으로 막는다."""
+ src = _humanoid()
+ anat = analyze(src)
+ cfg = dict(CFG)
+ cfg["anatomy"] = freeze_anatomy(src, cfg, _key())
+ box = solid_alpha_bbox(src)
+ axis_col = box[0] + anat.axis_x
+ for i in range(12):
+ frame = phase_frame(src, cfg, i / 12)
+ fb = solid_alpha_bbox(frame)
+ # 축 열의 콘텐츠가 그 프레임 안에서도 축 열에 그대로 있어야 한다: 소스 축 열의
+ # 불투명 span 이 출력 축 열에서도 연속으로 살아 있고, 좌우 이웃 열로 새지 않는다.
+ col = [frame.getpixel((axis_col, y))[3] >= 128 for y in range(fb[1], fb[3])]
+ assert sum(col) == fb[3] - fb[1], f"위상 {i}: 축 열에 구멍 — 열이 통째로 밀렸다"
+ left_edge = solid_alpha_bbox(frame)[0]
+ assert left_edge <= axis_col < solid_alpha_bbox(frame)[2], f"위상 {i}: 축이 실루엣 밖"
+
+
+# ── 2. 발바닥 고정 · 루프 길이 불변 ─────────────────────────────────
+
+def test_feet_stay_planted_and_loop_length_is_preserved() -> None:
+ src = _humanoid()
+ baseline = solid_alpha_bbox(src)[3]
+ frames, phases = _frames(src, count=12)
+ assert len(frames) == 12 and len(phases) == 12
+ for i, frame in enumerate(frames):
+ assert solid_alpha_bbox(frame)[3] == baseline, f"frame {i}: 발이 떴다"
+
+
+def test_breathing_actually_moves_the_body() -> None:
+ src = _humanoid()
+ frames, _ = _frames(src, count=12)
+ heights = {solid_alpha_bbox(f)[3] - solid_alpha_bbox(f)[1] for f in frames}
+ assert len(heights) > 1, "봉투 워프가 높이를 전혀 안 바꿨다"
+
+
+# ── 3. 부속은 밀리기만 하고 늘어나지 않는다 ─────────────────────────
+
+def test_appendage_is_pushed_not_stretched() -> None:
+ src = _winged()
+ anat = analyze(src)
+ assert anat.has_appendage, "테스트 도형은 부속이 있어야 한다"
+ frames, _ = _frames(src, count=12)
+ spans = [solid_alpha_bbox(f)[2] - solid_alpha_bbox(f)[0] for f in frames]
+ body_h = anat.height
+ # 날개 전체 폭 변화가 몸통이 부푸는 양(depth*기준높이)을 크게 넘지 않아야 한다 —
+ # 넘으면 부속이 몸통과 같은 배율로 늘어난 것이다.
+ assert max(spans) - min(spans) <= 2 * round(DEFAULT_DEPTH * body_h) + 2
+
+
+# ── 4. 정규화 기준 분기 ─────────────────────────────────────────────
+
+def test_amplitude_basis_uses_neck_only_when_the_bottleneck_is_real() -> None:
+ real = analyze(_humanoid())
+ assert real.neck_source == "bottleneck"
+ assert real.basis_row == real.neck_row
+
+ anat = analyze(_dome())
+ assert anat.neck_source == "shoulder-gradient"
+ assert anat.basis_row == anat.rigid_row, "병목이 가짜면 기준은 강체 경계여야 한다"
+ assert any("neck-absent" in w for w in anat.warnings), "대체 판정은 관측 가능해야 한다"
+ # 기준이 목이었다면 정규화가 폭주했을 것 — 상한 안에 들어와야 한다
+ assert row_strain(anat, DEFAULT_DEPTH) <= MAX_ROW_STRAIN
+
+
+def test_row_strain_over_the_cap_raises_instead_of_clamping() -> None:
+ src = _humanoid()
+ anat = analyze(src)
+ depth = DEFAULT_DEPTH
+ while row_strain(anat, depth) <= MAX_ROW_STRAIN:
+ depth *= 2
+ assert depth < 10, "상한을 넘길 수 있어야 한다"
+ with pytest.raises(SystemExit) as err:
+ phase_frame(src, {**CFG, "depth": depth}, 0.25)
+ assert "행당 변형" in str(err.value)
+
+
+# ── 5. 수동 override 와 자가 복구 ───────────────────────────────────
+
+def test_manual_rigid_row_overrides_detection_and_is_observable() -> None:
+ src = _humanoid()
+ auto = analyze(src)
+ manual = analyze(src, rigid_row=auto.rigid_row + 6)
+ assert manual.rigid_row == auto.rigid_row + 6
+ assert manual.rigid_source == "manual"
+ assert any("rigid-row-override" in w for w in manual.warnings)
+
+
+def test_stale_frozen_anatomy_self_heals() -> None:
+ src = _humanoid()
+ cfg = dict(CFG)
+ cfg["anatomy"] = freeze_anatomy(src, cfg, _key())
+ other = _winged()
+ assert _warp_inputs(analyze(src)) != _warp_inputs(analyze(other)), \
+ "픽스처 쌍이 워프 입력을 안 바꾸면 이 테스트는 아무것도 보증하지 못한다"
+
+ # 다른 스프라이트에 옛 해부 결과를 물려도 **그 프레임에서 다시 잰 값**으로 구워야 한다.
+ # 크기·bbox 만 보면 낡은 해부로 구워도 통과한다 — 실제로 쓴 해부를 픽셀로 대조한다.
+ healed = phase_frame(other, cfg, 0.25)
+ want = phase_frame(other, {k: v for k, v in cfg.items() if k != "anatomy"}, 0.25)
+ assert healed.tobytes() == want.tobytes(), \
+ "낡은 해부가 굽기로 샜다 — 다른 스프라이트의 경계로 구웠다"
+ stale = phase_frame(src, cfg, 0.25)
+ assert healed.tobytes() != stale.tobytes(), \
+ "픽스처가 같은 그림을 내면 위 단언이 공허하다"
+
+
+# ── 6. 위상 시퀀스 ──────────────────────────────────────────────────
+
+def test_phase_pattern_fits_requested_breaths_into_the_loop() -> None:
+ for seq_len, breaths in ((12, 1), (12, 2), (10, 3), (7, 2)):
+ pattern = fit_breathe_pattern(seq_len, {"breaths": breaths})
+ assert len(pattern) == seq_len
+ assert all(0.0 <= p < 1.0 for p in pattern)
+ assert pattern[0] == 0.0
+ assert fitted_breath_count(seq_len, {"breaths": breaths}) == breaths
+
+
+def test_wave_is_loop_closed() -> None:
+ assert wave(0.0) == pytest.approx(wave(1.0), abs=1e-9)
+
+
+def test_envelope_is_zero_above_the_rigid_boundary() -> None:
+ anat = analyze(_humanoid())
+ env, _ = envelope(anat)
+ band = max(1.5, TAPER * anat.height) / anat.height
+ above = anat.rigid_u + band + 1e-6
+ assert env(min(1.0, above)) == pytest.approx(0.0, abs=1e-12)
+ assert env(0.0) == pytest.approx(0.0, abs=1e-12), "발바닥도 고정"
+
+
+def test_smoothness_hint_scales_with_breath_count() -> None:
+ assert recommended_breathe_frames({"breaths": 1}) == SMOOTH_CYCLE_FRAMES
+ assert recommended_breathe_frames({"breaths": 3}) == 3 * SMOOTH_CYCLE_FRAMES
+ assert breathe_reads_smoothly(SMOOTH_CYCLE_FRAMES, {"breaths": 1}) is True
+ assert breathe_reads_smoothly(SMOOTH_CYCLE_FRAMES - 1, {"breaths": 1}) is False
+
+
+# ── 7. 폐기된 분할선 스키마는 요란하게 거부된다 ─────────────────────
+
[email protected]("retired", [{"splits": [0.55]}, {"amplitude": 2}, {"subpixel": True}])
+def test_retired_split_schema_is_rejected_loudly(retired: dict) -> None:
+ curation = {"states": {"idle": {"breathe": {**retired, "breaths": 1}}}}
+ with pytest.raises(SystemExit) as err:
+ state_breathe(curation, "idle")
+ message = str(err.value)
+ assert "폐기된" in message
+ assert "migrate-breathe" in message, "마이그레이션 경로를 알려줘야 한다"
+
+
+def test_new_schema_normalizes_within_range() -> None:
+ cfg = state_breathe({"states": {"idle": {"breathe": {"depth": 0.08, "breaths": 3}}}}, "idle")
+ assert cfg == {"depth": 0.08, "depth_x": None, "breaths": 3, "lag": 0.10,
+ "rigid_row": None, "axis_x": None, "torso_half": None, "anatomy": None}
+
+
+def test_clipping_the_cell_raises_instead_of_cropping_the_head() -> None:
+ """여백이 없어 늘어난 프레임이 셀 밖으로 나가면 조용히 자르지 않는다."""
+ tight = _humanoid().crop(solid_alpha_bbox(_humanoid())) # 여백 0
+ cfg = dict(CFG)
+ cfg["anatomy"] = freeze_anatomy(tight, cfg, _key())
+ with pytest.raises(SystemExit) as err:
+ bake_breathe_sequence([tight] * 12, cfg)
+ assert "셀 밖으로" in str(err.value)
+
+
+# ── 8. 얼굴이 몸통에 있는 실루엣 (목 없음) ─────────────────────────
+
+def test_face_on_the_body_pushes_the_boundary_below_the_face() -> None:
+ """슬라임형: 목이 없고 얼굴이 몸통 한가운데다.
+
+ 목만 보면 경계가 얼굴 위에 걸려 눈 행이 변형 구간에 들어간다. 얼굴 검출이
+ 경계를 얼굴 아래로 내려야 표정이 살아남는다."""
+ slime = _dome(with_face=True)
+ anat = analyze(slime)
+ assert anat.neck_source == "shoulder-gradient", "돔에는 병목이 없어야 한다"
+ assert anat.face is not None, "대칭 눈쌍을 찾아야 한다"
+ assert anat.rigid_row > anat.face[0], "경계가 얼굴 위에 걸리면 안 된다"
+ assert anat.rigid_source == "face"
+ assert anat.basis_row == anat.rigid_row
+
+ frames, _ = _frames(slime)
+ band = int(max(1.5, TAPER * anat.height)) + 1
+ rigid_h = anat.rigid_row - band
+ # 눈(픽스처 44~51행)이 강체 구간 안이어야 한다. face[1] 아래쪽은 입 여유분이라
+ # 테이퍼가 걸쳐도 된다 — 지켜야 하는 건 표정을 만드는 도트지 여유분이 아니다.
+ assert rigid_h > 51, f"눈이 변형 구간에 들어갔다 (강체 {rigid_h}행까지)"
+ ref = frames[0]
+ top = solid_alpha_bbox(ref)[1]
+ expect = ref.crop((0, top, ref.width, top + rigid_h)).tobytes()
+ for i, frame in enumerate(frames[1:], 1):
+ t = solid_alpha_bbox(frame)[1]
+ assert frame.crop((0, t, frame.width, t + rigid_h)).tobytes() == expect, \
+ f"frame {i}: 얼굴이 흔들렸다"
+
+
+def test_face_detection_ignores_a_single_eye_paired_with_a_centred_mouth() -> None:
+ """눈 후보는 축을 **사이에 두고** 있어야 한다.
+
+ 이 제약이 없으면 한쪽 눈과 축 위의 입이 짝으로 잡혀 얼굴 구간이 입 아래까지
+ 늘어난다 (실측: 버섯에서 경계가 57 -> 64 로 밀렸다)."""
+ im = _dome(with_face=True)
+ for y in range(66, 72): # 축 위 입 (눈보다 아래, 눈과 안 닿게)
+ for x in range(37, 44):
+ im.putpixel((x, y), (8, 20, 14, 255))
+ anat = analyze(im)
+ assert anat.face is not None
+ # 눈쌍(44~52)이 이겨야 한다 — 입(56~62)까지 삼키면 bottom 이 훨씬 아래로 간다
+ assert anat.face[0] < 56, f"눈쌍이 아니라 다른 짝이 이겼다: {anat.face}"
+
+
+# ── 9. Validator round 2 회귀 ───────────────────────────────────────
+
+def test_repeated_phases_are_bit_identical_so_atlas_cells_can_be_shared() -> None:
+ """수학적으로 같은 위상은 **같은 double** 이어야 한다.
+
+ 아틀라스는 (프레임, 위상)을 칸 키로 써서 같은 그림을 한 칸만 굽는다. 위상을
+ `(i*breaths/seq_len) % 1.0` 로 계산하면 표현 노이즈로 같은 위상이 갈려서
+ 바이트 동일한 칸이 중복 구워진다 (실측 18슬롯 3호흡: 유니크 6 -> 14,
+ 시트 폭 576 -> 1344, validator 검증 2026-07-25)."""
+ for seq_len, breaths in ((18, 3), (12, 2), (12, 4), (20, 5)):
+ pattern = fit_breathe_pattern(seq_len, {"breaths": breaths})
+ exact = {(i * breaths) % seq_len for i in range(seq_len)}
+ assert len(set(pattern)) == len(exact), \
+ f"{seq_len}슬롯 {breaths}호흡: 유니크 위상 {len(set(pattern))} != 수학적 {len(exact)}"
+ # 같은 나머지를 갖는 슬롯끼리 실제로 같은 값인지
+ for i in range(seq_len):
+ j = i + seq_len // breaths
+ if j < seq_len and (i * breaths) % seq_len == (j * breaths) % seq_len:
+ assert pattern[i] == pattern[j], f"슬롯 {i}/{j}: 같은 위상인데 double 이 다르다"
+
+
+def test_repeated_phases_render_byte_identical_frames() -> None:
+ """위상이 같으면 구워진 픽셀도 같아야 칸 공유가 정당하다."""
+ src = _humanoid()
+ cfg = dict(CFG)
+ cfg["anatomy"] = freeze_anatomy(src, cfg, _key())
+ frames, phases = bake_breathe_sequence([src] * 18, {**cfg, "breaths": 3})
+ by_phase: dict[float, bytes] = {}
+ for frame, phase in zip(frames, phases):
+ data = frame.tobytes()
+ if phase in by_phase:
+ assert by_phase[phase] == data, f"위상 {phase}: 같은 위상인데 픽셀이 다르다"
+ by_phase[phase] = data
+ assert len(by_phase) == 6, f"18슬롯 3호흡의 유니크 위상은 6이어야 한다 (got {len(by_phase)})"
+
+
+def test_manual_rigid_row_beats_a_frozen_anatomy() -> None:
+ """`rigid_row` 는 사람의 의도(입력)고 `anatomy` 는 파생 캐시다 — 의도가 이긴다.
+
+ frozen 분기가 `cfg["rigid_row"]` 를 안 보면 사람이 고친 숫자가 조용히 버려진다
+ (실측: cfg 33 을 줘도 얼린 23 이 구워지고 경고도 없었다, validator 검증 2026-07-25)."""
+ src = _humanoid()
+ cfg = dict(CFG)
+ cfg["anatomy"] = freeze_anatomy(src, cfg, _key())
+ frozen_row = cfg["anatomy"]["rigid_row"]
+
+ same = resolve_anatomy(src, cfg)
+ assert same.rigid_row == frozen_row, "override 없으면 같은 프레임에서 같은 값이 나온다"
+
+ want = frozen_row + 10
+ anat = resolve_anatomy(src, {**cfg, "rigid_row": want})
+ assert anat.rigid_row == want, "사람이 준 값이 얼린 값에 먹혔다"
+ assert anat.rigid_source == "manual"
+ assert any("rigid-row-override" in w for w in anat.warnings)
+
+ # **거짓말하는 캐시가 굽기로 새지 않는다.** 굽기는 진짜 프레임을 손에 들고 있으니
+ # 재는 게 언제나 옳고, 얼린 값은 웹뷰가 그림을 그리려고 들고 있는 캐시일 뿐이다.
+ lying = {**cfg, "anatomy": {**cfg["anatomy"], "rigid_row": frozen_row + 7,
+ "axis_x": cfg["anatomy"]["axis_x"] + 5}}
+ assert resolve_anatomy(src, lying).rigid_row == frozen_row, \
+ "사이드카 캐시가 굽기 값을 밀어냈다 — 캐시는 진실이 아니다"
+
+
+def test_the_bake_re_measures_alpha_invariant_paint() -> None:
+ """불투명 픽셀 위에 눈을 덧칠하면 굽기가 **그 얼굴을 찾아** 경계를 내린다.
+
+ 이건 큐레이터 픽셀 편집기의 문서화된 기능이고 알파가 1바이트도 안 바뀐다. 예전 설계는
+ "얼린 해부를 믿을지" 를 프레임 RGBA 해시로 판정했는데, 그 해시가 웹뷰와 영구 불일치를
+ 만드는 원흉이었다 (BICUBIC vs NEAREST). 지금은 굽기가 **캐시를 아예 안 믿고** 매번
+ 자기 기준 프레임에서 재므로, 판정 자체가 필요 없다 — 그래서 이 테스트는 지문이 아니라
+ 구워진 해부를 본다.
+
+ 사용자 쪽 사이드카 캐시가 낡았는지는 `anatomy_report(...)["sidecar_drift"]` 가 값으로
+ 보고하고, 웹뷰의 미리보기 신선도는 `reference_key`(입력 기반)가 판정한다."""
+ plain = _dome(with_face=False)
+ painted = _dome(with_face=True) # 알파 동일, RGB 만 다름
+ assert plain.getchannel("A").tobytes() == painted.getchannel("A").tobytes(), \
+ "이 픽스처 쌍은 알파가 같아야 의미가 있다"
+
+ cfg = dict(CFG)
+ cfg["anatomy"] = freeze_anatomy(plain, cfg, _key()) # 얼굴 없는 상태로 확정
+ anat = resolve_anatomy(painted, cfg) # 그 뒤 눈을 덧칠
+ assert anat.face is not None and anat.rigid_source == "face", \
+ "덧칠된 얼굴을 못 찾았다 — 굽기가 낡은 경계로 굽는다"
+
+ report = anatomy_report([painted], cfg)
+ assert report["matches_sidecar"] is False, "사이드카가 낡았는데 보고가 조용하다"
+ assert "rigid_row" in (report["sidecar_drift"] or {}), \
+ "무엇이 어긋났는지 값으로 보고해야 한다 (원칙 6)"
+
+
+def test_out_of_range_values_are_refused_instead_of_clamped() -> None:
+ """범위 밖 값은 조용히 깎지 않는다.
+
+ 클램프가 파이썬에만 있어서 미러·배지·문서가 굽기와 다른 값을 말했다 (validator 실측
+ 2026-07-25: `breaths 12` 를 8 로 깎는데 프리뷰·필름스트립·WebM 은 12회 숨쉬고
+ 배지는 "적용 12회" 라고 띄웠다). 폐기 키는 요란하게 거부하면서 값 범위만 조용한 것도
+ 계약이 어긋난다 — 한쪽으로 정했다."""
+ from sprite_gen.curate.curation import (BREATHE_BREATHS_MAX, BREATHE_DEPTH_MAX,
+ BREATHE_LAG_MAX, state_breathe)
+ for key, over in (("depth", BREATHE_DEPTH_MAX + 0.01),
+ ("breaths", BREATHE_BREATHS_MAX + 1),
+ ("lag", BREATHE_LAG_MAX + 0.01)):
+ with pytest.raises(SystemExit) as err:
+ state_breathe({"states": {"idle": {"breathe": {key: over}}}}, "idle")
+ assert key in str(err.value) and "범위" in str(err.value)
+ # 경계값은 통과한다
+ ok = state_breathe({"states": {"idle": {"breathe": {
+ "depth": BREATHE_DEPTH_MAX, "breaths": BREATHE_BREATHS_MAX, "lag": BREATHE_LAG_MAX}}}}, "idle")
+ assert ok["breaths"] == BREATHE_BREATHS_MAX
+
+
+def test_the_curator_ui_cap_matches_the_schema_bound() -> None:
+ """UI 컨트롤 상한과 스키마 상한이 갈리면 UI 가 만든 값을 굽기가 거부한다."""
+ from sprite_gen.curate.curation import BREATHE_BREATHS_MAX, BREATHE_DEPTH_MAX, BREATHE_LAG_MAX
+ import re
+ from sprite_gen.serve.serve_curation import CURATOR_DIR
+ js = (CURATOR_DIR / "src" / "breathe.js").read_text(encoding="utf-8")
+ for name, want in (("BREATHE_BREATHS_MAX", BREATHE_BREATHS_MAX),
+ ("BREATHE_DEPTH_MAX", BREATHE_DEPTH_MAX),
+ ("BREATHE_LAG_MAX", BREATHE_LAG_MAX)):
+ # 값을 숫자로 파싱해서 비교한다 — 문자열 포함 검사는 0.2 가 0.25 에도 걸린다
+ m = re.search(rf"^const {name} = ([0-9.]+);", js, re.M)
+ assert m, f"{name} 미러 상수가 breathe.js 에 없다"
+ assert float(m.group(1)) == float(want), \
+ f"{name} 미러 {m.group(1)} != 파이썬 {want} — UI 가 만든 값을 굽기가 거부한다"
+
+
+def _reaches_further(base):
+ """같은 줄의 다른 프레임 — **워프가 실제로 쓰는 값**이 갈리게 만든다.
+
+ round-5 에 넣은 첫 판은 RGB 만 덧칠해서 `face`/`warnings` 만 바뀌고 워프 입력
+ (`axis_x`·`torso_half`·`max_half`)은 그대로였다. 그래서 프레임별 재검출로 되돌리는
+ 변이를 넣어도 출력이 바이트 동일해 **테스트가 안 물었다** (validator note 2026-07-25).
+ 팔을 뻗으면 `axis_x` 13→14, `max_half` 14→19 로 워프 입력이 실제로 갈린다."""
+ out = base.copy()
+ px = out.load()
+ box = solid_alpha_bbox(out)
+ for y in range(box[1] + 40, box[1] + 50):
+ for x in range(box[2], min(out.width, box[2] + 6)):
+ px[x, y] = (90, 60, 30, 255)
+ return out
+
+
+def _warp_inputs(anat):
+ return (anat.rigid_row, anat.basis_row, anat.axis_x, anat.torso_half, anat.max_half)
+
+
+def test_row_anatomy_is_shared_across_the_sequence() -> None:
+ """줄 전체가 해부 한 벌을 쓴다 — 프레임마다 다시 재면 경계·축이 흔들린다.
+
+ 경계가 프레임마다 움직이면 '강체 구간' 이 프레임 간 같은 구간이 아니게 되고,
+ 사이드카 한 벌로 그리는 프리뷰와도 갈린다 (validator 실측 2026-07-25)."""
+ base = _humanoid()
+ other = _reaches_further(base)
+ assert _warp_inputs(analyze(base)) != _warp_inputs(analyze(other)), \
+ "픽스처 쌍이 워프 입력을 안 바꾸면 이 테스트는 아무것도 보증하지 못한다"
+
+ cfg = dict(CFG)
+ cfg["anatomy"] = freeze_anatomy(base, cfg, _key())
+ seq = [base, other, base, other]
+ frames, phases = bake_breathe_sequence(seq, cfg)
+ anat = resolve_anatomy(base, cfg)
+
+ diverged = 0
+ for i, frame in enumerate(frames):
+ want = phase_frame(seq[i], cfg, phases[i], anat)
+ assert frame.tobytes() == want.tobytes(), \
+ f"frame {i}: 줄 해부 한 벌로 구운 것과 다르다 — 프레임별 재검출이 되살아났다"
+ per_frame = phase_frame(seq[i], cfg, phases[i]) # 프레임 자기 해부로 구운 것
+ if per_frame.tobytes() != frame.tobytes():
+ diverged += 1
+ assert diverged, ("어떤 프레임도 자기 해부와 줄 해부의 출력이 다르지 않다 — "
+ "이 픽스처로는 변이가 안 잡힌다 (그물이 이름값을 못 한다)")
+
+ report = anatomy_report(seq, cfg)
+ assert "rigid_row_varies" not in report, "경계가 프레임마다 달라질 수 있는 표현이 남아 있다"
+ assert report["anatomy"]["rigid_row"] == anat.rigid_row
+
+
+def test_a_non_integer_breaths_is_refused_not_truncated() -> None:
+ """비정수는 조용히 깎지 않는다 (round-7 R2).
+
+ `int(2.7) -> 2` 로 되돌려도 전체 스위트가 통과했다 — 그물이 없었다
+ (validator 변이 검증 2026-07-26). 파이썬이 버리고 미러가 반올림하면 굽기 2회 /
+ 프리뷰 3회가 되고, 첫 autosave 가 사이드카를 반올림값으로 덮는다."""
+ from sprite_gen.curate.curation import state_breathe
+ for value in (2.7, "3.5", 1.0001):
+ with pytest.raises(SystemExit) as err:
+ state_breathe({"states": {"idle": {"breathe": {"depth": 0.06, "breaths": value}}}}, "idle")
+ assert "정수가 아니다" in str(err.value), f"{value!r}: 정수 계약이 아닌 사유로 죽었다"
+ # 정수로 표현되는 실수는 받는다 (3.0 == 3)
+ assert state_breathe({"states": {"idle": {"breathe": {"depth": 0.06, "breaths": 3.0}}}},
+ "idle")["breaths"] == 3
+
+
+# ── 7. 가로/세로 진폭 분리 + 수동 밴드 보호 앵커 (2026-07-30) ───────
+
+def test_depth_x_absent_is_byte_identical_to_depth_x_equal_depth() -> None:
+ """레거시 계약: depth_x 부재 = depth 따름. 명시 depth_x==depth 와 바이트 동일해야
+ 분리 도입이 기존 굽기를 1픽셀도 안 바꿨다는 증명이 된다 (순수 확장)."""
+ src = _dome()
+ base, _ = _frames(src, count=12)
+ explicit, _ = _frames(src, count=12, cfg={**CFG, "depth_x": CFG["depth"]})
+ assert [f.tobytes() for f in base] == [f.tobytes() for f in explicit]
+
+
+def test_depth_x_zero_keeps_horizontal_extent() -> None:
+ """depth_x=0 = 가로 사상 전 위상 항등 — 가로 bbox 가 움직이지 않는다."""
+ src = _dome()
+ x0, _, x1, _ = solid_alpha_bbox(src)
+ frames, _ = _frames(src, count=12, cfg={**CFG, "depth": 0.10, "depth_x": 0.0})
+ for f in frames:
+ b = solid_alpha_bbox(f)
+ assert (b[0], b[2]) == (x0, x1), "가로 항등인데 가로 bbox 가 움직였다"
+ # 대조군: depth_x 가 depth 를 따르면 같은 설정에서 출력이 실제로 달라야 한다
+ moving, _ = _frames(src, count=12, cfg={**CFG, "depth": 0.10})
+ assert any(a.tobytes() != b.tobytes() for a, b in zip(frames, moving)), \
+ "depth_x=0 과 따름이 같은 그림 — 가로 성분이 아예 안 굽는다"
+
+
+def test_depth_x_does_not_leak_into_the_vertical_axis() -> None:
+ """축 독립: `depth_x` 를 바꿔도 세로 운동(정수리 궤적)은 한 톨도 안 바뀐다.
+
+ 분리의 요점은 두 축이 **스칼라만 다르고 나머지를 공유**하는 것이라, 세로 누적에
+ 가로 진폭이 섞여도 겉보기 출력은 계속 그럴듯하다 — 변이 검증 2026-07-31 에서
+ 세로 누적을 `dx_amp` 로 바꾼 mutant 가 기존 depth_x 그물 3개를 전부 통과했다."""
+ src = _humanoid()
+
+ def top_track(dx):
+ cfg = {**CFG, "depth": 0.10, "depth_x": dx}
+ frames, _ = _frames(src, count=12, cfg=cfg)
+ return [solid_alpha_bbox(f)[1] for f in frames]
+
+ baseline = top_track(0.10)
+ for dx in (0.0, 0.03, 0.12):
+ assert top_track(dx) == baseline, (
+ f"depth_x={dx} 가 세로 궤적을 바꿨다 — 가로 진폭이 세로 축으로 샌다")
+
+
+def test_manual_band_anchors_protection_to_the_band() -> None:
+ """수동 밴드는 무조건 켜지고 램프가 밴드에 앵커된다 — 블롭에서 밴드 조정이
+ 무력했던 버그의 회귀 그물 (실측 2026-07-30 synthetic silhouette: 밴드 12→4 무변화)."""
+ from sprite_gen.effects.breathe import protect
+ src = _humanoid()
+ auto = analyze(src)
+ assert not auto.has_appendage, "휴머노이드는 부속이 없어야 한다 (자동 경로 무보호 전제)"
+ assert auto.torso_source == "auto"
+ manual = analyze(src, torso_half=6)
+ assert manual.torso_source == "manual"
+ p = protect(manual)
+ assert p(manual.axis_x) == 0.0, "축은 비보호"
+ assert p(manual.axis_x + 5) == 0.0, "밴드 안(t0 미만)은 비보호"
+ assert p(manual.axis_x + 9) == 1.0, "밴드 밖(t1 초과)은 완전 보호 — 밀리기만 한다"
+ assert protect(auto)(auto.axis_x + 9) == 0.0, "자동 경로(블롭)는 기존 계약 그대로 무보호"
+
+
+def test_manual_band_actually_changes_the_bake() -> None:
+ """**부속이 없는** 픽스처로, **폭 변동 크기**로 잰다 — 그게 실제 계약이다.
+
+ 두 번의 변이 검증(2026-07-31)이 순진한 그물을 둘 다 통과시켰다:
+ (1) `_dome` 은 부속이 있어서 자동 램프가 이미 켜져 있고,
+ (2) `_humanoid` 이라도 밴드를 좁히면 `has_appendage`(max_half >= 1.3*torso_half)
+ 판정이 뒤집혀 자동 램프가 켜지므로, 앵커 수리를 되돌려도 **출력은 어차피
+ 달라진다** — "다르다" 단정으로는 회귀를 못 잡는다.
+ 실제 계약은 **밴드 밖이 늘어나지 않고 밀리기만 하는 것**이므로, 밴드를 좁힐수록
+ 실루엣 폭 변동이 줄어드는지를 잰다 (실측: 수리 3px→1px, mutant 3px→2px).
+ """
+ src = _humanoid()
+ assert not analyze(src).has_appendage, "이 그물은 부속 없는 도형이어야 의미가 있다"
+
+ def width_swing(cfg):
+ frames, _ = _frames(src, count=12, cfg=cfg)
+ spans = [solid_alpha_bbox(f)[2] - solid_alpha_bbox(f)[0] for f in frames]
+ return max(spans) - min(spans)
+
+ wide = width_swing({**CFG, "depth": 0.10})
+ narrow = width_swing({**CFG, "depth": 0.10, "torso_half": 4})
+ assert narrow <= 1, (
+ f"수동 밴드 4 인데 폭이 {narrow}px 흔들린다 — 밴드 밖이 밀리지 않고 늘어났다")
+ assert narrow < wide, (
+ f"밴드를 좁혔는데 폭 변동이 안 줄었다 (auto {wide}px vs 밴드4 {narrow}px) — "
+ f"보호가 밴드에 앵커되지 않았다")
+
+
+def test_depth_x_schema_bounds() -> None:
+ """depth_x 는 null(따름)과 0(가로 끄기)이 유효하고, 범위 밖은 요란하게 거부."""
+ def cur(dx):
+ return {"states": {"idle": {"breathe": {"depth": 0.06, "breaths": 1,
+ "lag": 0.1, "depth_x": dx}}}}
+ assert state_breathe(cur(None), "idle")["depth_x"] is None
+ base = {"states": {"idle": {"breathe": {"depth": 0.06, "breaths": 1, "lag": 0.1}}}}
+ assert state_breathe(base, "idle")["depth_x"] is None
+ assert state_breathe(cur(0), "idle")["depth_x"] == 0.0
+ assert state_breathe(cur(0.12), "idle")["depth_x"] == 0.12
+ for bad in (-0.01, 0.5, "abc"):
+ with pytest.raises(SystemExit):
+ state_breathe(cur(bad), "idle")
diff --git a/tests/effects/test_breathe_anatomy_route.py b/tests/effects/test_breathe_anatomy_route.py
new file mode 100644
index 0000000..5ba26d8
--- /dev/null
+++ b/tests/effects/test_breathe_anatomy_route.py
@@ -0,0 +1,321 @@
+# SPDX-License-Identifier: Apache-2.0
+"""`GET /api/breathe-anatomy` 의 기준 프레임 해소를 **실제로** 태운다.
+
+이 라우트는 검출 SSoT 를 서버로 몬 설계의 유일한 진입점이다 — 큐레이터가 호흡을 켤 때,
+경계를 드래그할 때, `auto` 로 되돌릴 때 전부 여기를 부른다. 그런데 도입(`a385c3f`)부터
+**항상 HTTP 500** 이었고 7라운드를 살아남았다: `_breathe_source_frame` 이 `state_plan` 을
+잘못된 인자 순서로 부르고 존재하지 않는 `request["cell_width"]` 를 읽었는데, 이 경로를
+태우는 테스트가 하나도 없었기 때문이다 (validator 2026-07-26).
+
+미러 테스트들은 파이썬에서 만든 `freeze_anatomy` 결과를 JS 에 직접 먹인다 — **서버가 그
+숫자를 만들어 낼 수 있는지**는 한 번도 묻지 않았다. 그 공백을 여기서 메운다.
+
+추출 완료 상태의 최소 런을 합성한다(골든 픽스처는 추출 전이라 프레임 manifest 가 없다).
+"""
+
+import json
+import sys
+from pathlib import Path
+
+import pytest
+from PIL import Image
+
+ROOT = Path(__file__).resolve().parent.parent.parent
+sys.path.insert(0, str(ROOT))
+
+CELL = 96
+
+
+def _figure(cell=CELL):
+ """셀 안에 목 병목이 있는 도형 — 해부가 성립해야 한다."""
+ im = Image.new("RGBA", (cell, cell), (0, 0, 0, 0))
+ px = im.load()
+ def block(x0, y0, x1, y1, rgb):
+ for y in range(y0, y1):
+ for x in range(x0, x1):
+ px[x, y] = (*rgb, 255)
+ block(38, 14, 58, 34, (90, 60, 30)) # 머리
+ block(44, 34, 52, 40, (90, 60, 30)) # 목 (병목)
+ block(32, 40, 64, 82, (90, 60, 30)) # 몸통
+ for x0 in (41, 51): # 눈 (좌우 대칭)
+ block(x0, 20, x0 + 4, 26, (10, 10, 12))
+ return im
+
+
+def run_dir(tmp_path):
+ """추출까지 끝난 최소 런 — sprite-request + frames manifest + 프레임 PNG."""
+ run = tmp_path / "run"
+ (run / "frames" / "idle").mkdir(parents=True)
+ request = {
+ "character": "fixture",
+ "cell": {"shape": "square", "width": CELL, "height": CELL, "size": CELL,
+ "safe_margin_x": 8, "safe_margin_y": 8, "safe_margin": 8},
+ "states": {"idle": {"frames": 4, "fps": 6, "loop": True}},
+ }
+ (run / "sprite-request.json").write_text(json.dumps(request), encoding="utf-8")
+ files = []
+ for i in range(4):
+ rel = f"frames/idle/frame-{i}.png"
+ img = _figure()
+ if i: # 프레임마다 조금씩 다르게 (깜빡임 흉내)
+ p = img.load()
+ for y in range(20 + i, 26):
+ for x in range(41, 45):
+ p[x, y] = (90, 60, 30, 255)
+ img.save(run / rel)
+ files.append(rel)
+ (run / "frames" / "frames-manifest.json").write_text(json.dumps({
+ "ok": True, "errors": [], "warnings": [],
+ "rows": [{"state": "idle", "frames": 4, "method": "components", "files": files,
+ "ok": True}]}), encoding="utf-8")
+ return run
+
+
+def test_the_route_helper_returns_a_usable_reference_frame(run_dir):
+ """예외 없이 셀 크기의 RGBA 프레임이 나와야 한다."""
+ import sprite_gen.serve.serve_curation as serve_curation
+ frame, key = serve_curation._breathe_source_frame(run_dir, "idle")
+ assert isinstance(frame, Image.Image), f"기준 프레임을 못 만든다 ({frame!r})"
+ assert isinstance(key, str) and key.startswith("breathe-ref-v1|"), \
+ f"기준 프레임 키를 같이 못 내놓는다 ({key!r}) — 웹뷰가 신선도를 못 본다"
+ assert frame.mode == "RGBA"
+ assert frame.size == (CELL, CELL), "굽기와 같은 셀 크기여야 한다"
+
+
+def test_the_route_helper_feeds_freeze_anatomy(run_dir):
+ """그 프레임으로 해부를 얼릴 수 있어야 한다 — 라우트가 돌려주는 값 그대로."""
+ import sprite_gen.serve.serve_curation as serve_curation
+ from sprite_gen.effects.breathe import freeze_anatomy
+
+ frame, key = serve_curation._breathe_source_frame(run_dir, "idle")
+ frozen = freeze_anatomy(frame, {}, key)
+ for key in ("rigid_row", "neck_row", "basis_row", "axis_x", "torso_half",
+ "max_half", "width", "height", "fingerprint"):
+ assert key in frozen, f"라우트 응답에 {key} 가 없다"
+ assert 0 < frozen["rigid_row"] < frozen["height"]
+
+
+def test_a_manual_rigid_row_is_honoured(run_dir):
+ """`?rigid_row=` 경로 — 큐레이터의 경계 드래그가 쓰는 인자."""
+ import sprite_gen.serve.serve_curation as serve_curation
+ from sprite_gen.effects.breathe import freeze_anatomy
+
+ frame, key = serve_curation._breathe_source_frame(run_dir, "idle")
+ auto = freeze_anatomy(frame, {}, key)
+ want = min(auto["height"] - 2, auto["rigid_row"] + 5)
+ manual = freeze_anatomy(frame, {"rigid_row": want}, key)
+ assert manual["rigid_row"] == want and manual["rigid_source"] == "manual"
+
+
+def test_the_reference_is_the_frame_the_bake_starts_from(run_dir):
+ """서버가 얼리는 기준 프레임 = **굽기가 실제로 해부를 확정하는 프레임**이어야 한다.
+
+ 둘이 다르면 지문이 영구 불일치라 프리뷰·영상 내보내기가 계속 거부된다.
+
+ 첫 판은 `_breathe_source_frame` 을 두 번 불러 비교하는 **항등식**이었다 — 이름이
+ 단언하는 것을 한 번도 안 물었고 그 사유로는 절대 실패할 수 없었다 (validator note
+ 2026-07-26, round-6 N1 과 같은 클래스). 이제 실제로 `compose_gif` 를 돌려 manifest 가
+ 기록한 **해부 값**과 대조한다 — 굽기는 지문을 안 찍는다(캐시를 안 믿고 매번 다시
+ 잰다). 프리뷰가 지켜야 하는 것도 지문이 아니라 "굽기와 같은 경계로 그린다" 이다."""
+ import sprite_gen.serve.serve_curation as serve_curation
+ from sprite_gen.compose import compose_gif
+ from sprite_gen.effects.breathe import freeze_anatomy
+
+ # 사이드카에 호흡을 켜고 실제로 굽는다
+ from sprite_gen.curate.curation import stamp_curation
+ curation = stamp_curation(run_dir, {
+ "version": 1, "kind": "sprite-gen-curation",
+ "states": {"idle": {"selected": [0, 1, 2, 3],
+ "breathe": {"depth": 0.06, "breaths": 1, "lag": 0.1}}}})
+ (run_dir / "curation.json").write_text(json.dumps(curation), encoding="utf-8")
+ out = run_dir / "gif"
+ compose_gif.run(run_dir=run_dir, out_dir=out)
+ manifest = json.loads((out / "gif-manifest.json").read_text(encoding="utf-8"))
+ baked = next(e for e in manifest["exports"] if e["state"] == "idle")
+ baked_anat = baked["breathe"]["resolved"]["anatomy"]
+
+ frame, key = serve_curation._breathe_source_frame(run_dir, "idle")
+ served = freeze_anatomy(frame, {}, key)
+ drift = {k: [baked_anat[k], served[k]] for k in baked_anat
+ if k in served and baked_anat[k] != served[k]}
+ assert not drift, (
+ "라우트가 얼리는 해부가 굽기가 쓰는 해부와 다르다 — 프리뷰가 굽기와 다른 "
+ f"경계로 그린다: {drift}")
+
+
[email protected]("state,why", [
+ ("no-such-state", "manifest 에 줄이 없다"),
+ ("pending", "request 에 선언됐지만 아직 추출 안 된 줄 (manifest row 없음)"),
+])
+def test_a_resolvable_frame_is_always_reported_the_same_way(run_dir, state, why):
+ """기준 프레임을 못 만드는 **모든** 사유가 같은 모양으로 나와야 한다.
+
+ 핸들러는 `frame, key = _breathe_source_frame(...)` 로 받는다. 한 갈래만 맨 `None`
+ 이면 거기서 `TypeError: cannot unpack non-iterable NoneType` 이 나고, 의도한
+ 404("no extracted frame for state") 대신 그 문구로 **500** 이 나간다 — 추출이 아직
+ 안 끝난 줄에서 호흡을 켜면 도달한다 (validator 실측 2026-07-26).
+
+ 앞선 판은 `is None` 만 봐서 반환 **모양**을 한 번도 안 물었다 (round-6 N1 ·
+ round-9 N1 과 같은 클래스: 이름이 단언하는 것을 안 묻는 테스트)."""
+ import sprite_gen.serve.serve_curation as serve_curation
+ if state == "pending":
+ # 사용자가 실제로 닿는 모양: request 에는 있는데 아직 안 구워진 줄이다
+ # (`load_consistent_frames_manifest(allow_pending_states=True)` 가 허용하는 상태).
+ # manifest 에 row 를 넣고 파일만 없애는 판은 로더가 먼저 loud fail 해서 도달 불가다.
+ rp = run_dir / "sprite-request.json"
+ req = json.loads(rp.read_text(encoding="utf-8"))
+ req["states"]["pending"] = {"frames": 1, "fps": 6, "loop": True}
+ rp.write_text(json.dumps(req), encoding="utf-8")
+
+ got = serve_curation._breathe_source_frame(run_dir, state)
+ frame, key = got # 핸들러와 **같은 모양**으로 받는다 ({why})
+ assert frame is None and key is None, f"{why}: {got!r}"
+
+
+def test_the_reference_frame_is_measured_after_the_transform(run_dir):
+ """해부는 **변형을 적용한 뒤**의 프레임에서 잰다.
+
+ 굽기는 `apply_pixel_edits` → `apply_transform` 뒤에 호흡을 얹으므로, 원본 프레임에서
+ 재면 라우트가 얼리는 경계와 굽기가 쓰는 경계가 다르다. 계약은 지켜지고 있었지만
+ `_breathe_source_frame` 의 마지막 줄을 `return source, key`(변형 생략)로 되돌려도
+ **전체 스위트 529 가 전부 통과했다** — 회귀하면 경계가 몇 행 어긋난 채 조용히 나간다
+ (validator note 2026-07-26; round-8 이 "라우트 그물 0" 으로 기각한 그 자리다).
+
+ 변형이 해부를 **실제로 바꾸는** 값을 쓴다 — 안 그러면 단언이 공허하다."""
+ import sprite_gen.serve.serve_curation as serve_curation
+ from sprite_gen.effects.breathe import freeze_anatomy
+ from sprite_gen.curate.curation import stamp_curation
+
+ plain_frame, plain_key = serve_curation._breathe_source_frame(run_dir, "idle")
+ plain = freeze_anatomy(plain_frame, {}, plain_key)
+
+ curation = {"version": 1, "kind": "sprite-gen-curation",
+ # 호흡을 **켜둔다** — 안 켜면 manifest 에 `breathe` 가 없어 아래 굽기 대조
+ # 절이 통째로 죽은 코드가 된다 (노을이 note 2026-07-26).
+ "states": {"idle": {"selected": [0, 1, 2, 3],
+ "breathe": {"depth": 0.06, "breaths": 1, "lag": 0.1},
+ "transforms": {"0": {"rotate": 5.0, "scale": 1.05}}}}}
+ (run_dir / "curation.json").write_text(
+ json.dumps(stamp_curation(run_dir, curation)), encoding="utf-8")
+ rot_frame, rot_key = serve_curation._breathe_source_frame(run_dir, "idle")
+ rotated = freeze_anatomy(rot_frame, {}, rot_key)
+
+ moved = {k for k in ("rigid_row", "axis_x", "height", "neck_row")
+ if plain[k] != rotated[k]}
+ assert moved, (
+ "변형을 걸었는데 해부가 하나도 안 움직였다 — 이 픽스처로는 '변형 후에 잰다' 를 "
+ f"보증할 수 없다 (plain={plain}, rotated={rotated})")
+
+ # 그리고 그 값은 **굽기가 쓰는 값**과 같아야 한다
+ from sprite_gen.compose import compose_gif
+ out = run_dir / "gif-rot"
+ compose_gif.run(run_dir=run_dir, out_dir=out)
+ manifest = json.loads((out / "gif-manifest.json").read_text(encoding="utf-8"))
+ baked = next(e for e in manifest["exports"] if e["state"] == "idle")
+ assert baked.get("breathe"), "굽기가 호흡을 안 실었다 — 이 대조 절이 죽은 코드가 된다"
+ baked_anat = baked["breathe"]["resolved"]["anatomy"]
+ drift = {k: [baked_anat[k], rotated[k]] for k in baked_anat
+ if k in rotated and baked_anat[k] != rotated[k]}
+ assert not drift, f"라우트가 변형 후 프레임을 안 쟀다 — 굽기와 어긋난다: {drift}"
+
+
+def test_the_reference_frame_honours_every_axis_the_bake_uses(run_dir):
+ """"굽기가 보는 것과 같은 픽셀" 은 **네 축 전부**다 — 변형만이 아니다.
+
+ `_breathe_source_frame` 은 (1) 재생 순서로 기준 프레임을 고르고 (2) 픽셀 편집을 얹고
+ (3) 변형을 걸고 (4) pp 런이면 격자로 재양자화한다. 앞선 그물은 (3) 만 태웠고, 나머지
+ 셋은 픽스처가 기본값이라 변이를 걸어도 **행동이 안 바뀌어** 통과했다 (노을이 note
+ 2026-07-26: `snap=None`, `pixel_ops={}`, `ordered==range(4)`).
+
+ 그래서 축마다 **결과를 실제로 바꾸는** 값을 준 뒤, 그 축을 무시하는 변이가 다른
+ 프레임을 만들어내는지 본다. "닫았다" 고 적은 계약이 한 축만 덮고 있던 것을 고친다."""
+ import sprite_gen.serve.serve_curation as serve_curation
+ from sprite_gen.curate.curation import stamp_curation
+
+ # 재생 첫 슬롯을 2번 프레임으로 바꾸고(순서), 그 프레임에만 픽셀을 칠하고(편집),
+ # 변형을 건다 — 셋 다 기준 프레임의 픽셀을 바꾼다.
+ paint = {f"{x},{y}": "#ff00ff" for x in range(20, 34) for y in range(44, 58)}
+ curation = {"version": 1, "kind": "sprite-gen-curation",
+ "states": {"idle": {"selected": [2, 0, 1, 3],
+ "breathe": {"depth": 0.06, "breaths": 1, "lag": 0.1},
+ "pixels": {"2": paint},
+ "transforms": {"2": {"rotate": 5.0, "scale": 1.05}}}}}
+ (run_dir / "curation.json").write_text(
+ json.dumps(stamp_curation(run_dir, curation)), encoding="utf-8")
+
+ frame, key = serve_curation._breathe_source_frame(run_dir, "idle")
+ assert frame is not None, "기준 프레임을 못 만든다"
+ got = frame.tobytes()
+
+ # 축 (1) 재생 순서: 물리 0번을 기준으로 삼으면 다른 그림이 나와야 한다
+ plain = {"version": 1, "kind": "sprite-gen-curation",
+ "states": {"idle": {"selected": [0, 1, 2, 3],
+ "breathe": {"depth": 0.06, "breaths": 1, "lag": 0.1},
+ "pixels": {"2": paint},
+ "transforms": {"2": {"rotate": 5.0, "scale": 1.05}}}}}
+ (run_dir / "curation.json").write_text(
+ json.dumps(stamp_curation(run_dir, plain)), encoding="utf-8")
+ other, _ = serve_curation._breathe_source_frame(run_dir, "idle")
+ assert other.tobytes() != got, (
+ "재생 순서를 바꿔도 같은 기준 프레임이 나온다 — 이 축이 그물 밖이다")
+
+ # 축 (2) 픽셀 편집: 칠한 색이 기준 프레임에 실제로 있어야 한다
+ (run_dir / "curation.json").write_text(
+ json.dumps(stamp_curation(run_dir, curation)), encoding="utf-8")
+ frame, _ = serve_curation._breathe_source_frame(run_dir, "idle")
+ colors = {px[:3] for px in frame.convert("RGBA").getdata() if px[3] > 0}
+ assert (255, 0, 255) in colors, (
+ "픽셀 편집이 기준 프레임에 안 얹혔다 — 굽기는 얹고 굽는다")
+
+ # 축 (4) 스냅은 별도 테스트 — sprite-request 를 도중에 고쳐 쓰면 `run_revision` 이
+ # 바뀌어 큐레이션이 통째로 무효화되고, 그러면 "달라졌다" 가 **엉뚱한 이유로** 참이 된다
+ # (실제로 그랬다: snap 을 None 으로 만든 변이에서도 통과했다).
+
+
+def test_a_pixel_perfect_run_snaps_the_reference_frame_to_the_grid(tmp_path):
+ """pp 런의 기준 프레임은 **격자에 물려** 있다 (`pixel_snap_scale` 재양자화).
+
+ 앞선 판은 테스트 도중 `sprite-request.json` 을 고쳐 써서 두 프레임을 비교했는데,
+ 그러면 `run_revision` 이 바뀌어 큐레이션이 무효화되고 "달라졌다" 가 스냅과 무관한
+ 이유로 참이 된다 — snap 을 None 으로 만든 변이에서도 통과했다. 그래서 비교가 아니라
+ **속성**을 본다: 격자에 물린 그림은 k 로 줄였다 늘려도 자기 자신이다."""
+ import sprite_gen.serve.serve_curation as serve_curation
+ from sprite_gen.curate.curation import pixel_snap_scale, stamp_curation
+
+ run = tmp_path / "run"
+ (run / "frames" / "idle").mkdir(parents=True)
+ request = {
+ "character": {"id": "fixture", "name": "fixture"},
+ "cell": {"shape": "square", "width": CELL, "height": CELL, "size": CELL,
+ "safe_margin_x": 8, "safe_margin_y": 8, "safe_margin": 8},
+ "fit": {"pixel_unfake": True, "logical_height": CELL // 2},
+ "states": {"idle": {"frames": 2, "fps": 6, "loop": True}},
+ }
+ (run / "sprite-request.json").write_text(json.dumps(request), encoding="utf-8")
+ k = pixel_snap_scale(request)
+ assert k and k > 1, f"픽스처가 스냅 배율을 안 만든다 (k={k}) — 이 테스트는 공허하다"
+ files = []
+ for i in range(2):
+ rel = f"frames/idle/frame-{i}.png"
+ _figure().save(run / rel)
+ files.append(rel)
+ (run / "frames" / "frames-manifest.json").write_text(json.dumps({
+ "ok": True, "errors": [], "warnings": [],
+ "rows": [{"state": "idle", "frames": 2, "method": "components", "files": files,
+ "ok": True}]}), encoding="utf-8")
+ # 회전을 걸어 둔다 — 스냅이 없으면 BICUBIC 결과가 격자를 벗어난다
+ curation = {"version": 1, "kind": "sprite-gen-curation",
+ "states": {"idle": {"selected": [0, 1],
+ "breathe": {"depth": 0.06, "breaths": 1, "lag": 0.1},
+ "transforms": {"0": {"rotate": 5.0}}}}}
+ (run / "curation.json").write_text(
+ json.dumps(stamp_curation(run, curation)), encoding="utf-8")
+
+ frame, _ = serve_curation._breathe_source_frame(run, "idle")
+ assert frame is not None
+ small = frame.resize((CELL // k, CELL // k), Image.NEAREST)
+ regrid = small.resize((CELL, CELL), Image.NEAREST)
+ assert regrid.tobytes() == frame.tobytes(), (
+ f"기준 프레임이 k={k} 격자에 안 물려 있다 — 굽기는 물려서 굽는다"
+ " (`apply_transform(snap_scale=...)`)")
diff --git a/tests/effects/test_breathe_js_mirror.py b/tests/effects/test_breathe_js_mirror.py
new file mode 100644
index 0000000..e574da3
--- /dev/null
+++ b/tests/effects/test_breathe_js_mirror.py
@@ -0,0 +1,438 @@
+# SPDX-License-Identifier: Apache-2.0
+"""큐레이터 JS 미러가 파이썬 굽기와 **바이트 동일**한지 (Task Card Verification).
+
+호흡 워프는 두 곳에 구현돼 있다: 굽기(`sprite_gen/effects/breathe.py`)와 라이브 프리뷰
+(`sprite_gen/serve/curator/src/breathe.js`). 검출은 서버 한 곳으로 몰았지만 워프는 프리뷰를
+위해 미러가 남아 있고, 미러가 갈리면 "미리보기와 결과가 다르다"가 된다.
+
+이 테스트가 그 계약을 고정한다 — 위상 0 을 포함한 전 위상을 비교한다. 위상 0 이
+중요한 이유: 진행파 지연 때문에 t=0 도 항등이 아닌데, 예전엔 두 소비자가 그걸
+건너뛰어 아틀라스만 원본을 굽는 사고가 있었다 (validator 검증 2026-07-25).
+
+node 가 없으면 skip — CI 에 node 가 없을 수 있고, 그 경우 조용히 통과시키지 않고
+skip 사유를 남긴다.
+"""
+
+import json
+import shutil
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+
+sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent))
+
+from sprite_gen.effects.breathe import (MAX_ROW_STRAIN, anatomy_fingerprint, # noqa: E402
+ freeze_anatomy, phase_frame, reference_key, resolve_anatomy,
+ row_strain)
+from sprite_gen.frames.extract import solid_alpha_bbox # noqa: E402
+from sprite_gen.serve.serve_curation import CURATOR_DIR # noqa: E402
+from tests.effects.test_breathe import CFG, _dome, _humanoid, _key, _small_outlined, _winged # noqa: E402
+
+CURATOR_BREATHE = CURATOR_DIR / "src" / "breathe.js"
+PHASES = [i / 12 for i in range(12)]
+
+# breathe.js 는 클래식 스크립트(모듈 아님)라 전역 어휘를 공유한다. node 에서 돌리려면
+# 문서 API 최소분만 shim 하면 된다 — 워프는 canvas 2D getImageData/putImageData 만 쓴다.
+HARNESS = r"""
+const fs = require("fs");
+const vm = require("vm");
+
+function makeCanvas(w, h, data) {
+ const buf = data ? Uint8ClampedArray.from(data) : new Uint8ClampedArray(w * h * 4);
+ const ctx = {
+ imageSmoothingEnabled: false,
+ getImageData: () => ({ data: buf, width: w, height: h }),
+ putImageData: (img) => { buf.set(img.data); },
+ createImageData: (cw, ch) => ({ data: new Uint8ClampedArray(cw * ch * 4), width: cw, height: ch }),
+ drawImage: (src) => { buf.set(src.__buf); },
+ clearRect: () => {},
+ };
+ const cvs = { width: w, height: h, getContext: () => ctx, __buf: buf };
+ return cvs;
+}
+
+const payload = JSON.parse(fs.readFileSync(process.argv[2], "utf8"));
+const sandbox = {
+ document: { createElement: () => makeCanvas(payload.width, payload.height) },
+ console,
+ entries: {}, run: { states: [] }, t: () => "", setStatus: () => {}, fetch: () => {},
+};
+sandbox.globalThis = sandbox;
+vm.createContext(sandbox);
+vm.runInContext(fs.readFileSync(payload.script, "utf8"), sandbox);
+
+const out = [];
+for (const item of payload.cases) {
+ const base = makeCanvas(payload.width, payload.height, item.rgba);
+ try {
+ const res = sandbox.breatheComposite(base, payload.cfg, item.phase);
+ out.push({ ok: true, data: Array.from(res.getContext().getImageData().data) });
+ } catch (e) {
+ out.push({ ok: false, refused: e.constructor.name === "BreatheRefused", message: e.message });
+ }
+}
+fs.writeFileSync(payload.out, JSON.stringify(out));
+"""
+
+
+def _rgba(image):
+ return list(image.convert("RGBA").tobytes())
+
+
[email protected](shutil.which("node") is None, reason="node 가 없어 JS 미러를 실행할 수 없다")
[email protected]("build,overrides", [
+ (_humanoid, {}), (_winged, {}), (_dome, {}),
+ # 다듬기(_thin_outline_1px/breatheThinOutline)가 **실제로 픽셀을 치환하는** 유일한
+ # 픽스처 — 기본 3종은 depth 0.06 에서 다듬기가 0바이트라, 이 케이스가 없으면
+ # JS 다듬기 미러가 파이썬과 갈라져도 패리티 스위트가 못 잡는다
+ # (validator 지정 2026-07-30: depth 0.08 24위상에서 294바이트 치환 실측).
+ (_small_outlined, {"depth": 0.08, "breaths": 3}),
+ # 가로/세로 진폭 분리 + 수동 밴드 (2026-07-30): 가로 강함 / 가로 항등 / 밴드 앵커 보호.
+ # 이 케이스들이 없으면 JS 의 depthX 해석·수동 protect 앵커가 파이썬과 갈라져도 못 잡는다.
+ (_dome, {"depth_x": 0.12}),
+ (_dome, {"depth": 0.10, "depth_x": 0.0}),
+ (_dome, {"depth": 0.10, "torso_half": 6}),
+], ids=["humanoid", "winged", "dome", "small-outlined-thinning",
+ "dome-depth-x", "dome-depth-x-zero", "dome-manual-band"])
+def test_curator_mirror_is_byte_identical_to_the_bake(build, overrides, tmp_path):
+ src = build()
+ cfg = {**CFG, **overrides}
+ cfg["anatomy"] = freeze_anatomy(src, cfg, _key())
+
+ payload = {
+ "script": str(CURATOR_BREATHE),
+ "width": src.width,
+ "height": src.height,
+ "cfg": {"depth": cfg["depth"], "breaths": cfg["breaths"], "lag": cfg["lag"],
+ **({"depth_x": cfg["depth_x"]} if "depth_x" in cfg else {}),
+ **({"torso_half": cfg["torso_half"]} if "torso_half" in cfg else {}),
+ "anatomy": cfg["anatomy"]},
+ "cases": [{"phase": p, "rgba": _rgba(src)} for p in PHASES],
+ "out": str(tmp_path / "js.json"),
+ }
+ payload_path = tmp_path / "payload.json"
+ payload_path.write_text(json.dumps(payload), encoding="utf-8")
+ harness = tmp_path / "harness.cjs"
+ harness.write_text(HARNESS, encoding="utf-8")
+
+ proc = subprocess.run([shutil.which("node"), str(harness), str(payload_path)],
+ capture_output=True, text=True)
+ assert proc.returncode == 0, f"node 하네스 실패:\n{proc.stderr}"
+ js_frames = json.loads((tmp_path / "js.json").read_text(encoding="utf-8"))
+
+ assert len(js_frames) == len(PHASES)
+ for phase, js in zip(PHASES, js_frames):
+ assert js["ok"], f"{build.__name__} 위상 {phase:.4f}: JS 가 거부했다 — {js['message']}"
+ py = _rgba(phase_frame(src, cfg, phase))
+ diff = sum(1 for a, b in zip(py, js["data"]) if a != b)
+ assert diff == 0, f"{build.__name__} 위상 {phase:.4f}: JS 미러가 굽기와 {diff}바이트 다르다"
+
+
[email protected](shutil.which("node") is None, reason="node 가 없어 JS 미러를 실행할 수 없다")
[email protected]("build", [_humanoid, _winged, _dome], ids=["humanoid", "winged", "dome"])
+def test_the_mirror_refuses_exactly_what_the_bake_refuses(build, tmp_path):
+ """굽기가 `SystemExit` 으로 거부하는 프레임은 미러도 만들어 주면 안 된다.
+
+ 미러가 조용히 잘라 내보내면 (a) 프리뷰는 멀쩡한데 굽기가 죽고 (b) `row-export` 의
+ WebM/MP4 는 서버를 안 거치므로 **잘린 영상이 사용자 손에 들어간다** (validator 실측
+ 2026-07-25: 여백 0 셀에서 불투명 73px 소실, 오류 0건). 여기서 여백을 없애 그 상황을
+ 강제로 만든다."""
+ src = build()
+ src = src.crop(solid_alpha_bbox(src)) # 여백 0 — 늘어나면 반드시 잘린다
+ cfg = dict(CFG)
+ cfg["anatomy"] = freeze_anatomy(src, cfg, _key())
+
+ refused_py = []
+ for phase in PHASES:
+ try:
+ phase_frame(src, cfg, phase)
+ except SystemExit:
+ refused_py.append(phase)
+ assert refused_py, "이 픽스처는 굽기가 거부하는 위상을 가져야 의미가 있다"
+
+ payload = {
+ "script": str(CURATOR_BREATHE), "width": src.width, "height": src.height,
+ "cfg": {"depth": cfg["depth"], "breaths": cfg["breaths"], "lag": cfg["lag"],
+ "anatomy": cfg["anatomy"]},
+ "cases": [{"phase": p, "rgba": _rgba(src)} for p in PHASES],
+ "out": str(tmp_path / "js.json"),
+ }
+ (tmp_path / "payload.json").write_text(json.dumps(payload), encoding="utf-8")
+ (tmp_path / "harness.cjs").write_text(HARNESS, encoding="utf-8")
+ proc = subprocess.run([shutil.which("node"), str(tmp_path / "harness.cjs"),
+ str(tmp_path / "payload.json")], capture_output=True, text=True)
+ assert proc.returncode == 0, f"node 하네스 실패:\n{proc.stderr}"
+ js = json.loads((tmp_path / "js.json").read_text(encoding="utf-8"))
+
+ for phase, got in zip(PHASES, js):
+ py_refused = phase in refused_py
+ assert got["ok"] != py_refused, (
+ f"{build.__name__} 위상 {phase:.4f}: 굽기 거부={py_refused} 인데 "
+ f"미러는 {'거부' if not got['ok'] else '통과'} — 계약이 한쪽에만 있다")
+ if not got["ok"]:
+ assert got["refused"], f"BreatheRefused 가 아닌 예외로 죽었다: {got['message']}"
+
+
[email protected](shutil.which("node") is None, reason="node 가 없어 JS 미러를 실행할 수 없다")
[email protected]("build", [_humanoid, _winged], ids=["humanoid", "winged"])
+def test_the_mirror_matches_on_frames_other_than_the_frozen_one(build, tmp_path):
+ """줄의 **다른** 프레임에서도 굽기와 미러가 같아야 한다.
+
+ 사이드카에는 해부가 한 벌뿐이고 미러는 그걸 그대로 쓴다. 굽기가 프레임마다 다시
+ 재던 시절엔 깜빡임처럼 프레임이 조금만 달라도 갈렸다 (validator 실측 2026-07-25:
+ 골든 픽스처 idle 4프레임에서 최대 220바이트, 불투명 픽셀 **수**까지 불일치).
+ 지금은 줄 전체가 한 벌을 쓰므로 같아야 한다 — 이 테스트가 그 계약이다.
+
+ 기존 미러 테스트는 `freeze_anatomy(src)` 한 프레임만 비교해 이 경로가 통째로
+ 그물 밖이었다."""
+ frozen_src = build()
+ cfg = dict(CFG)
+ cfg["anatomy"] = freeze_anatomy(frozen_src, cfg, _key())
+
+ # 같은 줄의 '다른 프레임' — 알파 무변 RGB 덧칠 (큐레이터 픽셀 편집기의 문서화된 기능)
+ other = frozen_src.copy()
+ px = other.load()
+ box = solid_alpha_bbox(other)
+ axis = (box[0] + box[2]) // 2 # 몸통 축 — 반드시 불투명하다
+ painted = 0
+ for y in range(box[1] + 4, box[1] + 14):
+ for x in range(axis - 3, axis + 4):
+ if px[x, y][3] >= 128:
+ px[x, y] = (12, 14, 18, px[x, y][3])
+ painted += 1
+ assert painted, "덧칠할 불투명 픽셀을 못 찾았다"
+ assert other.tobytes() != frozen_src.tobytes(), "픽스처가 실제로 달라야 의미가 있다"
+
+ anat = resolve_anatomy(frozen_src, cfg) # 줄 전체가 기준 프레임의 한 벌을 쓴다
+
+ payload = {
+ "script": str(CURATOR_BREATHE), "width": other.width, "height": other.height,
+ "cfg": {"depth": cfg["depth"], "breaths": cfg["breaths"], "lag": cfg["lag"],
+ "anatomy": cfg["anatomy"]},
+ "cases": [{"phase": p, "rgba": _rgba(other)} for p in PHASES],
+ "out": str(tmp_path / "js.json"),
+ }
+ (tmp_path / "payload.json").write_text(json.dumps(payload), encoding="utf-8")
+ (tmp_path / "harness.cjs").write_text(HARNESS, encoding="utf-8")
+ proc = subprocess.run([shutil.which("node"), str(tmp_path / "harness.cjs"),
+ str(tmp_path / "payload.json")], capture_output=True, text=True)
+ assert proc.returncode == 0, f"node 하네스 실패:\n{proc.stderr}"
+ js = json.loads((tmp_path / "js.json").read_text(encoding="utf-8"))
+
+ for phase, got in zip(PHASES, js):
+ assert got["ok"], f"위상 {phase:.4f}: JS 가 거부했다 — {got['message']}"
+ py = _rgba(phase_frame(other, cfg, phase, anat)) # 줄 해부 한 벌로 굽는다
+ diff = sum(1 for a, b in zip(py, got["data"]) if a != b)
+ assert diff == 0, f"{build.__name__} 위상 {phase:.4f}: 얼린 프레임 밖에서 {diff}바이트 갈렸다"
+
+
[email protected](shutil.which("node") is None, reason="node 가 없어 JS 미러를 실행할 수 없다")
+def test_the_mirror_refuses_the_same_strain_cap(tmp_path):
+ """행당 변형 상한 거부도 양쪽이 같아야 한다 (validator note: JS 상한 그물이 비어 있었다).
+
+ 클리핑 거부만 그물이 있고 상한 거부는 없어서, JS 가드를 죽여도 미러 테스트가
+ 전부 통과했다. 동작은 동치였지만 회귀를 막는 것이 없었다."""
+ # 강체 경계를 아래로 내리면 변형 구간이 좁아지고 정규화 계수가 커져 행당 변형이
+ # 상한을 넘는다 — 사람이 `rigid_row` 로 도달할 수 있는 실제 조합이다.
+ src = _humanoid()
+ base = dict(CFG)
+ base["anatomy"] = freeze_anatomy(src, base, _key())
+ height = base["anatomy"]["height"]
+ cfg = {**base, "rigid_row": int(height * 0.78)}
+ anat = resolve_anatomy(src, cfg)
+ cfg["anatomy"] = {**anat.as_dict(), "fingerprint": base["anatomy"]["fingerprint"]}
+ depth = next((round(0.005 * i, 3) for i in range(1, 41)
+ if row_strain(anat, round(0.005 * i, 3)) > MAX_ROW_STRAIN), None)
+ assert depth is not None, (
+ f"경계 {cfg['rigid_row']}/{height} 에서도 스키마 범위 안에서 상한을 못 넘긴다 "
+ f"(depth 0.20 에서 {row_strain(anat, 0.20):.3f}) — 상한이 도달 불가면 계약이 죽은 것이다")
+ over = {**cfg, "depth": depth}
+
+ with pytest.raises(SystemExit):
+ phase_frame(src, over, 0.25, anat)
+
+ payload = {
+ "script": str(CURATOR_BREATHE), "width": src.width, "height": src.height,
+ "cfg": {"depth": depth, "breaths": cfg["breaths"], "lag": cfg["lag"],
+ "anatomy": cfg["anatomy"]},
+ "cases": [{"phase": 0.25, "rgba": _rgba(src)}],
+ "out": str(tmp_path / "js.json"),
+ }
+ (tmp_path / "payload.json").write_text(json.dumps(payload), encoding="utf-8")
+ (tmp_path / "harness.cjs").write_text(HARNESS, encoding="utf-8")
+ proc = subprocess.run([shutil.which("node"), str(tmp_path / "harness.cjs"),
+ str(tmp_path / "payload.json")], capture_output=True, text=True)
+ assert proc.returncode == 0, f"node 하네스 실패:\n{proc.stderr}"
+ got = json.loads((tmp_path / "js.json").read_text(encoding="utf-8"))[0]
+ assert not got["ok"] and got["refused"], \
+ f"굽기는 상한으로 거부하는데 미러는 통과시켰다: {got}"
+
+
[email protected](shutil.which("node") is None, reason="node 가 없어 JS 미러를 실행할 수 없다")
+def test_the_mirror_refuses_a_stale_anatomy_against_a_manual_rigid_row(tmp_path):
+ """사이드카 `rigid_row` 가 얼린 해부와 어긋나면 미러는 **거부**해야 한다.
+
+ `rigid_row` 는 의도(입력), `anatomy` 는 파생 캐시다. 굽기는 어긋나면 재검출해 의도를
+ 따르는데 미러는 검출을 못 한다 — 낡은 캐시로 그리면 거짓말이다. 실측 (validator
+ 2026-07-25): override 31 을 굽기는 따르고 미러는 얼린 23 으로 그려 12위상 전부,
+ 최대 164바이트 갈렸다. `row-export` 는 이 미러로 WebM/MP4 를 굽는다."""
+ src = _humanoid()
+ cfg = dict(CFG)
+ cfg["anatomy"] = freeze_anatomy(src, cfg, _key())
+ frozen_row = cfg["anatomy"]["rigid_row"]
+ override = frozen_row + 8
+ stale = {**cfg, "rigid_row": override}
+
+ anat = resolve_anatomy(src, stale) # 굽기는 의도를 따른다
+ assert anat.rigid_row == override
+
+ payload = {
+ "script": str(CURATOR_BREATHE), "width": src.width, "height": src.height,
+ "cfg": {"depth": cfg["depth"], "breaths": cfg["breaths"], "lag": cfg["lag"],
+ "rigid_row": override, "anatomy": cfg["anatomy"]},
+ "cases": [{"phase": p, "rgba": _rgba(src)} for p in PHASES],
+ "out": str(tmp_path / "js.json"),
+ }
+ (tmp_path / "payload.json").write_text(json.dumps(payload), encoding="utf-8")
+ (tmp_path / "harness.cjs").write_text(HARNESS, encoding="utf-8")
+ proc = subprocess.run([shutil.which("node"), str(tmp_path / "harness.cjs"),
+ str(tmp_path / "payload.json")], capture_output=True, text=True)
+ assert proc.returncode == 0, f"node 하네스 실패:\n{proc.stderr}"
+ for phase, got in zip(PHASES, json.loads((tmp_path / "js.json").read_text(encoding="utf-8"))):
+ assert not got["ok"] and got["refused"], (
+ f"위상 {phase:.4f}: 캐시가 의도와 어긋나는데 미러가 그렸다 — "
+ f"프리뷰·WebM 이 굽기와 다른 애니메이션이 된다")
+
+ # 해부를 갱신하면 다시 같아진다 (거부가 영구 차단이 아니라는 것)
+ fresh = {**stale, "anatomy": {**anat.as_dict(), "fingerprint": anatomy_fingerprint(_key())}}
+ payload["cfg"] = {"depth": cfg["depth"], "breaths": cfg["breaths"], "lag": cfg["lag"],
+ "rigid_row": override, "anatomy": fresh["anatomy"]}
+ (tmp_path / "payload.json").write_text(json.dumps(payload), encoding="utf-8")
+ proc = subprocess.run([shutil.which("node"), str(tmp_path / "harness.cjs"),
+ str(tmp_path / "payload.json")], capture_output=True, text=True)
+ assert proc.returncode == 0
+ for phase, got in zip(PHASES, json.loads((tmp_path / "js.json").read_text(encoding="utf-8"))):
+ assert got["ok"], f"갱신 후에도 거부한다: {got['message']}"
+ py = _rgba(phase_frame(src, fresh, phase, anat))
+ assert sum(1 for a, b in zip(py, got["data"]) if a != b) == 0, \
+ f"위상 {phase:.4f}: 갱신 후 굽기와 갈린다"
+
+
[email protected](shutil.which("node") is None, reason="node 가 없어 JS 미러를 실행할 수 없다")
+def test_the_mirror_refuses_a_stale_reference_frame(tmp_path):
+ """`rigid_row` 가 auto(null)여도 신선도 검사가 돌아야 한다.
+
+ round-6 의 가드는 `cfg.rigid_row` 가 있을 때만 걸렸다. 그런데 `rigid_row` 는 사람이
+ 경계를 드래그할 때만 채워지므로 **기본값은 null** 이고, 그 경우 미러엔 신선도 검사가
+ 하나도 없었다. 굽기는 지문으로 자가 복구하는데 미러는 얼린 숫자로 계속 그린다 —
+ 큐레이터 픽셀 편집기로 도트를 찍기만 해도 도달한다(호흡을 건드릴 필요조차 없다).
+ 실측 (validator 2026-07-25): 최대 617바이트, 불투명 픽셀 **수**까지 불일치."""
+ base = _humanoid()
+ cfg = dict(CFG)
+ cfg["anatomy"] = freeze_anatomy(base, cfg, _key())
+ assert cfg.get("rigid_row") is None, "이 계약은 override 가 없을 때의 이야기다"
+
+ # 픽셀 편집기로 도트를 찍는다 = 사이드카 `pixels` 가 바뀐다 = 기준 프레임 키가 바뀐다.
+ # 근거가 **그림**이 아니라 **사이드카**인 것이 이 설계의 요점이다: 굽기는 BICUBIC 으로
+ # 리샘플하고 웹뷰는 NEAREST 라 그림은 구조적으로 다르고, 그림을 근거로 삼으면 회전이
+ # 걸린 줄이 영구 불일치가 된다 (validator 실측 2026-07-26, R1).
+ edited_key = reference_key(state="idle", variant="plain", request_stamp="1:1",
+ source_index=0, source_stamp="fixture",
+ pixel_ops={"12,40": "#5a3c1e"}, transform=None)
+ assert anatomy_fingerprint(edited_key) != cfg["anatomy"]["fingerprint"], \
+ "픽셀 편집이 키를 안 바꾼다 — 신선도 판정이 그걸 못 본다"
+
+ harness = tmp_path / "fresh.cjs"
+ harness.write_text(
+ 'const fs=require("fs"),vm=require("vm");'
+ 'const P=JSON.parse(fs.readFileSync(process.argv[3],"utf8"));'
+ 'function mk(w,h,d){const b=Uint8ClampedArray.from(d);'
+ ' const c={imageSmoothingEnabled:false,getImageData:()=>({data:b,width:w,height:h}),'
+ ' putImageData:i=>b.set(i.data),createImageData:(a,e)=>({data:new Uint8ClampedArray(a*e*4),width:a,height:e}),'
+ ' drawImage:s=>b.set(s.__buf),clearRect:()=>{}};return{width:w,height:h,getContext:()=>c,__buf:b};}'
+ 'const sb={document:{createElement:()=>mk(P.w,P.h,new Array(P.w*P.h*4).fill(0))},console,'
+ 'entries:{},run:{states:[]},t:()=>"",setStatus:()=>{},fetch:()=>{},TextEncoder};'
+ 'sb.globalThis=sb;vm.createContext(sb);'
+ 'vm.runInContext(fs.readFileSync(process.argv[2],"utf8"),sb);'
+ 'let out;try{sb.breatheAssertFresh(P.key,P.cfg);out={ok:true};}'
+ 'catch(e){out={ok:false,refused:e.constructor.name==="BreatheRefused",message:e.message};}'
+ 'fs.writeFileSync(P.out,JSON.stringify(out));', encoding="utf-8")
+ src_json = tmp_path / "in.json"
+ src_json.write_text(json.dumps({
+ "w": base.width, "h": base.height, "key": edited_key,
+ "cfg": {"depth": cfg["depth"], "breaths": cfg["breaths"], "lag": cfg["lag"],
+ "anatomy": cfg["anatomy"]},
+ "out": str(tmp_path / "out.json")}), encoding="utf-8")
+ proc = subprocess.run([shutil.which("node"), str(harness), str(CURATOR_BREATHE), str(src_json)],
+ capture_output=True, text=True)
+ assert proc.returncode == 0, f"node 하네스 실패:\n{proc.stderr}"
+ got = json.loads((tmp_path / "out.json").read_text(encoding="utf-8"))
+ assert not got["ok"] and got["refused"], (
+ "기준 프레임이 바뀌었는데 미러가 신선하다고 판정했다 — "
+ "프리뷰·WebM 이 굽기와 다른 애니메이션이 된다")
+
+ # 원래 기준 프레임에는 걸리지 않는다 (거부가 상시가 아니라는 것)
+ src_json.write_text(json.dumps({
+ "w": base.width, "h": base.height, "key": _key(),
+ "cfg": {"depth": cfg["depth"], "breaths": cfg["breaths"], "lag": cfg["lag"],
+ "anatomy": cfg["anatomy"]},
+ "out": str(tmp_path / "out.json")}), encoding="utf-8")
+ subprocess.run([shutil.which("node"), str(harness), str(CURATOR_BREATHE), str(src_json)],
+ capture_output=True, text=True, check=True)
+ assert json.loads((tmp_path / "out.json").read_text(encoding="utf-8"))["ok"], \
+ "기준 프레임 그대로인데 거부한다 — 프리뷰가 상시 죽는다"
+
+
+# 지문·기준 프레임 키의 교차언어 계약은 `tests/test_breathe_reference_key.py` 가 소유한다
+# (값 모양 전수 + 서버 페이로드 → 웹뷰 키 왕복). 여기 있던 이미지 기반 지문 비교는
+# 그 설계가 폐기되면서 같이 지웠다 — 두 파일이 같은 계약을 말하면 한쪽만 고쳐진다.
+
+
[email protected](shutil.which("node") is None, reason="node 가 없어 JS 미러를 실행할 수 없다")
[email protected]("anatomy_shape", ["fingerprint-null", "fingerprint-missing"],
+ ids=["null", "missing"])
+def test_the_mirror_refuses_when_it_cannot_verify(anatomy_shape, tmp_path):
+ """지문이 없으면 "확인 불가" 이지 "괜찮음" 이 아니다.
+
+ `refreshAnatomy` 가 실패하면 지문만 무효화한 해부가 남는데, 미러가 그걸 조용히
+ 통과시켜 낡은 숫자로 그렸다 — 굽기와 164바이트, 불투명 픽셀 수까지 불일치
+ (validator 실측 2026-07-26). `row-export` 가 같은 함수를 쓰므로 WebM/MP4 가 GIF 와
+ 다른 애니메이션으로 나갔다."""
+ src = _humanoid()
+ cfg = dict(CFG)
+ frozen = freeze_anatomy(src, cfg, _key())
+ if anatomy_shape == "fingerprint-null":
+ frozen = {**frozen, "fingerprint": None}
+ else:
+ frozen = {k: v for k, v in frozen.items() if k != "fingerprint"}
+ cfg["anatomy"] = frozen
+
+ harness = tmp_path / "fresh.cjs"
+ harness.write_text(
+ 'const fs=require("fs"),vm=require("vm");'
+ 'const P=JSON.parse(fs.readFileSync(process.argv[3],"utf8"));'
+ 'function mk(w,h,d){const b=Uint8ClampedArray.from(d);'
+ ' const c={imageSmoothingEnabled:false,getImageData:()=>({data:b,width:w,height:h}),'
+ ' putImageData:i=>b.set(i.data),createImageData:(a,e)=>({data:new Uint8ClampedArray(a*e*4),width:a,height:e}),'
+ ' drawImage:s=>b.set(s.__buf),clearRect:()=>{}};return{width:w,height:h,getContext:()=>c,__buf:b};}'
+ 'const sb={document:{createElement:()=>mk(P.w,P.h,new Array(P.w*P.h*4).fill(0))},console,'
+ 'entries:{},run:{states:[]},t:()=>"",setStatus:()=>{},fetch:()=>{},TextEncoder};'
+ 'sb.globalThis=sb;vm.createContext(sb);'
+ 'vm.runInContext(fs.readFileSync(process.argv[2],"utf8"),sb);'
+ 'let out;try{sb.breatheAssertFresh(P.key,P.cfg);out={ok:true};}'
+ 'catch(e){out={ok:false,refused:e.constructor.name==="BreatheRefused",message:e.message};}'
+ 'fs.writeFileSync(P.out,JSON.stringify(out));', encoding="utf-8")
+ src_json = tmp_path / "in.json"
+ src_json.write_text(json.dumps({
+ "w": src.width, "h": src.height, "rgba": _rgba(src),
+ "cfg": {"depth": cfg["depth"], "breaths": cfg["breaths"], "lag": cfg["lag"],
+ "anatomy": frozen},
+ "out": str(tmp_path / "out.json")}), encoding="utf-8")
+ proc = subprocess.run([shutil.which("node"), str(harness), str(CURATOR_BREATHE), str(src_json)],
+ capture_output=True, text=True)
+ assert proc.returncode == 0, f"node 하네스 실패:\n{proc.stderr}"
+ got = json.loads((tmp_path / "out.json").read_text(encoding="utf-8"))
+ assert not got["ok"] and got["refused"], (
+ f"지문 {anatomy_shape} 인데 미러가 신선하다고 판정했다 — 확인 불가는 괜찮음이 아니다")
diff --git a/tests/effects/test_breathe_off_state.py b/tests/effects/test_breathe_off_state.py
new file mode 100644
index 0000000..3c590b0
--- /dev/null
+++ b/tests/effects/test_breathe_off_state.py
@@ -0,0 +1,921 @@
+# SPDX-License-Identifier: Apache-2.0
+"""호흡을 **끈** 상태에서 큐레이터가 워프를 그리지 않는지 (소스 계약).
+
+봉투에서 위상 0 은 항등이 아니다 — 진행파 지연 때문에 `t=0` 도 변형된 프레임이다.
+그래서 "꺼짐"을 "위상 0" 으로 표현하면 안 된다: 굽기는 off 면 `state_breathe` 가 None
+이라 원본을 굽는데, 프리뷰는 워프된 정지화면을 보여준다 (실측 348~800B 차이,
+validator 검증 2026-07-25).
+
+`breatheComposite` 호출부는 전부 "호흡이 켜져 있는가"로 게이트돼야 한다. 소스 수준
+계약 테스트인 이유: 이 경로는 캔버스 렌더 루프 안이라 단위 실행이 어렵고, 되살아나는
+방식이 항상 "가드를 빼먹는" 형태라 호출부 형태를 고정하는 게 정확히 맞는 그물이다.
+(`tests/test_curator_pixel_scaling_ssot.py` 가 같은 방식의 선례다.)
+
+## 이 파일의 성격 — 증명이 아니라 **트립와이어**다 (maintainer 결정 2026-07-26)
+
+여기 있는 스캐너들은 정규식으로 JS 데이터플로를 **근사**한다. 근사이므로 우회할 수 있고,
+실제로 검증 라운드에서 열 번 넘게 새 우회가 발견됐다 (분기 · 흐름 · 사이트 수집 · 잎 판정 ·
+인벤토리 · 호출부 · 줄바꿈 · 문법 토큰 · 스코프 · 문자열 매칭). 매번 막았지만 매번 다음
+축이 나왔다 — **수렴하지 않는 접근**이라는 것이 그 자체로 결론이다.
+
+그래서 다음 사람(과 다음 검증자)에게 명시한다:
+
+- **새 우회 형태를 찾은 것은 결함 보고가 아니다.** 살아있는 결함(실제 코드가 지금 잘못
+ 동작한다)만 결함이다. "이렇게 리팩토링하면 그물이 못 잡는다" 는 이 파일의 알려진 한계다.
+- 계약을 **진짜로** 지키는 것은 동작 테스트다: `tests/test_breathe_reference_key.py` 가
+ 실제 `store.js`/`breathe.js` 를 node 로 돌려 서버 페이로드와 왕복 대조한다. 계약을
+ 강화할 여지가 있으면 **거기에** 추가하는 것이 옳고, 여기 정규식을 조이는 것이 아니다.
+- 이 스캐너들이 실제로 잡은 회귀는 `scripts/breathe_mutation_battery.py` 에 변이로 남아
+ 있다. 그물을 손대면 배터리 전건을 재실행한다 (새 변이만 확인하는 것으로는 부족하다 —
+ 그물 자신의 개선이 다른 축을 여는 일이 반복됐다).
+
+이 한계를 적어두는 이유는 원칙 6 이다: 못 하는 것을 못 한다고 말하지 않으면, 다음 사람이
+이 파일을 증명으로 믿는다.
+"""
+
+import re
+from pathlib import Path
+
+import pytest
+
+from sprite_gen.serve.serve_curation import CURATOR_DIR
+
+ROOT = Path(__file__).resolve().parent.parent.parent
+CURATOR_SRC = CURATOR_DIR / "src"
+CALL = re.compile(r"breatheComposite\s*\(|breatheComposeForPreview\s*\(")
+# 파이썬 굽기 소비자 — 위상 0 을 건너뛰면 그 슬롯만 원본이 구워진다.
+PY_CONSUMERS = ("sprite_gen/compose/compose_atlas.py", "sprite_gen/compose/compose_gif.py")
+PY_CALL = re.compile(r"phase_frame\s*\(|bake_breathe_sequence\s*\(")
+
+# 게이트는 **호출부 같은 줄**에 있어야 한다. 감싸는 블록까지 인정하면 그물이 무의미해진다
+# — 실측: 25줄 창으로 넓혔더니 무관한 `bm.enabled ?`(위상 계산 줄)가 걸려서, 정작 워프
+# 호출의 가드를 빼도 통과했다. 그래서 계약을 "호출부에서 삼항으로" 로 통일했다.
+# (`stateBreathe()` 가 꺼진 줄에 null 을 주므로 `bcfg ?` 도 유효한 켜짐 게이트다.)
+GUARDS = ("bm.enabled ?", "bcfg ?")
+
+
+def _strip_comments(src: str) -> str:
+ """주석을 공백으로 (줄 수·오프셋 보존). 주석 속 `/api/compare-gif` 언급이 파일 생성
+ 연산으로 잡히면 그물이 엉뚱한 자리를 지목한다."""
+ out, i, n = [], 0, len(src)
+ while i < n:
+ two = src[i:i + 2]
+ if two == "//":
+ j = src.find("\n", i)
+ j = n if j < 0 else j
+ out.append(" " * (j - i)); i = j
+ elif two == "/*":
+ j = src.find("*/", i + 2)
+ j = n if j < 0 else j + 2
+ out.append("".join(c if c == "\n" else " " for c in src[i:j])); i = j
+ else:
+ out.append(src[i]); i += 1
+ return "".join(out)
+
+
+# ── 문장 리더 — 그물 넷이 **같은 것**을 읽는다 ──────────────────────
+#
+# 앞선 판은 스캐너 넷이 전부 **줄 단위**로 읽었다. 그래서 잎 판정을 아무리 좁혀도 `\n`
+# 하나가 그 좁힘 전체를 우회했다 (노을이 탈출 J/J2/K 2026-07-26):
+#
+# const canonical = (canonImg && canonImg.complete) // <- 여기까지만 읽고 참
+# ? canonImg
+# : image; // <- 폴백이 안 보인다
+#
+# prettier 식 줄바꿈만 입히면 되므로 적대적 트릭이 필요 없다. 문장(깊이 0 의 `;` 까지)을
+# 단위로 읽으면 이 축이 통째로 사라진다.
+def _neutralize_literals(src: str, strip_comments: bool = False) -> str:
+ """문자열·템플릿·정규식 리터럴의 **내용만** `_` 로 덮는다 (구조·길이·줄수 보존).
+
+ `strip_comments=True` 면 주석도 **같은 패스**에서 지운다. 두 패스로 나누면 서로를
+ 오인한다 — 주석 제거를 먼저 하면 정규식 `/^\\/run\\//` 안의 `//` 를 줄주석으로 읽어
+ 그 줄 뒤를 통째로 날리고, 리터럴을 먼저 하면 주석 안의 따옴표에 걸린다.
+
+ 내용을 남기면 템플릿 리터럴의 `${...}` 중괄호가 문장을 끊고, 정규식의 `/`·`{` 도
+ 같은 짓을 한다 — 실제로 `cards.js` 의 `` `#${frame.index}` `` 한 줄이 문장 리더를
+ 무너뜨려 그 파일의 사이트가 통째로 어긋났다. 통째로 공백으로 지우면 `""`(빈 값 잎)
+ 같은 의미 있는 리터럴이 사라지므로, 따옴표는 남기고 안만 덮는다."""
+ out, i, n, prev = [], 0, len(src), ""
+ while i < n:
+ ch = src[i]
+ if strip_comments and src.startswith("//", i):
+ j = src.find("\n", i)
+ j = n if j < 0 else j
+ out.append(" " * (j - i))
+ i = j
+ continue
+ if strip_comments and src.startswith("/*", i):
+ j = src.find("*/", i + 2)
+ j = n if j < 0 else j + 2
+ out.append("".join(c if c == "\n" else " " for c in src[i:j]))
+ i = j
+ continue
+ if ch in "'\"":
+ j = i + 1
+ while j < n and src[j] != ch:
+ j += 2 if src[j] == "\\" else 1
+ out.append(ch + "".join("\n" if c == "\n" else "_" for c in src[i + 1:j]) + ch)
+ i = j + 1
+ prev = "x"
+ continue
+ if ch == "`":
+ j, tdepth = i + 1, 0
+ while j < n:
+ if src[j] == "\\":
+ j += 2
+ continue
+ if src[j] == "$" and j + 1 < n and src[j + 1] == "{":
+ tdepth += 1
+ j += 2
+ continue
+ if src[j] == "}" and tdepth:
+ tdepth -= 1
+ j += 1
+ continue
+ if src[j] == "`" and not tdepth:
+ break
+ j += 1
+ out.append("`" + "".join("\n" if c == "\n" else "_" for c in src[i + 1:j]) + "`")
+ i = j + 1
+ prev = "x"
+ continue
+ if ch == "/" and (prev == "" or prev in "(,=:[!&|?{;+-*%~^<>"):
+ j = i + 1
+ while j < n and src[j] not in "/\n":
+ j += 2 if src[j] == "\\" else 1
+ if j < n and src[j] == "/":
+ out.append("/" + "_" * (j - i - 1) + "/")
+ i = j + 1
+ prev = "x"
+ continue
+ out.append(ch)
+ if not ch.isspace():
+ prev = ch
+ i += 1
+ return "".join(out)
+
+
+def _statements(name: str):
+ """[(시작줄, 문장 텍스트)] — 주석·리터럴 중립화 후 깊이 0 의 `;`/`{`/`}` 로 끊는다."""
+ src = _neutralize_literals((CURATOR_SRC / name).read_text(encoding="utf-8"),
+ strip_comments=True)
+ out, buf, start, line = [], "", 1, 1
+ stack, prev = [], "" # stack: 열린 괄호 종류 ("(" "[" "{obj")
+ for ch in src:
+ if ch == "\n":
+ line += 1
+ buf += " "
+ continue
+ if ch in "([":
+ stack.append(ch)
+ elif ch in ")]":
+ if stack:
+ stack.pop()
+ elif ch == "{":
+ # **블록이냐 리터럴이냐** — 구조분해/객체 리터럴의 `{}` 를 문장 구분자로 쓰면
+ # `const { url: refUrl } = ...` 같은 선언이 토막난다(실제로 났다). 앞의 유의미
+ # 문자로 가른다: `=`·`(`·`,`·`:`·`?`·`return` 뒤면 값이고, 그 외는 블록이다.
+ # `const {` / `let {` / `var {` / `return {` 뒤도 값(구조분해·객체)이다 —
+ # 선언 키워드 뒤를 블록으로 읽으면 `const { url: refUrl } = ...` 가 토막나서
+ # 그 이름의 바인딩을 영영 못 찾고 "증명 불가 = 거짓" 으로 정상 코드를 오진한다.
+ tail = buf.rstrip().rsplit(" ", 1)[-1] if buf.strip() else ""
+ if prev in "=(,:?[&|" or tail in ("const", "let", "var", "return"):
+ stack.append("{obj")
+ elif not stack:
+ text = buf.strip()
+ if text:
+ out.append((start, text))
+ buf, start = "", line
+ prev = ch
+ continue
+ else:
+ stack.append("{blk")
+ elif ch == "}":
+ kind = stack.pop() if stack else None
+ if kind is None:
+ text = buf.strip()
+ if text:
+ out.append((start, text))
+ buf, start = "", line
+ prev = ch
+ continue
+ if not stack and ch == ";":
+ text = buf.strip()
+ if text:
+ out.append((start, text))
+ buf, start = "", line
+ prev = ch
+ continue
+ if not buf.strip():
+ start = line
+ buf += ch
+ if not ch.isspace():
+ prev = ch
+ if buf.strip():
+ out.append((start, buf.strip()))
+ return out
+
+
+def _js_files():
+ return [p.name for p in sorted(CURATOR_SRC.glob("*.js")) if p.name != "breathe.js"]
+
+
+def _inventory(sites):
+ got = {}
+ for name, *_ in sites:
+ got[name] = got.get(name, 0) + 1
+ return got
+
+
+def _assert_inventory(kind, got, expected):
+ """사이트 인벤토리는 **파일당 개수**까지 못박는다.
+
+ 존재만 보면 사이트가 여럿인 파일의 상실을 못 보고, 전역 "비어있지 않다" 만 보면
+ 파일 하나가 통째로 사라져도 통과한다. 둘 다 이 플랜에서 실제로 뚫린 형태다."""
+ assert got == expected, (
+ f"{kind} 인벤토리가 달라졌다.\n 기대: {expected}\n 실제: {got}\n"
+ " 줄었으면 사이트가 조용히 증발한 것이고(줄바꿈·이름 변경), 늘었으면 새 자리가"
+ " 계약에 들어온 것이다 — 어느 쪽이든 표를 같이 고쳐라.")
+
+
+EXPECTED_CALL_SITES = {"cards.js": 1, "compare.js": 1, "row-export.js": 1, "zoom-editor.js": 2}
+
+
+def _call_sites():
+ for name in _js_files(): # breathe.js 는 정의부 — 호출부가 아니다
+ for lineno, text in _statements(name):
+ if CALL.search(text):
+ yield name, lineno, text
+
+
+def test_there_are_call_sites_to_guard():
+ """호출부 **인벤토리**가 그대로여야 한다.
+
+ "비어있지 않다" 만 보면 한 자리가 줄바꿈 한 번으로 증발해도 통과한다 — 신호는
+ "테스트가 하나 줄었다" 뿐이고, 그건 이 플랜이 두 번 1급 계약으로 올린 실패 모드다."""
+ _assert_inventory("breatheComposite 호출부", _inventory(_call_sites()), EXPECTED_CALL_SITES)
+
+
[email protected]("site", list(_call_sites()), ids=lambda s: f"{s[0]}:{s[1]}")
+def test_every_breathe_composite_call_is_gated_on_enabled(site):
+ name, lineno, line = site
+ assert any(guard in line for guard in GUARDS), (
+ f"{name}:{lineno} 가 켜짐 여부로 게이트되지 않았다 — 꺼진 줄이 워프된다.\n"
+ f" {line}\n"
+ f" 허용 형태: {', '.join(GUARDS)}")
+
+
+# ── 파이썬 굽기 소비자 ──────────────────────────────────────────────
+
+def _py_call_sites():
+ for rel in PY_CONSUMERS:
+ path = ROOT / rel
+ if not path.is_file():
+ continue
+ lines = path.read_text(encoding="utf-8").splitlines()
+ for lineno, line in enumerate(lines, 1):
+ if PY_CALL.search(line) and not line.lstrip().startswith("#"):
+ # 이 호출을 감싸는 가장 가까운 `if` 조건 (들여쓰기가 더 얕은 첫 if)
+ indent = len(line) - len(line.lstrip())
+ guard = ""
+ for prev in range(lineno - 2, -1, -1):
+ cand = lines[prev]
+ if not cand.strip():
+ continue
+ cind = len(cand) - len(cand.lstrip())
+ if cind < indent and cand.lstrip().startswith("if "):
+ guard = cand.strip()
+ break
+ if cind < indent:
+ break
+ yield rel, lineno, line.strip(), guard
+
+
+def test_there_are_python_bake_call_sites():
+ assert list(_py_call_sites()), "굽기 소비자에서 호흡 호출부가 사라졌다 — 계약 위치 확인"
+
+
[email protected]("site", list(_py_call_sites()), ids=lambda s: f"{s[0].split('/')[-1]}:{s[1]}")
+def test_python_bake_never_skips_a_phase(site):
+ """굽기가 **위상 값으로** 워프 여부를 가르면 안 된다.
+
+ `if breathe_cfg and breathe_phase:` 는 위상 0 슬롯을 건너뛰어 그 칸만 원본이 되고,
+ 같은 런의 GIF 굽기와 그림이 갈린다 (round-1 reject 1, 실측 353px). 게이트는
+ "호흡이 켜져 있는가"(`breathe_cfg`)만 봐야 한다.
+
+ 이 그물이 필요한 이유: validator가 변이 테스트로 확인했다 — `compose_atlas` 의 가드를
+ 옛 형태로 되돌려도 `pytest -k "atlas or breathe"` 40개가 **전부 통과**했다.
+ JS 쪽엔 그물이 있었고 파이썬 쪽만 비어 있었다 (2026-07-25)."""
+ rel, lineno, line, guard = site
+ assert "phase" not in guard.replace("breathe_cfg", ""), (
+ f"{rel}:{lineno} 의 가드가 위상 값을 본다 — 위상 0 이 안 구워진다.\n"
+ f" 가드: {guard}\n 호출: {line}")
+
+
+# ── 줄 단위 신선도 검사가 실제로 걸리는가 ──────────────────────────
+
+PREVIEW_CALL = re.compile(r"breatheComposeForPreview\s*\(([^;]*)\)")
+FRESH = re.compile(r"breatheAssertFresh\s*\(")
+
+
+EXPECTED_PREVIEW_SITES = {"cards.js": 1, "compare.js": 1, "zoom-editor.js": 2}
+
+
+def _preview_call_sites():
+ for name in _js_files():
+ for lineno, text in _statements(name):
+ m = PREVIEW_CALL.search(text)
+ if m:
+ yield name, lineno, text, m.group(1)
+
+
+def test_there_are_preview_call_sites():
+ _assert_inventory("프리뷰 호출부",
+ _inventory(_preview_call_sites()), EXPECTED_PREVIEW_SITES)
+
+
[email protected]("site", list(_preview_call_sites()), ids=lambda s: f"{s[0]}:{s[1]}")
+def test_every_preview_call_passes_a_freshness_reference(site):
+ """프리뷰 호출부는 **전부** 기준 프레임을 넘겨야 한다.
+
+ round-7 은 `reference` 를 선택 인자로 뒀고 5곳 중 2곳만 넘겼다. 나머지 3곳은
+ `if (reference)` 를 통째로 건너뛰어, 같은 웹뷰의 두 화면이 정반대로 행동했다 —
+ 줄 카드는 거부하는데 호흡 편집 모달은 낡은 숫자로 조용히 그렸다 (validator 실측
+ 2026-07-26: 12/12 위상 갈림, 알림 0건). round-2 가 켜짐 게이트를 호출부 전수
+ 파라미터화로 고정한 것과 같은 형태의 그물이다."""
+ name, lineno, line, args = site
+ # `breatheComposeForPreview(a, b, c, ref)` — 인자 4개여야 한다
+ depth = 0
+ parts, cur = [], ""
+ for ch in args:
+ if ch in "([{":
+ depth += 1
+ elif ch in ")]}":
+ depth -= 1
+ if ch == "," and depth == 0:
+ parts.append(cur.strip()); cur = ""
+ else:
+ cur += ch
+ parts.append(cur.strip())
+ assert len(parts) >= 4 and parts[3], (
+ f"{name}:{lineno} 가 기준 프레임을 안 넘긴다 — 신선도 검사가 건너뛰어진다.\n {line}")
+
+
+# ── 파일을 만드는 자리는 전부 신선도를 본다 ────────────────────────
+
+# 사용자 손에 **파일**이 떨어지는 연산. 프리뷰 래퍼는 거부를 잡아 원본을 돌려주므로
+# (화면에선 옳다) 이 자리에 신선도 검사가 없으면 호흡이 빠진 파일이 조용히 나간다.
+# 파일을 만드는 연산. **두 축**이다:
+# - 캔버스 축(`toDataURL`/`toBlob`) — 코드에 그대로 있다.
+# - 엔드포인트 축(`/api/...`) — **문자열 리터럴 안에만** 있다.
+# 리터럴 중립화한 소스에서 후자를 찾으면 영원히 0건이다(라운드 9 가 중립화를 통일하면서
+# 그 축을 조용히 죽였다 — 현행 두 경로가 우연히 `toDataURL` 도 써서 초록이었을 뿐이다).
+# 그래서 엔드포인트 축은 **원문**에서 찾는다 (노을이 M2 실측 2026-07-26).
+FILE_PRODUCERS = re.compile(r"toDataURL\s*\(|toBlob\s*\(")
+FILE_PRODUCER_URLS = re.compile(r"/api/compare-gif|/api/row-video")
+FRESH = re.compile(r"breatheAssertFresh\s*\(")
+
+# 호흡 계약이 사는 파일 안에서 파일을 만드는 **모든** 함수가 대상이다.
+# 손으로 적은 파일 화이트리스트(`FRESH_CONSUMERS = ("row-export.js",)`)로 쓰면 안 된다:
+# 그 판일 때 `compare.js` 의 영상 다운로드가 호흡을 조용히 뺀 파일을 만들고 있었는데
+# 그물은 아무 말도 안 했다 (validator 실측 2026-07-26). 대상은 이름이 아니라 **연산**이다.
+# 파일을 만들지만 **호흡 경로가 아닌** 자리 — 면제는 파일 단위로, 이유와 함께.
+NON_BREATHE_PRODUCERS = {
+ "base-editor.js": "베이스 이미지 편집 업로드 — 호흡 레이어를 안 거친다 (/api/base-edit)",
+}
+
+
+HEADER = re.compile(r"(function\s*\w*\s*\([^)]*\)|\([^()]*\)\s*=>|\w+\s*=>)\s*$")
+
+
+def _enclosing_function(src: str, pos: int) -> tuple[str, int] | None:
+ """`pos` 를 감싸는 **가장 안쪽 함수 본문**과 그 시작줄.
+
+ 줄 기준 휴리스틱으로 자르면 `const gcd = (a, b) => ...` 같은 한 줄 화살표 함수가
+ 다음 함수 시작으로 잡혀 뒤따르는 본문을 통째로 삼킨다 — 그러면 검사가 있는데도
+ 없다고 보고한다. 중괄호를 세어 진짜 블록을 찾는다."""
+ stack = []
+ for i, ch in enumerate(src[:pos]):
+ if ch == "{":
+ stack.append(i)
+ elif ch == "}" and stack:
+ stack.pop()
+ for open_at in reversed(stack):
+ if not HEADER.search(src[max(0, open_at - 200):open_at]):
+ continue
+ depth = 0
+ for j in range(open_at, len(src)):
+ if src[j] == "{":
+ depth += 1
+ elif src[j] == "}":
+ depth -= 1
+ if depth == 0:
+ return src[open_at:j + 1], src[:open_at].count("\n") + 1
+ return src[open_at:], src[:open_at].count("\n") + 1
+ return None
+
+
+def _file_producing_functions():
+ """(파일, 시작줄, 본문) — 파일을 만드는 연산을 감싼 함수 전수 (중복 제거).
+
+ **큐레이터 전 파일**을 훑는다. `BREATHE_FILES` 로 한정하면 내보내기 플러밍을 공용
+ 헬퍼로 빼는 흔한 DRY 리팩토링만으로 그 함수가 수집에서 통째로 증발한다 — 그리고
+ 같은 커밋에서 신선도 게이트를 지워도 540 passed, 기준선과 개수까지 동일이었다
+ (노을이 탈출 L 실측 2026-07-26). 이 그물이 잡으려고 존재하는 **역사적 버그 그 자체**가
+ 원문 그대로 되살아나도 신호가 없었다.
+
+ 리터럴·주석은 문장 리더와 **같은 중립화**를 쓴다 — 두 리더가 다른 것을 보면 한쪽에만
+ 보이는 자리가 생긴다."""
+ out, seen = [], set()
+ for name in (p.name for p in sorted(CURATOR_SRC.glob("*.js"))):
+ if name in NON_BREATHE_PRODUCERS:
+ continue
+ raw = (CURATOR_SRC / name).read_text(encoding="utf-8")
+ src = _neutralize_literals(raw, strip_comments=True)
+ stripped = _strip_comments(raw)
+ # 캔버스 축은 중립화 소스에서, 엔드포인트 축은 **원문**(주석만 제거)에서 찾는다.
+ spots = {m.start() for m in FILE_PRODUCERS.finditer(src)}
+ spots |= {m.start() for m in FILE_PRODUCER_URLS.finditer(stripped)}
+ for start in sorted(spots):
+ found = _enclosing_function(src, start)
+ assert found, f"{name}:{src[:start].count(chr(10)) + 1} 를 감싼 함수를 못 찾았다"
+ body, line = found
+ if (name, line) in seen:
+ continue
+ seen.add((name, line))
+ out.append((name, line, body))
+ return out
+
+
+EXPECTED_FILE_PRODUCERS = {"compare.js": 1, "row-export.js": 1}
+
+
+def test_every_file_producing_path_checks_freshness():
+ """파일을 만드는 자리는 **전부** 기준 프레임 신선도를 확인해야 한다.
+
+ `row-export` 는 예외를 올려 파일 생성 전에 멈췄는데 `compare.js` 의 영상
+ 다운로드는 프리뷰 래퍼를 거쳐 거부를 삼켰다 — 같은 조건에서 두 내보내기가
+ **정반대로** 행동했고, 호흡 없는 파일이 나간 뒤 초록 "완료" 알림까지 떴다."""
+ sites = _file_producing_functions()
+ _assert_inventory("파일 생성 경로", _inventory(sites), EXPECTED_FILE_PRODUCERS)
+ missing = [(n, ln) for n, ln, body in sites if not FRESH.search(body)]
+ assert not missing, (
+ "파일을 만드는데 신선도를 안 본다 — 낡은 해부로 구운 파일이 사용자에게 간다:\n"
+ + "\n".join(f" {n}:{ln}" for n, ln in missing))
+
+
+# ── 호흡은 굽기가 읽는 파일로 그린다 ───────────────────────────────
+
+# 굽기 파일에 도달하는 **인정 경로**. `bakeFrameUrl` 직접 호출이거나, 그것을 거쳐
+# URL 을 내주는 store 헬퍼에서 받은 값이거나. 이름 화이트리스트가 아니라 **출처**다 —
+# 헬퍼 자신은 `bakeFrame` 을 거치고, 그 선택은 node 동작 테스트가 따로 검증한다
+# (`tests/test_breathe_reference_key.py::test_geometry_measures_the_reference_frame...`).
+BAKE_SOURCES = ("bakeFrameUrl(", "breatheGeometryFrame(")
+BAKE_HEAD = re.compile(r"(?:bakeFrameUrl|breatheGeometryFrame)\s*\(")
+
+
+def _is_bake_call(expr: str) -> bool:
+ """식 **전체**가 정확히 굽기 소스 호출인가 (뒤따르는 프로퍼티 접근만 허용).
+
+ 정규식 `fullmatch` + 탐욕 `.*` 로 판정하면 `bakeFrameUrl(a) ?? frameUrl(b)` 도,
+ `bakeFrameUrl(a) , frameUrl(b)` 도 참이 된다 — 탈출 G 에서 없앤 "부분문자열 관대함" 이
+ 정규식 형태로 되돌아온 것이다. 인자 괄호를 **세어** 호출이 어디서 끝나는지 보고,
+ 그 뒤에 뭐가 더 있으면 거짓이다. 이러면 같은 축의 다음 철자(새 연산자)도 안 샌다."""
+ if not BAKE_HEAD.match(expr):
+ return False
+ depth = 0
+ for i, ch in enumerate(expr):
+ if ch == "(":
+ depth += 1
+ elif ch == ")":
+ depth -= 1
+ if depth == 0:
+ rest = expr[i + 1:].strip()
+ return rest == "" or bool(re.fullmatch(r"(?:\.\w+)+", rest))
+ return False
+IMG_CALL = re.compile(r"\bimg\s*\(")
+# 호흡 계약이 사는 파일 — 이 안의 **모든** 프레임 이미지 소스가 굽기 파일이어야 한다.
+#
+# 변수명 화이트리스트로 쓰면 안 된다: round-9 판은 `zoom-editor.js: ("image",)` 였고,
+# 그래서 `const canonImg = img(fr.url)` 로 지오메트리를 재던 자리가 **스캔 대상에조차
+# 없었다** (validator 실측 2026-07-26: 경계가 8px 어긋났는데 그물은 조용했다). 이름이
+# 아니라 **파일 전체**를 훑고, 호흡과 무관한 줄만 명시적으로 면제한다.
+BREATHE_FILES = ("cards.js", "compare.js", "zoom-editor.js", "row-export.js")
+# 호흡 경로가 아닌 이미지 소스 (표시·썸네일 등) — 면제는 **이유와 함께** 명시한다.
+NON_BREATHE_IMG = {
+ ("cards.js", "image"): "카드 표시면 — 호흡 합성 전 원본 표시 (frameUrl 이 맞다)",
+}
+
+
+EMPTY_LEAF = re.compile(r"^(null|undefined|false|0|\"\"|\'\')$")
+
+
+# 자르면 안 되는 2글자 토큰 — `?` 로 시작하지만 삼항이 아니다.
+# `??` 는 **분기**라 따로 자르고(아래), `?.`·`=>` 는 통째로 지나가야 한다.
+ATOMIC = ("??", "?.", "=>", "===", "!==", "==", "!=", ">=", "<=")
+
+
+def _split_top(expr: str, seps: tuple[str, ...]) -> list[str]:
+ """괄호 깊이 0 에서만 자른다 (`?:` 는 `?` 와 `:` 를 짝으로 다룬다).
+
+ `??`·`?.` 같은 원자 토큰은 통째로 지나간다 — 안 그러면 `a ?? b` 를 삼항으로 잘못
+ 쪼개고, 쪼개다 실패하면 잎으로 떨어져 **분기 전수 판정이 통째로 우회된다**
+ (노을이 탈출 M 2026-07-26)."""
+ out, cur, depth, i = [], "", 0, 0
+ while i < len(expr):
+ ch = expr[i]
+ if depth == 0:
+ atom = next((a for a in ATOMIC if expr.startswith(a, i) and a not in seps), None)
+ if atom:
+ cur += atom
+ i += len(atom)
+ continue
+ if ch in "([{":
+ depth += 1
+ elif ch in ")]}":
+ depth -= 1
+ if depth == 0:
+ for sep in seps:
+ if expr.startswith(sep, i):
+ out.append(cur); cur = ""; i += len(sep); break
+ else:
+ cur += ch; i += 1
+ continue
+ cur += ch; i += 1
+ out.append(cur)
+ return [x.strip() for x in out]
+
+
+def _neutral_src(name: str) -> str:
+ return _neutralize_literals((CURATOR_SRC / name).read_text(encoding="utf-8"),
+ strip_comments=True)
+
+
+def _line_start(src: str, lineno: int) -> int:
+ """1-기반 줄 번호의 시작 오프셋."""
+ pos, line = 0, 1
+ while line < lineno:
+ nxt = src.find("\n", pos)
+ if nxt < 0:
+ return len(src)
+ pos, line = nxt + 1, line + 1
+ return pos
+
+
+def _enclosing_spans(src: str, pos: int):
+ """`pos` 를 감싸는 함수 본문들 — [(여는{ 오프셋, 닫는} 오프셋, 헤더텍스트)], 안쪽부터."""
+ stack = []
+ for i, ch in enumerate(src[:pos]):
+ if ch == "{":
+ stack.append(i)
+ elif ch == "}" and stack:
+ stack.pop()
+ out = []
+ for open_at in reversed(stack):
+ header = src[max(0, open_at - 200):open_at]
+ if not HEADER.search(header):
+ continue
+ depth, close = 0, len(src)
+ for j in range(open_at, len(src)):
+ if src[j] == "{":
+ depth += 1
+ elif src[j] == "}":
+ depth -= 1
+ if depth == 0:
+ close = j
+ break
+ out.append((open_at, close, header))
+ return out
+
+
+PARAMS = re.compile(r"\(([^()]*)\)\s*(?:=>)?\s*$")
+
+
+def _param_names(header: str) -> set:
+ m = PARAMS.search(header.rstrip())
+ if not m:
+ return set()
+ return {t.strip().split(":")[0].strip() for t in m.group(1).split(",") if t.strip()}
+
+
+def _reassigned(name: str, symbol: str) -> bool:
+ """`symbol` 이 선언 밖에서 다시 대입되는가.
+
+ `_bake_only` 는 이름을 만나면 **선언만** 읽는다. 그래서 `const` 를 `let` 으로 바꾸고
+ 가드 본문에서 되돌리면 그물이 침묵했다:
+
+ let canonical = canonSrc ? img(canonSrc) : null;
+ if (!(canonical && canonical.complete)) canonical = image; // <- 무사통과
+
+ 선언 RHS 가 굽기 소스라 참을 주고 그 뒤 흐름을 안 봤다 — 그물이 자기 규칙("증명 못
+ 하는 이름은 거짓")을 자기가 어긴 것이다. 재대입된 이름은 증명된 이름이 아니다."""
+ sym = re.escape(symbol)
+ decl = re.compile(rf"\b(const|let|var)\s+({sym}\b|\{{[^}}]*\b{sym}\b[^}}]*\}})\s*=")
+ assign = re.compile(rf"(^|[^\w.]){sym}\s*(=(?![=>])|\+=|\|\|=|\?\?=)")
+ return any(assign.search(t) and not decl.search(t) for _, t in _statements(name))
+
+
+def _binding_rhs(name: str, lineno: int, symbol: str):
+ """`symbol` 의 선언(위쪽)과 그 시작줄. 못 찾거나 **재대입되면** None.
+
+ **문장 단위**로 읽는다. 줄 단위(`prev.split("=", 1)[1]`)로 읽던 판은 RHS 가 다음
+ 줄로 넘어가면 뒷부분이 통째로 안 보였고, 잘린 머리가 참을 줬다 — prettier 식
+ 줄바꿈만으로 분기 전수 판정이 통째로 우회됐다 (노을이 탈출 J 2026-07-26).
+
+ 구조분해(`const { url: refUrl } = breatheGeometryFrame(...)`)도 읽는다."""
+ if _reassigned(name, symbol):
+ return None # 흐름에 따라 값이 바뀐다 = 증명 불가
+ # **스코프**를 본다. 예전엔 파일 전체에서 "그 줄 앞의 마지막 선언" 을 찾아, 그리는
+ # 자리가 **함수 파라미터**를 받으면 같은 파일 위쪽의 무관한 `const image = ...` 가
+ # 그 파라미터를 증명해버렸다 — 실제 인자는 호출부에 있고 호출부는 수집되지도 않는다.
+ # 두 블록이 거의 같아 그리기를 헬퍼로 빼는 **평범한 DRY 리팩토링**만으로 도달했고,
+ # 540 passed(기준선과 개수까지 동일)였다 (노을이 탈출 N 2026-07-26).
+ src = _neutral_src(name)
+ spans = _enclosing_spans(src, _line_start(src, lineno))
+ if spans and symbol in _param_names(spans[0][2]):
+ return None # 파라미터 = 값이 호출부에 있다 = 증명 불가
+ sym = re.escape(symbol)
+ direct = re.compile(rf"\b(const|let|var)\s+{sym}\b\s*=")
+ destructured = re.compile(rf"\b(const|let|var)\s*\{{[^}}]*\b{sym}\b[^}}]*\}}\s*=")
+ best = None
+ for start, text in _statements(name):
+ if start > lineno:
+ break
+ if direct.search(text) or destructured.search(text):
+ # 선언이 사이트의 **스코프 체인 안**에 있어야 한다. 형제 스코프의 동명 바인딩은
+ # 이 자리를 증명하지 못한다 (자기 계약: 증명 못 하면 거짓).
+ at = _line_start(src, start)
+ if spans and not any(o < at < c for o, c, _ in spans):
+ continue
+ best = (text.split("=", 1)[1].strip(), start)
+ return best
+
+
+def _bake_only(name: str, lineno: int, expr: str, depth: int = 8) -> bool:
+ """`expr` 이 **모든 분기에서** 굽기 소스이거나 빈 값인가.
+
+ "굽기 소스에 닿는가" 로는 부족하다 — 앞선 판은 도달만 보고 True 를 줬고, 그래서
+ 폐기된 폴백을 한 줄 변수 추출로 원문 그대로 되살려도 537 전부 통과했다:
+
+ const canonImg = canonSrc ? img(canonSrc) : null;
+ const canonical = (canonImg && canonImg.complete) ? canonImg : image; // <- 무사통과
+
+ 워커가 `canonImg` 를 따라 `bakeFrameUrl` 에 닿으면 참을 돌려주고, **같은 바인딩의
+ `: image` 가지를 안 봤다.** 그물을 강화하려고 넣은 전이 추적이 정확히 그 탈출구를 열었다
+ (노을이 실측 2026-07-26 R1). 그래서 도달이 아니라 **분기 전수**로 판정한다.
+
+ 증명 못 하면 거짓이다 — 못 찾은 이름(파라미터·상위 스코프)을 통과시키면 같은 구멍이 난다.
+
+ 예산(`depth`)은 **바인딩을 따라갈 때만** 깎는다. 삼항·`&&`·`||` 분해는 같은 식을 쪼개는
+ 것이라 홉이 아닌데, 거기서도 깎으면 정상 체인이 예산 고갈로 거짓이 되어 오진한다."""
+ if depth <= 0:
+ return False
+ expr = expr.strip()
+ while expr.startswith("(") and expr.endswith(")") and len(_split_top(expr[1:-1], (",",))) == 1:
+ expr = expr[1:-1].strip()
+ if not expr:
+ return False
+ # 삼항: 두 가지가 **모두** 성립해야 한다 (조건절은 값이 아니다)
+ parts = _split_top(expr, ("?",))
+ if len(parts) == 2:
+ branches = _split_top(parts[1], (":",))
+ if len(branches) == 2:
+ return all(_bake_only(name, lineno, b, depth) for b in branches)
+ # `||`·`??` 는 분기다 — 모든 피연산자가 성립해야 한다.
+ # `??` 를 빠뜨렸더니 "굽기 URL 이 없으면 표시 URL" 을 `??` 로 적는 것만으로 그물 둘이
+ # 동시에 침묵했다. 그건 적대적 트릭이 아니라 **린터가 권하는 표현**이고, `bakeFrameUrl`
+ # 은 plain+트윈없음에서 실제로 `null` 을 돌려주므로 그 폴백은 진짜로 발화한다.
+ for op in ("||", "??"):
+ parts = _split_top(expr, (op,))
+ if len(parts) > 1:
+ return all(_bake_only(name, lineno, o, depth) for o in parts)
+ # 콤마 연산자도 분기다 (값은 마지막이지만, 앞 항이 굽기 소스라고 통과시키면 안 된다)
+ commas = _split_top(expr, (",",))
+ if len(commas) > 1:
+ return all(_bake_only(name, lineno, c, depth) for c in commas)
+ # `&&` 는 가드 + 값 — 마지막 피연산자만 값이다
+ ands = _split_top(expr, ("&&",))
+ if len(ands) > 1:
+ return _bake_only(name, lineno, ands[-1], depth)
+ # 잎 — 여기서 참을 주는 형태를 **좁게 열거**한다. 넓게 열면 매 라운드 새 우회가 생겼다.
+ if EMPTY_LEAF.match(expr):
+ return True # 값 없음 = 워프 안 함 (폴백이 아니다)
+ # 굽기 소스는 "그 식이 **그 호출이다**" 여야 한다. `src in expr` 부분문자열 판정은
+ # `imgOrDisplay(bakeFrameUrl(...), image)` 처럼 굽기 소스를 **인자로 품은** 임의의
+ # 호출에 참을 준다 — 폴백을 두 번째 인자로 숨기면 그만이다 (노을이 탈출 G).
+ if _is_bake_call(expr):
+ return True
+ # 호출 투명성은 `img(` **하나에만** 준다. `[\w.]+\(x\)` 로 열어두면 폐기된 폴백을
+ # 한 인자 헬퍼에 넣는 것만으로 통과한다 — 그물이 인자만 보고 헬퍼가 그걸로 무엇을
+ # 하는지 한 번도 안 본다 (노을이 탈출 F 실측 2026-07-26: 538 passed, 기준선과 동일):
+ #
+ # const readyOr = (c) => (c && c.complete) ? c : image;
+ # const canonical = readyOr(canonImg); // <- 무사통과였다
+ #
+ # 자기 계약("증명 못 하는 이름은 거짓")과 맞추려면 아는 함수만 투명해야 한다.
+ call = re.fullmatch(r"img\(\s*([\w.]+)\s*\)", expr)
+ if call:
+ return _bake_only(name, lineno, call.group(1), depth - 1)
+ if re.fullmatch(r"[\w.]+", expr):
+ found = _binding_rhs(name, lineno, expr.split(".")[0])
+ if not found:
+ return False # 증명 불가 = 거짓
+ rhs, at = found
+ return _bake_only(name, at, rhs, depth - 1)
+ return False
+
+
+def _bound_from_bake_source(name: str, lineno: int, symbol: str) -> bool:
+ """호환 진입점 — 판정은 `_bake_only` 하나가 소유한다."""
+ return _bake_only(name, lineno, symbol)
+
+
+def _breathe_image_sites():
+ for name in BREATHE_FILES:
+ for lineno, text in _statements(name):
+ m = re.match(r"(?:const|let|var)\s+(\w+)\s*=", text)
+ if not (m and IMG_CALL.search(text)):
+ continue
+ if (name, m.group(1)) in NON_BREATHE_IMG:
+ continue
+ yield name, lineno, text
+
+
+EXPECTED_IMAGE_SITES = {"cards.js": 1, "compare.js": 1, "zoom-editor.js": 4, "row-export.js": 1}
+
+
+def test_there_are_breathe_image_sites():
+ sites = list(_breathe_image_sites())
+ assert sites, "호흡 이미지 소스 지점이 사라졌다 — 계약 위치 확인"
+ got = {}
+ for name, _, _ in sites:
+ got[name] = got.get(name, 0) + 1
+ assert got == EXPECTED_IMAGE_SITES, (
+ f"호흡 이미지 사이트 인벤토리가 달라졌다.\n 기대: {EXPECTED_IMAGE_SITES}\n"
+ f" 실제: {got}\n"
+ " 선언 키워드·대입 모양을 바꾸면 사이트가 조용히 증발한다 — 파일 존재만 보면 "
+ "여러 사이트를 가진 파일의 상실을 못 본다(워프 base 스캐너가 그렇게 뚫렸다).")
+
+
[email protected]("site", list(_breathe_image_sites()), ids=lambda s: f"{s[0]}:{s[1]}")
+def test_breathe_draws_from_the_file_the_bake_reads(site):
+ """워프 base 도 신선도 기준도 **굽기가 읽는 파일**에서 와야 한다.
+
+ `frameUrl` 은 표시용이라 pp OFF 에서 `orig/` 고해상 트윈을 준다 — 굽기(`row_frame_rel`)
+ 는 그 파일을 절대 안 읽는다. 기준이 굽기가 안 읽는 파일이면 지문이 **영구 불일치**라
+ 해부를 갱신해도 안 풀리고 그 줄의 영상 내보내기가 영구 차단된다. 캐노니컬(`f.url`)로
+ 그리면 pp OFF 줄에서 굽기와 다른 그림이 나간다 (validator 2026-07-26: 같은 캔버스를
+ 다른 해부로 워프해 4위상에서 최대 114바이트).
+
+ 이 그물이 없던 동안 `frameUrl` → `f.url` 로 되돌려도 111개 테스트가 전부 통과했다."""
+ name, lineno, line = site
+ # 판정은 **`_bake_only` 하나**가 소유한다 — 형제 스캐너(워프 base)와 같은 판정기다.
+ #
+ # 앞선 판은 여기서만 옛 관대함을 들고 있었다: (a) 줄에서 첫 `img(` 인자 **한 심볼**만
+ # 뽑아 봐서 같은 선언의 다른 분기가 안 보였고(탈출 C 의 분기 사각이 축만 바꿔 재발),
+ # (b) 줄 **부분문자열** 지름길(`bakeFrameUrl(` 이 어딘가 있으면 통과)이 탈출 G 에서 잎에서는 없앤 그
+ # 관대함을 그대로 남겨뒀다. 그래서 `img(refUrl || frameUrl(...))` 같은 폴백이 540 passed
+ # 로 통과했다 (노을이 탈출 I 실측 2026-07-26).
+ #
+ # 판정기를 좁히면 **모든 호출부가 같이 좁아져야** 한다. 한 곳만 고치면 다음 우회가
+ # 안 고친 쪽으로 간다 — 이 플랜에서 여섯 라운드 반복된 형태다.
+ rhs = line.split("=", 1)[1].strip().rstrip(";") if "=" in line else line
+ assert _bake_only(name, lineno, rhs), (
+ f"{name}:{lineno} 의 어떤 분기가 굽기 파일이 아니다.\n {line}\n"
+ f" `bakeFrameUrl(state, frame)` 또는 그걸 거치는 store 헬퍼를 써라 "
+ f"(frameUrl 은 표시용, f.url 은 캐노니컬).")
+
+
+# ── 고칠 수 없는 차이도 관측 가능해야 한다 ──────────────────────────
+
+RESAMPLE_NOTICE = re.compile(r"breatheResamplesDifferently\s*\(")
+
+
+def test_file_producing_paths_report_the_resampler_gap():
+ """회전·확대가 걸린 줄은 프리뷰와 굽기의 **픽셀이 다르다** — 말은 해야 한다.
+
+ 굽기는 `apply_transform` 에서 BICUBIC(`snap_scale` 없는 런 = 기본 런 전부),
+ 웹뷰는 `imageSmoothingEnabled=false` 캔버스라 NEAREST 다. 실측 (validator 2026-07-26,
+ 96px 픽스처, 신선도는 통과시킨 상태): rotate 3° 에서 12/12 위상 최대 1803px 상이,
+ scale 1.03 에서 최대 1699px. 원인은 표시 파이프라인이라 호흡이 고칠 수 있는 게
+ 아니지만, `row-export` 와 비교뷰 다운로드는 **이 캔버스로 파일을 굽는다** —
+ 조용히 두면 사용자는 GIF 와 다른 파일을 받고도 모른다 (원칙 6).
+
+ "고칠 수 없으니 말하지 않는다" 는 이 플랜에서 금지된 형태다."""
+ for name, line, body in _file_producing_functions():
+ assert RESAMPLE_NOTICE.search(body), (
+ f"{name}:{line} 이 파일을 만들면서 리샘플러 차이를 안 알린다 — "
+ "사용자는 GIF 와 다른 파일을 받고도 모른다")
+
+
+def test_the_warn_notice_has_a_visible_style():
+ """`warn` 알림이 스타일 없이 나가면 '알렸다' 가 사실상 거짓이 된다."""
+ css = (CURATOR_SRC.parent / "curator.css").read_text(encoding="utf-8")
+ assert ".status.warn" in css, "warn 알림에 스타일이 없다 — 오류·성공과 구분이 안 된다"
+
+
+# ── 워프 base 는 폴백하지 않는다 ────────────────────────────────────
+
+# 워프 base 사이트는 **이름이 아니라 의미**로 모은다.
+#
+# 앞선 판은 `drawFrameInto\(\s*(\w*[Bb]aseCtx)` 로 ctx **이름**을 훑었다. 그 패턴에 걸리는
+# 자리는 레포 전체에 2곳뿐이었고, `baseCtx` 를 `warpCtx` 로 바꾸는 것만으로 cards.js 가
+# 통째로 스캐너에서 사라지면서 폴백을 원문 그대로 되살려도 537 passed 였다 — 개수까지
+# 기준선과 같아서 테스트가 사라진 신호조차 없었다 (노을이 실측 2026-07-26).
+#
+# 그래서 사이트를 **호흡 워프에 실제로 들어가는 캔버스**에서 역산한다:
+# breatheComposite(X, ...) / breatheComposeForPreview(X, ...) -> 캔버스 X
+# const <ctx> = X.getContext(...) -> 그 캔버스의 ctx
+# drawFrameInto(<ctx>, ARG, ...) -> ARG 가 워프 base 다
+# 이름을 바꿔도 역산이 따라가므로 리네임으로 빠져나갈 수 없다. 덤으로 `bx` 처럼 이름이
+# 다른 자리 3곳(compare·row-export·zoom-editor 두 번째)도 이제 계약에 들어온다 —
+# row-export 는 프리뷰가 아니라 **WebM 파일을 굽는** 경로다.
+COMPOSITE_CALL = re.compile(r"breathe(?:Composite|ComposeForPreview)\(\s*(\w+)")
+CTX_BIND = re.compile(r"\b(?:const|let|var)\s+(\w+)\s*=\s*(\w+)\.getContext\(")
+DRAW_INTO = re.compile(r"drawFrameInto\(\s*(\w+)\s*,\s*([^,]+),")
+# 워프 base **인벤토리** — 파일마다 몇 곳인지까지 못박는다.
+#
+# "파일에 하나라도 있나" 만 보면 사이트가 2곳인 파일(zoom-editor)은 하나가 사라져도
+# 못이 안 운다. 그 자리에 조용한 표시파일 폴백을 되살리면 538 passed, **기준선과 개수까지
+# 동일**이었다 (노을이 탈출 H 실측 2026-07-26). ctx 바인딩을 헬퍼로 묶는 자연스러운 DRY
+# 리팩토링만으로 도달한다 — 적대적 트릭이 필요 없다.
+EXPECTED_WARP_BASES = {"cards.js": 1, "compare.js": 1, "zoom-editor.js": 2, "row-export.js": 1}
+
+
+def _warp_base_sites():
+ for name in BREATHE_FILES:
+ stmts = _statements(name)
+ joined = " ".join(t for _, t in stmts)
+ canvases = set(COMPOSITE_CALL.findall(joined))
+ ctxs = {ctx for ctx, canvas in CTX_BIND.findall(joined) if canvas in canvases}
+ for lineno, text in stmts:
+ m = DRAW_INTO.search(text)
+ if m and m.group(1) in ctxs:
+ yield name, lineno, m.group(2).strip()
+
+
+def test_the_warp_base_inventory_is_intact():
+ """워프 base 사이트가 **파일마다 몇 곳인지까지** 그대로여야 한다.
+
+ 존재만 보는 못은 사이트가 여럿인 파일에서 상실을 못 본다 — 하나가 사라져도 나머지가
+ 파일을 커버한다. 조용한 커버리지 상실은 이 플랜이 이미 두 번 1급 계약으로 올린
+ 실패 모드이고, 이건 그 다음 granularity 다.
+
+ 개수가 바뀌면 실패하는 게 **의도다**: 워프 base 를 늘리거나 줄이는 변경은 사람이
+ 한 번 보고 이 표를 같이 고쳐야 한다."""
+ got = {}
+ for name, _, _ in _warp_base_sites():
+ got[name] = got.get(name, 0) + 1
+ assert got == EXPECTED_WARP_BASES, (
+ f"워프 base 인벤토리가 달라졌다.\n 기대: {EXPECTED_WARP_BASES}\n 실제: {got}\n"
+ " 줄었으면 사이트가 조용히 증발한 것이고(캔버스·ctx·호출 이름 변경), "
+ "늘었으면 새 워프 base 가 계약에 들어온 것이다 — 어느 쪽이든 표를 같이 고쳐라.")
+
+
+def test_the_warp_base_never_falls_back_to_a_display_file():
+ """호흡 워프의 base 는 **굽기가 읽는 파일 하나**다 — 폴백을 두지 않는다.
+
+ `cards.js` 는 `(canonical && canonical.complete) ? canonical : image` 였다. 굽기 파일
+ 이미지가 아직 로드 중이면 **표시 파일**(pp OFF 트윈 줄은 `orig/` 고해상본)을 워프
+ base 로 썼고 알림은 0건이었다. 로드되면 자가 교정되는 일시적 현상이라 산출물은 안
+ 깨지지만, 조용히 **틀린 그림**을 그리는 건 조용히 **안 그리는** 것과 다르다 —
+ 준비 안 됐으면 워프하지 않는다(`zoom-editor`·`compare`·`row-export` 가 쓰는 형태).
+
+ 판정은 도달도 선언도 아닌 **분기 전수 + 재대입 금지**다 (`_bake_only`): 세 번의 탈출이
+ 각각 분기·흐름·사이트 수집을 노렸다."""
+ sites = list(_warp_base_sites())
+ assert sites, "워프 base 자리를 하나도 못 찾았다 — 스캐너가 고장났다"
+ for name, line, arg in sites:
+ assert _bake_only(name, line, arg), (
+ f"{name}:{line} 워프 base {arg!r} 의 어떤 분기가 굽기 파일이 아니다.\n"
+ " 준비 안 된 소스는 폴백이 아니라 **안 그리는 것**으로 다뤄라.")
+
+
+# ── 문서가 폐기된 설계를 말하지 않는다 ──────────────────────────────
+
+REPO_ROOT = ROOT
+# round-11 이 폐기한 설계의 문구. 문서가 이걸 말하면 다음 사람이 폐기된 모델로 고친다.
+RETIRED_DOC_CLAIMS = [
+ ("fingerprint of the\n frame it came from", "지문은 프레임이 아니라 **입력 키**의 지문이다"),
+ ("a mismatch re-detects", "굽기는 지문을 안 보고 **매번** 재검출한다"),
+]
+DOC_FILES = ["CHANGELOG.md", "SKILL.md", "README.md",
+ "docs/static-pose-recipe.md", "docs/run-contract.md", "docs/curation.md"]
+
+
+def test_no_doc_still_describes_the_retired_fingerprint_design():
+ """문서는 지금 설계를 말해야 한다 (SSoT 드리프트 금지).
+
+ round-11 이 지문을 *변형 결과 픽셀* 에서 *입력 키* 로 옮겼고 굽기가 캐시를 아예 안
+ 믿게 됐는데, CHANGELOG 한 곳만 옛 모델을 계속 말하고 있었다 (validator note 2026-07-26).
+ 같은 규칙을 말하는 진입점이 여럿이면 한쪽만 고쳐진다 — 그래서 전 진입점을 훑는다."""
+ stale = []
+ for rel in DOC_FILES:
+ path = REPO_ROOT / rel
+ if not path.is_file():
+ continue
+ text = path.read_text(encoding="utf-8")
+ for claim, why in RETIRED_DOC_CLAIMS:
+ if claim in text:
+ stale.append(f"{rel}: {claim!r} — {why}")
+ assert not stale, "문서가 폐기된 지문 설계를 말한다:\n " + "\n ".join(stale)
diff --git a/tests/effects/test_breathe_reference_key.py b/tests/effects/test_breathe_reference_key.py
new file mode 100644
index 0000000..8928fbb
--- /dev/null
+++ b/tests/effects/test_breathe_reference_key.py
@@ -0,0 +1,614 @@
+# SPDX-License-Identifier: Apache-2.0
+"""기준 프레임 키 — 파이썬과 JS 가 **같은 문자열**을 내는가 (그리고 웹뷰가 그 재료를
+어디서 긁어오는가).
+
+## 왜 이 파일이 따로 있나
+
+호흡 지문은 원래 *변형 결과 RGBA* 의 해시였다. 그런데 굽기는 `apply_transform` 에서
+BICUBIC 으로 리샘플하고(`snap_scale` 없는 런 = 기본 런 전부) 웹뷰 캔버스는
+`imageSmoothingEnabled=false`, 즉 NEAREST 다. 같은 원본에 같은 변형을 걸어도 두 쪽이
+만드는 그림이 다르니 지문은 **영구 불일치**였고, 회전·확대가 걸린 줄은 프리뷰가 영원히
+원본으로 떨어지고 영상 내보내기가 영구 차단됐다 (validator 실측 2026-07-26: rotate 3° 555px
+상이, 정수 이동만 걸린 줄은 우연히 일치).
+
+10라운드를 살아남은 이유가 구조적이다: 기존 미러 테스트는 **같은 픽셀 버퍼**를 양쪽에
+먹여서 "웹뷰가 서버가 지문 찍은 그 버퍼를 만들어 낼 수 있는가" 를 한 번도 묻지 않았다.
+그래서 이 파일은 픽셀을 아예 안 쓰고 **입력에서 키가 나오는 경로**만 본다.
+"""
+
+import json
+import re
+import subprocess
+import sys
+import tempfile
+from pathlib import Path
+
+import pytest
+
+sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent))
+
+from sprite_gen.effects.breathe import anatomy_fingerprint, reference_key # noqa: E402
+from sprite_gen.serve.serve_curation import CURATOR_DIR # noqa: E402
+
+SRC = CURATOR_DIR / "src"
+
+pytestmark = pytest.mark.skipif(
+ not __import__("shutil").which("node"), reason="node 없음 — 미러를 못 돌린다")
+
+
+def _node(script: str, payload: dict):
+ with tempfile.TemporaryDirectory() as tmp:
+ pj = Path(tmp) / "payload.json"
+ pj.write_text(json.dumps(payload), encoding="utf-8")
+ run = subprocess.run(["node", "-e", script, str(pj)],
+ capture_output=True, text=True, timeout=120)
+ assert run.returncode == 0, f"node 실패:\n{run.stderr}"
+ return json.loads(run.stdout)
+
+
+KEY_HARNESS = r"""
+const fs = require("fs"), vm = require("vm");
+const payload = JSON.parse(fs.readFileSync(process.argv[1], "utf8"));
+const sandbox = { console, TextEncoder, entries: {}, run: {}, setStatus: () => {},
+ document: { createElement: () => ({ getContext: () => ({}) }) } };
+sandbox.globalThis = sandbox;
+vm.createContext(sandbox);
+vm.runInContext(fs.readFileSync(payload.script, "utf8"), sandbox);
+const out = payload.cases.map((c) => ({
+ key: sandbox.breatheReferenceKeyOf(c),
+ fingerprint: sandbox.breatheFingerprint(sandbox.breatheReferenceKeyOf(c)),
+}));
+process.stdout.write(JSON.stringify(out));
+"""
+
+# 값 **모양**의 전수 — 지적당한 한 칸만 메우는 방식이 열 라운드 동안 실패했다.
+# 변형 없음(대부분의 프레임)·항등 명시·회전·축소·음수 이동·거울·문자열 수·소수 경계,
+# 픽셀편집 없음/지움(null)/여러 점(정렬 순서 뒤섞임)까지 한 번에 건다.
+CASES = [
+ {"variant": "plain", "transform": None, "pixel_ops": None},
+ {"variant": "plain", "transform": {}, "pixel_ops": {}},
+ {"variant": "pixel", "transform": {"rotate": 0.0, "scale": 1.0, "dx": 0, "dy": 0,
+ "shx": 0.0, "shy": 0.0, "flipX": 0}, "pixel_ops": None},
+ {"variant": "plain", "transform": {"rotate": 3.0}, "pixel_ops": None},
+ {"variant": "plain", "transform": {"scale": 0.9}, "pixel_ops": None},
+ {"variant": "pixel", "transform": {"dx": -7, "dy": 12}, "pixel_ops": None},
+ {"variant": "pixel", "transform": {"flipX": True}, "pixel_ops": None},
+ {"variant": "plain", "transform": {"rotate": "3"}, "pixel_ops": None},
+ {"variant": "plain", "transform": {"scale": 1.0000005}, "pixel_ops": None},
+ {"variant": "plain", "transform": {"rotate": -0.5, "shx": 0.25}, "pixel_ops": None},
+ {"variant": "plain", "transform": None, "pixel_ops": {"3,4": "#ff0000"}},
+ {"variant": "plain", "transform": None, "pixel_ops": {"10,2": None}},
+ {"variant": "pixel", "transform": None,
+ "pixel_ops": {"9,9": "#00ff00", "1,1": "#0000ff", "10,0": None}},
+ {"variant": "pixel", "transform": {"rotate": 3.0}, "pixel_ops": {"2,2": "#123456"}},
+]
+
+
+def _py(case, *, state="idle", request_stamp="120:5", source_index=0, source_stamp="900:7"):
+ return reference_key(state=state, variant=case["variant"], request_stamp=request_stamp,
+ source_index=source_index, source_stamp=source_stamp,
+ pixel_ops=case["pixel_ops"], transform=case["transform"])
+
+
+def _js_case(case, *, state="idle", request_stamp="120:5", source_index=0, source_stamp="900:7"):
+ return {"state": state, "variant": case["variant"], "requestStamp": request_stamp,
+ "sourceIndex": source_index, "sourceStamp": source_stamp,
+ "pixelOps": case["pixel_ops"], "transform": case["transform"]}
+
+
+def test_python_and_js_build_the_same_key_for_every_value_shape():
+ got = _node(KEY_HARNESS, {"script": str(SRC / "breathe.js"),
+ "cases": [_js_case(c) for c in CASES]})
+ assert len(got) == len(CASES)
+ for case, js in zip(CASES, got):
+ py = _py(case)
+ assert js["key"] == py, (
+ f"키가 갈렸다 — 변형 {case['transform']!r} / 픽셀 {case['pixel_ops']!r}\n"
+ f" py: {py}\n js: {js['key']}")
+ assert js["fingerprint"] == anatomy_fingerprint(py), "같은 키인데 지문이 갈렸다"
+
+
+def test_every_ingredient_changes_the_key():
+ """재료 하나를 건드리면 키가 **반드시** 달라진다.
+
+ 안 달라지는 재료가 있으면 그건 신선도 판정에서 빠진 것이다 — 사용자가 그걸 바꿔도
+ 프리뷰가 낡은 해부로 계속 그린다."""
+ base = {"variant": "plain", "transform": {"rotate": 3.0}, "pixel_ops": {"2,2": "#123456"}}
+ ref = _py(base)
+ variants = {
+ "state": _py(base, state="walk"),
+ "variant": _py({**base, "variant": "pixel"}),
+ "request_stamp": _py(base, request_stamp="121:5"),
+ "source_index": _py(base, source_index=1),
+ "source_stamp": _py(base, source_stamp="900:8"),
+ "transform": _py({**base, "transform": {"rotate": 3.000001}}),
+ "pixel_ops": _py({**base, "pixel_ops": {"2,2": "#123457"}}),
+ }
+ for name, key in variants.items():
+ assert key != ref, f"{name} 을 바꿨는데 키가 그대로다 — 신선도 판정 밖에 있다"
+
+
+def test_the_key_never_reads_pixels():
+ """키 계산에 이미지가 **필요 없다**는 것이 이 설계의 요점이다.
+
+ 이 단언이 무너지면(키 함수가 프레임을 받게 되면) 리샘플러 차이가 다시 식에 들어온다."""
+ import inspect
+
+ from sprite_gen.effects import breathe
+ sig = inspect.signature(breathe.reference_key)
+ assert "frame" not in sig.parameters and "image" not in sig.parameters, \
+ "reference_key 가 프레임을 받는다 — BICUBIC/NEAREST 불일치가 되돌아온다"
+ js = (SRC / "breathe.js").read_text(encoding="utf-8")
+ body = js[js.index("function breatheReferenceKeyOf"):]
+ body = body[:body.index("\nfunction ", 1)]
+ for banned in ("getImageData", "getContext", "canvas", "drawImage"):
+ assert banned not in body, f"JS 키 빌더가 {banned} 를 쓴다 — 픽셀을 읽으면 안 된다"
+
+
+# ── 웹뷰가 서버가 쓴 그 키를 만들어 낼 수 있는가 ──────────────────────
+
+from tests.effects.test_breathe_anatomy_route import CELL, run_dir # noqa: E402,F401
+
+STORE_HARNESS = r"""
+const fs = require("fs"), vm = require("vm");
+const payload = JSON.parse(fs.readFileSync(process.argv[1], "utf8"));
+const sandbox = {
+ console, TextEncoder, Set, Map, setTimeout,
+ document: { createElement: () => ({ getContext: () => ({}), style: {} }),
+ addEventListener() {}, querySelectorAll: () => [] },
+ window: {}, fetch: () => {}, setStatus() {}, t: () => "", STR: {}, lang: "ko",
+ scheduleSave() {}, flushSave: async () => {}, rebuildState() {},
+ URL: { createObjectURL() {}, revokeObjectURL() {} },
+};
+sandbox.globalThis = sandbox;
+vm.createContext(sandbox);
+for (const f of payload.scripts) vm.runInContext(fs.readFileSync(f, "utf8"), sandbox);
+
+// 서버 페이로드를 웹뷰 상태로 — store.js 가 읽는 필드만.
+//
+// `let run`/`let entries` 는 컨텍스트의 **렉시컬 바인딩**이라 sandbox 객체에 대입해도
+// 스크립트가 못 본다. 컨텍스트 안에서 대입해야 한다.
+sandbox.__payload = payload;
+vm.runInContext(`
+ run = __payload.run;
+ entries = {};
+ // **손으로 unfakeStates 를 먹이지 않는다.** 웹뷰가 서버 페이로드에서 변종을 스스로
+ // 골라내는지가 이 하네스의 요점이다 — 시드를 밖에 두면 그 질문을 영영 못 묻는다
+ // (validator 실측 2026-07-26: 변종 불일치가 그 공백으로 한 라운드를 살아남았다).
+ seedUnfakeState(__payload.run);
+ for (const [name, v] of Object.entries(__payload.ppOverride || {})) unfakeStates[name] = v;
+ for (const [name, e] of Object.entries(__payload.entries)) {
+ entries[name] = { order: e.order, sel: new Set(e.sel), transforms: e.transforms || {},
+ pixels: e.pixels || {}, clones: e.clones || {},
+ unlinked: new Set(e.unlinked || []) };
+ }
+ __out = {};
+ for (const q of __payload.queries) {
+ if (q.kind === "key") __out[q.id] = breatheReferenceKey(q.state);
+ if (q.kind === "geometry") __out[q.id] = breatheGeometryFrame(q.state, q.fallback);
+ if (q.kind === "variant") __out[q.id] = bakeVariant(q.state);
+ }
+`, sandbox);
+process.stdout.write(JSON.stringify(sandbox.__out));
+"""
+
+
+def _webview(run_payload, entries, queries, pp_override=None):
+ """웹뷰를 서버 페이로드로 부팅해 질의한다 — `unfakeStates` 는 `seedUnfakeState` 가 짓는다.
+
+ `pp_override` 는 사용자가 화면에서 토글을 누른 상태를 흉내낼 때만 쓴다."""
+ return _node(STORE_HARNESS, {
+ "scripts": [str(SRC / "breathe.js"), str(SRC / "store.js")],
+ "run": run_payload, "entries": entries, "ppOverride": pp_override or {},
+ "queries": queries})
+
+
+def web_run(run_dir):
+ """`/api/run` 페이로드까지 조립되는 런 — 라우트 픽스처의 `character` 는 문자열이라
+ 페이로드 빌더(`request["character"]["id"]`)가 죽는다."""
+ req = json.loads((run_dir / "sprite-request.json").read_text(encoding="utf-8"))
+ req["character"] = {"id": "fixture", "name": "fixture"}
+ (run_dir / "sprite-request.json").write_text(json.dumps(req), encoding="utf-8")
+ return run_dir
+
+
+def _write_curation(run_dir, curation):
+ """세대 도장까지 찍어 저장 — 안 찍으면 로더가 "프레임 재생성됨" 으로 보고 그 줄을
+ 통째로 드롭한다 (그러면 pixel_perfect 설정도 같이 사라져 변종이 되돌아간다)."""
+ from sprite_gen.curate.curation import stamp_curation
+ (run_dir / "curation.json").write_text(
+ json.dumps(stamp_curation(run_dir, curation)), encoding="utf-8")
+
+
+def _server_payload(run_dir):
+ import sprite_gen.serve.serve_curation as serve_curation
+ return serve_curation._build_run_state_impl(run_dir)
+
+
+def test_the_webview_builds_the_same_key_the_route_used(web_run):
+ """**이 파일의 핵심 단언.**
+
+ 미러 테스트들은 같은 픽셀 버퍼를 양쪽에 먹여서 "웹뷰가 서버가 지문 찍은 그 프레임에
+ 도달할 수 있는가" 를 묻지 않았다 — 그래서 리샘플러 불일치가 10라운드를 살아남았다.
+ 여기서는 서버가 실제로 응답에 실어 보낸 페이로드만으로 웹뷰가 키를 만들게 하고,
+ 라우트가 해부를 얼릴 때 쓴 키와 **문자열 동일**한지 본다."""
+ import sprite_gen.serve.serve_curation as serve_curation
+ _, route_key = serve_curation._breathe_source_frame(web_run, "idle")
+ payload = _server_payload(web_run)
+ got = _webview(payload,
+ {"idle": {"order": [0, 1, 2, 3], "sel": [0, 1, 2, 3]}},
+ [{"id": "k", "kind": "key", "state": "idle"}])
+ assert got["k"] == route_key, (
+ "웹뷰가 라우트와 다른 키를 만든다 — 프리뷰가 영원히 원본으로 떨어진다.\n"
+ f" 라우트: {route_key}\n 웹뷰 : {got['k']}")
+
+
+def test_the_key_follows_the_sidecar_the_user_actually_edited(web_run):
+ """사용자가 변형·픽셀편집을 바꾸면 웹뷰 키가 **따라 움직인다.**
+
+ 안 움직이면 낡은 해부로 계속 그린다 — 지문의 존재 이유 자체가 사라진다."""
+ payload = _server_payload(web_run)
+ base = {"idle": {"order": [0, 1, 2, 3], "sel": [0, 1, 2, 3]}}
+ q = [{"id": "k", "kind": "key", "state": "idle"}]
+ plain = _webview(payload, base, q)["k"]
+ rotated = _webview(payload, {"idle": {**base["idle"], "transforms": {"0": {"rotate": 3.0}}}}, q)["k"]
+ painted = _webview(payload, {"idle": {**base["idle"], "pixels": {"0": {"3,4": "#ff0000"}}}}, q)["k"]
+ reordered = _webview(payload, {"idle": {"order": [2, 0, 1, 3], "sel": [0, 1, 2, 3]}}, q)["k"]
+ assert plain and rotated != plain, "회전을 걸었는데 키가 그대로다"
+ assert painted != plain, "픽셀을 칠했는데 키가 그대로다"
+ assert reordered != plain, "재생 순서를 바꿔 기준 프레임이 달라졌는데 키가 그대로다"
+
+
+def test_a_missing_stamp_refuses_instead_of_guessing(web_run):
+ """스탬프가 없으면 **키를 만들지 않는다** (null).
+
+ 없는 재료를 기본값으로 메우면 서로 다른 프레임이 같은 키를 갖고, 그때 신선도 검사는
+ 통과하면서 그림은 갈린다 — 조용한 오답이 시끄러운 거부보다 나쁘다."""
+ payload = _server_payload(web_run)
+ for st in payload["states"]:
+ for fr in st.get("frames", []):
+ fr.pop("stamp", None)
+ fr.pop("plainBakeStamp", None)
+ got = _webview(payload, {"idle": {"order": [0, 1, 2, 3], "sel": [0, 1, 2, 3]}},
+ [{"id": "k", "kind": "key", "state": "idle"}])
+ assert got["k"] is None, f"스탬프가 없는데 키를 만들어냈다: {got['k']!r}"
+
+
+def test_geometry_measures_the_reference_frame_not_the_opened_one(web_run):
+ """경계 지오메트리의 원점 = 재생 첫 슬롯. 모달이 열린 프레임이 아니다.
+
+ `rigid_row` 는 기준 프레임의 콘텐츠 행 인덱스라, 열린 프레임을 재면 선의 화면
+ 위치와 저장되는 행 번호가 굽기와 어긋난다 — 재생 순서만 바꿔도 도달하고 골든
+ 픽스처에서 8px(50px 캐릭터의 16%) 어긋났다 (validator 실측 2026-07-26).
+ round-10 은 이 결함을 고쳤지만 **그물이 없어** 되돌려도 전체 스위트가 통과했다."""
+ payload = _server_payload(web_run)
+ got = _webview(payload, {"idle": {"order": [2, 0, 1, 3], "sel": [0, 1, 2, 3]}},
+ [{"id": "g", "kind": "geometry", "state": "idle", "fallback": 3}])
+ assert got["g"]["index"] == 2, (
+ f"지오메트리가 재생 첫 슬롯(2)이 아니라 {got['g']['index']} 를 잰다 — "
+ "열린 프레임을 재면 경계가 굽기와 어긋난다")
+ empty = _webview(payload, {"idle": {"order": [0, 1, 2, 3], "sel": []}},
+ [{"id": "g", "kind": "geometry", "state": "idle", "fallback": 3}])
+ assert empty["g"]["index"] == 3, "재생목록이 비면 열린 프레임으로 떨어져야 한다"
+
+
+def web_run_plain(web_run):
+ """pp OFF 줄 — `.plain.png` 쌍둥이를 굽기가 읽는다.
+
+ R1 이 실제로 터진 경로다: 굽기는 `snap_scale` 이 없어 **BICUBIC** 으로 리샘플하고
+ 웹뷰는 NEAREST 라, 결과 픽셀을 해시하던 옛 지문이 여기서 영구 불일치였다."""
+ from PIL import Image
+ for i in range(4):
+ src = web_run / f"frames/idle/frame-{i}.png"
+ with Image.open(src) as im:
+ im.convert("RGBA").resize((CELL, CELL), Image.NEAREST).save(
+ src.with_suffix("").with_suffix(".plain.png"))
+ from sprite_gen.curate.curation import empty_curation
+ curation = empty_curation()
+ curation["states"]["idle"] = {"pixel_unfake": False}
+ _write_curation(web_run, curation)
+ return web_run
+
+
+def test_the_webview_agrees_on_the_plain_variant_too(web_run_plain):
+ """pp OFF 줄에서도 웹뷰 키 == 라우트 키.
+
+ 변종이 갈리면 서로 다른 **파일**을 기준으로 삼는다 — 이 줄이 정확히 그 경로다."""
+ import sprite_gen.serve.serve_curation as serve_curation
+ _, route_key = serve_curation._breathe_source_frame(web_run_plain, "idle")
+ assert "|plain|" in route_key, f"라우트가 plain 변종을 안 골랐다: {route_key}"
+ payload = _server_payload(web_run_plain)
+ got = _webview(payload, {"idle": {"order": [0, 1, 2, 3], "sel": [0, 1, 2, 3]}},
+ [{"id": "k", "kind": "key", "state": "idle"}])
+ assert got["k"] == route_key, (
+ f"pp OFF 줄에서 갈렸다\n 라우트: {route_key}\n 웹뷰 : {got['k']}")
+
+
+def test_a_rotated_row_stays_fresh(web_run_plain):
+ """**R1 회귀 그물.** 회전이 걸린 pp OFF 줄이 신선하다고 판정돼야 한다.
+
+ 옛 지문(변형 결과 RGBA 해시)에서는 이 줄이 영구 불일치라 프리뷰가 영원히 원본으로
+ 떨어지고 영상 내보내기가 영구 차단됐다 — 그리고 안내대로 해부를 갱신해도 라우트가
+ 또 BICUBIC 프레임으로 같은 숫자를 만들어 **절대 안 풀렸다** (validator 실측 2026-07-26:
+ rotate 3° 에서 555px 상이)."""
+ import sprite_gen.serve.serve_curation as serve_curation
+ from sprite_gen.effects.breathe import freeze_anatomy
+ curation = json.loads((web_run_plain / "curation.json").read_text(encoding="utf-8"))
+ curation["states"]["idle"]["transforms"] = {"0": {"rotate": 3.0}}
+ _write_curation(web_run_plain, curation)
+
+ frame, route_key = serve_curation._breathe_source_frame(web_run_plain, "idle")
+ frozen = freeze_anatomy(frame, {}, route_key) # 라우트가 사이드카에 얼리는 값
+ payload = _server_payload(web_run_plain)
+ got = _webview(payload,
+ {"idle": {"order": [0, 1, 2, 3], "sel": [0, 1, 2, 3],
+ "transforms": {"0": {"rotate": 3.0}}}},
+ [{"id": "k", "kind": "key", "state": "idle"}])
+ assert got["k"] == route_key, "회전이 걸린 줄에서 웹뷰가 다른 키를 만든다"
+ assert anatomy_fingerprint(got["k"]) == frozen["fingerprint"], (
+ "회전이 걸린 줄이 얼린 지문과 안 맞는다 — 프리뷰가 영원히 원본으로 떨어진다")
+
+
+# ── 굽기 변종 해소표 전수 ────────────────────────────────────────────
+
+# 해소 축은 셋이다: 트윈 존재(2) × per-state 선언(없음/켬/끔) × 런 전역(없음/켬/끔) = **18칸**.
+#
+# 앞선 판은 8칸을 "전수" 라고 적었는데 `twin=False` 일 때 `own=None` 한 줄만 돌았다. 빠진
+# 6칸 중 3칸이 갈리고 있었다 — 파이썬 per-state 분기는 **무조건**인데 미러가 트윈 존재로
+# 게이트했기 때문이다. 곱집합을 코드로 만들어 "전수" 가 이름이 아니라 사실이 되게 한다.
+VARIANT_CASES = [(twin, own, wide)
+ for twin in (False, True)
+ for own in (None, True, False)
+ for wide in (None, True, False)]
+
+
+def _variant_id(case):
+ twin, own, wide = case
+ fmt = {None: "없음", True: "켬", False: "끔"}
+ return f"twin{'있음' if twin else '없음'}-own{fmt[own]}-wide{fmt[wide]}"
+
+
[email protected]("twin,own,wide", VARIANT_CASES, ids=[_variant_id(c) for c in VARIANT_CASES])
+def test_the_webview_resolves_the_bake_variant_like_the_server(twin, own, wide):
+ """웹뷰의 굽기 변종 == 파이썬 `frame_variant` — 해소표 전수.
+
+ `unfakeOn` 은 **표시 렌즈**다: boot 시드가 트윈 없는 줄을 기본 OFF 로 놓는데 그 값은
+ 사이드카에 저장되지 않으므로 서버는 그 줄을 `pixel` 로 본다. 둘을 같은 값으로 쓰면
+ `fit.pixel_perfect` 없이 만든 **기본 런 전부**에서 지문이 영구 불일치가 되고,
+ 해부를 갱신해도 라우트가 또 `pixel` 로 같은 키를 만들어 절대 안 풀린다
+ (validator 실측 2026-07-26).
+
+ 한 칸씩 메우지 않고 표를 통째로 건다 — 같은 실패 모드가 축만 바꿔(파일 → 리샘플러
+ → 변종 이름) 세 번 되돌아왔다."""
+ from sprite_gen.curate.curation import frame_variant
+
+ curation = {"states": {}}
+ if own is not None:
+ curation["states"]["idle"] = {"pixel_unfake": own}
+ if wide is not None:
+ curation["pixel_unfake"] = wide
+ frames = [{"index": 0, "present": True, "url": "/f0.png", "stamp": "1:1"}]
+ if twin:
+ frames[0]["plainUrl"] = "/f0.plain.png"
+ frames[0]["plainBakeUrl"] = "/f0.plain.png"
+ frames[0]["plainBakeStamp"] = "2:2"
+ payload = {"requestStamp": "9:9", "curation": curation,
+ "states": [{"name": "idle", "frames": frames}]}
+ got = _webview(payload, {"idle": {"order": [0], "sel": [0]}},
+ [{"id": "v", "kind": "variant", "state": "idle"}])
+ assert got["v"] == frame_variant(curation, "idle"), (
+ f"트윈{twin} per-state{own} 전역{wide}: "
+ f"웹뷰 {got['v']!r} vs 서버 {frame_variant(curation, 'idle')!r}")
+
+
+def test_the_saved_sidecar_is_what_the_variant_resolves_from():
+ """굽기 변종은 **저장되는 값**으로 해소한다.
+
+ 트윈 없는 줄의 퍼펙은 사이드카에 안 적힌다(적으면 굽기가 존재하지 않는 `.plain`
+ 변형을 요구한다). 그래서 그 줄의 화면 토글은 변종을 바꾸면 안 된다 — 눌렀다고
+ 키가 바뀌면 굽기는 그대로인데 프리뷰만 거부된다."""
+ payload = {"requestStamp": "9:9", "curation": {"states": {}},
+ "states": [{"name": "idle", "frames": [
+ {"index": 0, "present": True, "url": "/f0.png", "stamp": "1:1"}]}]}
+ q = [{"id": "v", "kind": "variant", "state": "idle"}]
+ on = _webview(payload, {"idle": {"order": [0], "sel": [0]}}, q, pp_override={"idle": True})
+ off = _webview(payload, {"idle": {"order": [0], "sel": [0]}}, q, pp_override={"idle": False})
+ assert on["v"] == off["v"] == "pixel", (
+ f"트윈 없는 줄의 표시 토글이 굽기 변종을 바꾼다 (켬 {on['v']}, 끔 {off['v']})")
+
+
+def test_a_declared_twinless_row_still_builds_a_key():
+ """트윈 없는 줄에 per-state 선언이 있어도 웹뷰가 **키를 만들어야** 한다.
+
+ 변종 해소가 갈리면 웹뷰는 `plain` 을 고르고 `bakeFrame` 이 null 을 돌려줘 키가 아예
+ 안 만들어진다 → `breatheAssertFresh` 가 "기준 프레임 키를 만들 수 없다" 로 **영구
+ 거부**하고, 프리뷰 3곳·`row-export`·비교뷰 다운로드·경계 드래그가 전부 죽는다.
+ 굽기는 그 사이 멀쩡히 `pixel` 로 굽는다 (validator 실측 2026-07-26).
+
+ "갈렸다" 를 값으로 보는 위 해소표와 달리, 이건 **사용자가 겪는 결과**를 본다."""
+ curation = {"pixel_unfake": False, "states": {"idle": {"pixel_unfake": True}}}
+ payload = {"requestStamp": "9:9", "curation": curation,
+ "states": [{"name": "idle", "frames": [
+ {"index": 0, "present": True, "url": "/f0.png", "stamp": "1:1"}]}]}
+ got = _webview(payload, {"idle": {"order": [0], "sel": [0]}},
+ [{"id": "k", "kind": "key", "state": "idle"},
+ {"id": "g", "kind": "geometry", "state": "idle", "fallback": 0}])
+ assert got["k"] and "|pixel|" in got["k"], (
+ f"키를 못 만들거나 변종이 틀렸다: {got['k']!r} — 프리뷰·내보내기가 영구 거부된다")
+ assert got["g"]["url"], "경계 드래그가 잴 프레임을 못 잡는다"
+
+
+# ── 미러 전수: 파이썬 함수를 JS 가 베낀 자리는 **곱집합**으로 건다 ──────
+#
+# 여덟 라운드 동안 같은 형태로 기각당했다: 미러가 어떤 입력 부분집합에서 원본과 갈리고,
+# 그 부분집합이 손으로 적은 케이스 목록 밖에 있었다 (축만 파일 → 리샘플러 → 변종 이름 →
+# per-state 게이트로 옮겨갔다). 인스턴스가 아니라 **클래스**를 닫으려면 케이스를 적지 말고
+# 입력 축의 곱집합을 **생성**해야 한다. 이 절이 남은 미러들에 그 형태를 적용한다.
+
+MIRROR_HARNESS = r"""
+const fs = require("fs"), vm = require("vm");
+const payload = JSON.parse(fs.readFileSync(process.argv[1], "utf8"));
+const sandbox = { console, TextEncoder, Set, Map, setTimeout,
+ document: { createElement: () => ({ getContext: () => ({}), style: {} }),
+ addEventListener() {}, querySelectorAll: () => [] },
+ window: {}, fetch: () => {}, setStatus() {}, t: () => "", STR: {}, lang: "ko",
+ scheduleSave() {}, flushSave: async () => {}, rebuildState() {},
+ URL: { createObjectURL() {}, revokeObjectURL() {} } };
+sandbox.globalThis = sandbox;
+vm.createContext(sandbox);
+for (const f of payload.scripts) vm.runInContext(fs.readFileSync(f, "utf8"), sandbox);
+sandbox.__payload = payload;
+vm.runInContext(`
+ __out = [];
+ for (const c of __payload.cases) {
+ if (__payload.fn === "normalizeTransform") {
+ __out.push(breatheNormalizeTransform(c.transform));
+ } else if (__payload.fn === "editIndex") {
+ entries = { idle: { order: [0, 1, 2], sel: new Set([0, 1, 2]),
+ clones: c.clones || {},
+ unlinked: new Set(c.unlinked || []) } };
+ __out.push(editIndex("idle", c.index));
+ }
+ }
+`, sandbox);
+process.stdout.write(JSON.stringify(sandbox.__out));
+"""
+
+
+def _mirror(fn, cases):
+ return _node(MIRROR_HARNESS, {
+ "scripts": [str(SRC / "breathe.js"), str(SRC / "store.js")],
+ "fn": fn, "cases": cases})
+
+
+# 변형 필드 × 값 모양의 곱집합 — 하나라도 갈리면 그 필드가 걸린 줄의 키가 통째로 갈린다.
+_TRANSFORM_FIELDS = ["rotate", "scale", "dx", "dy", "shx", "shy", "flipX"]
+_TRANSFORM_VALUES = [0, 1, -1, 3.0, 0.9, 1.0000005, "3", "0.5", True, False]
+NORMALIZE_CASES = ([{"transform": None}, {"transform": {}}]
+ + [{"transform": {f: v}} for f in _TRANSFORM_FIELDS for v in _TRANSFORM_VALUES])
+
+
+def test_normalize_transform_mirror_agrees_on_the_full_product():
+ """`normalize_transform` 미러 — 필드 7 × 값 모양 10 곱집합.
+
+ 이 함수의 출력이 그대로 기준 프레임 키에 들어간다. 한 필드의 한 모양만 갈려도 그
+ 변형이 걸린 줄은 지문이 영구 불일치가 된다."""
+ from sprite_gen.curate.curation import normalize_transform
+
+ got = _mirror("normalizeTransform", NORMALIZE_CASES)
+ assert len(got) == len(NORMALIZE_CASES)
+ for case, js in zip(NORMALIZE_CASES, got):
+ py = normalize_transform(case["transform"])
+ assert {k: float(v) for k, v in js.items()} == {k: float(v) for k, v in py.items()}, (
+ f"normalize_transform 미러가 갈렸다 — 입력 {case['transform']!r}\n"
+ f" py: {py}\n js: {js}")
+
+
+# 복제 링크 × 링크끊기 × 인덱스의 곱집합.
+EDIT_INDEX_CASES = [{"clones": clones, "unlinked": unlinked, "index": index}
+ for clones in ({}, {"2": 0}, {"2": 1})
+ for unlinked in ([], [2])
+ for index in (0, 1, 2)]
+
+
+def test_edit_index_mirror_agrees_on_the_full_product():
+ """`edit_index` 미러 — 복제 링크 3 × 링크끊기 2 × 인덱스 3 곱집합.
+
+ 이 값이 어느 프레임의 변형·픽셀편집을 읽을지 정하고, 그게 기준 프레임 키의 재료다.
+ 갈리면 웹뷰와 굽기가 **다른 프레임의 편집**을 기준으로 삼는다. 미러라고 적혀 있지도
+ 않았고 교차언어 테스트도 없었다."""
+ from sprite_gen.curate.curation import edit_index
+
+ got = _mirror("editIndex", EDIT_INDEX_CASES)
+ assert len(got) == len(EDIT_INDEX_CASES)
+ for case, js in zip(EDIT_INDEX_CASES, got):
+ curation = {"states": {"idle": {"clones": case["clones"],
+ "unlinked": case["unlinked"]}}}
+ py = edit_index(curation, "idle", case["index"])
+ assert js == py, (
+ f"edit_index 미러가 갈렸다 — clones={case['clones']} "
+ f"unlinked={case['unlinked']} index={case['index']}: py={py} js={js}")
+
+
+def test_the_mirrored_limits_are_the_same_numbers():
+ """사이드카 허용 범위 상수 — 파이썬과 JS 가 **같은 숫자**여야 한다.
+
+ 갈리면 웹뷰가 굽기의 loud reject 를 못 예측해, 사용자는 저장되는데 안 구워지는
+ 설정을 만들 수 있다."""
+ from sprite_gen.curate import curation as C
+
+ js = (SRC / "breathe.js").read_text(encoding="utf-8")
+ for name, want in (("BREATHE_DEPTH_MAX", C.BREATHE_DEPTH_MAX),
+ ("BREATHE_BREATHS_MAX", C.BREATHE_BREATHS_MAX),
+ ("BREATHE_LAG_MAX", C.BREATHE_LAG_MAX)):
+ m = re.search(rf"const {name} = ([\d.]+);", js)
+ assert m, f"{name} 이 미러에 없다"
+ assert float(m.group(1)) == float(want), \
+ f"{name}: py={want} js={m.group(1)} — 갈리면 저장은 되는데 안 구워진다"
+
+ retired = re.search(r"const RETIRED_BREATHE_KEYS = \[(.*?)\];",
+ (SRC / "store.js").read_text(encoding="utf-8"))
+ assert retired, "폐기 키 목록이 미러에 없다"
+ js_keys = {k.strip().strip('"') for k in retired.group(1).split(",")}
+ assert js_keys == set(C.RETIRED_BREATHE_KEYS), \
+ f"폐기 키 목록이 갈렸다: py={sorted(C.RETIRED_BREATHE_KEYS)} js={sorted(js_keys)}"
+
+
+def test_a_plain_variant_without_a_twin_refuses_instead_of_falling_back():
+ """변종이 `plain` 인데 트윈 파일이 없으면 **캐노니컬로 조용히 떨어지지 않는다**.
+
+ 그 상태는 굽기도 `row_frame_rel(row, i, "plain")` 로 없는 파일을 가리켜 실패하는
+ 상태다. 웹뷰만 캐노니컬로 떨어지면 두 쪽이 서로 다른 진실을 갖고, 프리뷰는 멀쩡해
+ 보이는데 굽기는 죽는다.
+
+ 이 계약은 round-12 가 세웠는데 그물이 없었다 — `frame.plainBakeUrl || frame.url` 로
+ 되돌려도 529 전부 통과했다 (validator note 2026-07-26)."""
+ curation = {"states": {"idle": {"pixel_unfake": False}}} # plain 을 강제
+ payload = {"requestStamp": "9:9", "curation": curation,
+ "states": [{"name": "idle", "frames": [ # 트윈 없음
+ {"index": 0, "present": True, "url": "/f0.png", "stamp": "1:1"}]}]}
+ got = _webview(payload, {"idle": {"order": [0], "sel": [0]}},
+ [{"id": "v", "kind": "variant", "state": "idle"},
+ {"id": "k", "kind": "key", "state": "idle"},
+ {"id": "g", "kind": "geometry", "state": "idle", "fallback": 0}])
+ assert got["v"] == "plain", "픽스처가 plain 변종을 안 만든다 — 이 테스트는 공허하다"
+ assert got["k"] is None, (
+ f"트윈이 없는데 키를 만들어냈다: {got['k']!r} — 캐노니컬로 조용히 떨어졌다는 뜻이다")
+ assert got["g"]["url"] is None, (
+ f"지오메트리가 굽기가 못 읽는 파일을 가리킨다: {got['g']['url']!r}")
+
+
[email protected]("shape", ["null", "empty", "missing"])
+def test_the_mirror_refuses_when_the_key_cannot_be_built(shape):
+ """키를 못 만들면 "확인 불가" 이지 "괜찮음" 이 아니다.
+
+ 형제 분기(지문 없음)는 round-10 R3 이후 그물이 있는데 이쪽만 비어 있었다 —
+ `throw` 를 `return` 으로 바꿔도 529 전부 통과했다 (validator note 2026-07-26).
+ 키가 없는 상태는 트윈 없는 plain 줄·빈 재생목록·스탬프 없는 프레임에서 실제로 나온다."""
+ key = {"null": None, "empty": "", "missing": None}[shape]
+ harness = r"""
+const fs = require("fs"), vm = require("vm");
+const P = JSON.parse(fs.readFileSync(process.argv[1], "utf8"));
+const sb = { console, TextEncoder, document: { createElement: () => ({ getContext: () => ({}) }) },
+ entries: {}, run: {}, t: () => "", setStatus: () => {}, fetch: () => {} };
+sb.globalThis = sb; vm.createContext(sb);
+vm.runInContext(fs.readFileSync(P.script, "utf8"), sb);
+let out;
+try {
+ if (P.shape === "missing") sb.breatheAssertFresh(undefined, P.cfg);
+ else sb.breatheAssertFresh(P.key, P.cfg);
+ out = { ok: true };
+} catch (e) {
+ out = { ok: false, refused: e.constructor.name === "BreatheRefused", message: e.message };
+}
+process.stdout.write(JSON.stringify(out));
+"""
+ cfg = {"depth": 0.06, "breaths": 1, "lag": 0.1,
+ "anatomy": {"height": 50, "rigid_row": 12, "fingerprint": "pixel:0:deadbeef"}}
+ got = _node(harness, {"script": str(SRC / "breathe.js"), "key": key,
+ "shape": shape, "cfg": cfg})
+ assert not got["ok"] and got["refused"], (
+ f"키가 {shape} 인데 미러가 신선하다고 판정했다 — 낡은 해부로 그리고, "
+ f"`row-export` 는 그 캔버스로 파일을 굽는다 ({got})")
diff --git a/tests/effects/test_breathe_sidecar_roundtrip.py b/tests/effects/test_breathe_sidecar_roundtrip.py
new file mode 100644
index 0000000..c4ef47e
--- /dev/null
+++ b/tests/effects/test_breathe_sidecar_roundtrip.py
@@ -0,0 +1,312 @@
+# SPDX-License-Identifier: Apache-2.0
+"""폐기된 호흡 사이드카가 큐레이터 왕복에서 살아남는지 + JS 위상식이 파이썬과 같은지.
+
+굽기 경로만 `splits`/`amplitude`/`subpixel`/`hold` 를 loud reject 하면 계약이 반쪽이다.
+구 런을 큐레이터로 한 번 여는 것만으로 폐기 키가 사이드카에서 사라지면 (a) 사용자는
+호흡 설정이 있었다는 사실도 못 듣고 (b) `migrate-breathe` 가 옮길 근거가 파괴되고
+(c) 그 뒤 굽기는 "호흡 없음" 으로 조용히 성공한다. 합성 회귀가 이 경로를 고정한다.
+
+위상식은 별개 건이다. round-2 가 파이썬에서 `((i*breaths) % seq) / seq` 로 고쳤는데
+미러가 옛 식으로 남아 프리뷰와 굽기가 반올림 경계에서 갈렸다 (합성 경계: seq=30
+breaths=7 slot 24 → 4바이트 차이). 기존 미러 테스트는 위상을 파이썬에서 만들어
+양쪽에 먹여주기 때문에 `breathePattern` 을 한 번도 안 태운다 — 그래서 못 잡았다.
+"""
+
+import json
+import shutil
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+
+ROOT = Path(__file__).resolve().parent.parent.parent
+sys.path.insert(0, str(ROOT))
+
+from sprite_gen.effects.breathe import fit_breathe_pattern # noqa: E402
+from sprite_gen.curate.curation import RETIRED_BREATHE_KEYS, state_breathe # noqa: E402
+from sprite_gen.serve.serve_curation import CURATOR_DIR # noqa: E402
+
+CURATOR = CURATOR_DIR / "src"
+node = pytest.mark.skipif(shutil.which("node") is None, reason="node 가 없어 큐레이터 JS 를 실행할 수 없다")
+
+HARNESS = r"""
+const fs = require("fs"), vm = require("vm");
+const P = process.argv[2] + "/";
+const sb = { console, document: { createElement: () => ({ getContext: () => ({}) }) },
+ window: {}, __status: [], setStatus: (m, k) => sb.__status.push([k || "", String(m)]),
+ t: () => "", fetch: () => {}, alert: () => {}, lang: "ko", STR: { ko: {} },
+ entries: {}, anchorPicks: {}, previews: {} };
+sb.globalThis = sb; vm.createContext(sb);
+for (const f of ["util.js", "store.js", "persistence.js"]) {
+ try { vm.runInContext(fs.readFileSync(P + f, "utf8"), sb); } catch (e) {}
+}
+const input = JSON.parse(fs.readFileSync(process.argv[3], "utf8"));
+if (input.mode === "roundtrip") {
+ vm.runInContext(`run = ${JSON.stringify(input.run)};`, sb);
+ sb.seedEntries();
+ const payload = sb.buildPayload();
+ fs.writeFileSync(input.out, JSON.stringify({ payload, status: sb.__status }));
+} else {
+ vm.runInContext(fs.readFileSync(P + "breathe.js", "utf8"), sb);
+ const out = input.cases.map((c) => sb.breathePattern({ breaths: c.breaths }, c.seq));
+ fs.writeFileSync(input.out, JSON.stringify(out));
+}
+"""
+
+
+def _run(payload, tmp_path):
+ harness = tmp_path / "h.cjs"
+ harness.write_text(HARNESS, encoding="utf-8")
+ payload["out"] = str(tmp_path / "out.json")
+ src = tmp_path / "in.json"
+ src.write_text(json.dumps(payload), encoding="utf-8")
+ proc = subprocess.run([shutil.which("node"), str(harness), str(CURATOR), str(src)],
+ capture_output=True, text=True)
+ assert proc.returncode == 0, f"node 하네스 실패:\n{proc.stderr}"
+ return json.loads(Path(payload["out"]).read_text(encoding="utf-8"))
+
+
+@node
[email protected]("retired_key", sorted(RETIRED_BREATHE_KEYS))
+def test_curator_preserves_a_retired_breathe_sidecar(retired_key, tmp_path):
+ """구 스키마 키가 있는 사이드카를 웹뷰가 읽고 되쓰면 그 키가 그대로 남아야 한다."""
+ breathe = {retired_key: {"splits": [0.55], "amplitude": 2,
+ "subpixel": True, "hold": 2}[retired_key], "breaths": 3}
+ run = {"schemaVersion": 1, "fps": 6,
+ "states": [{"name": "idle", "fps": 6,
+ "frames": [{"index": 0, "present": True}, {"index": 1, "present": True}]}],
+ "curation": {"states": {"idle": {"selected": [0, 1], "breathe": breathe}}}}
+ got = _run({"mode": "roundtrip", "run": run}, tmp_path)
+ saved = got["payload"]["states"]["idle"].get("breathe")
+ assert saved is not None, f"{retired_key}: 저장 payload 에서 breathe 가 통째로 사라졌다"
+ assert retired_key in saved, f"{retired_key}: 폐기 키가 삭제됐다 — migrate 근거가 파괴된다"
+ assert saved == breathe, "폐기 사이드카는 정규화도 하지 않고 원본 그대로여야 한다"
+ # 굽기 쪽 loud reject 가 여전히 걸리는지 (계약이 왕복 후에도 성립)
+ with pytest.raises(SystemExit):
+ state_breathe({"states": {"idle": {"breathe": saved}}}, "idle")
+
+
+@node
+def test_curator_tells_the_user_about_a_retired_sidecar(tmp_path):
+ """조용히 넘어가지 않는다 — 마이그레이션 경로를 화면에 알린다."""
+ run = {"schemaVersion": 1, "fps": 6,
+ "states": [{"name": "idle", "fps": 6, "frames": [{"index": 0, "present": True}]}],
+ "curation": {"states": {"idle": {"selected": [0],
+ "breathe": {"splits": [0.55], "breaths": 1}}}}}
+ got = _run({"mode": "roundtrip", "run": run}, tmp_path)
+ errs = [m for kind, m in got["status"] if kind == "err"]
+ assert errs, "폐기 스키마를 만났는데 아무 알림도 없다"
+ assert any("migrate-breathe" in m for m in errs), f"마이그레이션 경로 안내가 없다: {errs}"
+
+
+@node
[email protected]("seq,breaths", [(18, 3), (30, 7), (12, 2), (12, 4), (7, 2), (20, 5)])
+def test_js_phase_pattern_is_bit_identical_to_python(seq, breaths, tmp_path):
+ """위상식 미러 — 부동소수 표현까지 같아야 프리뷰가 굽기와 안 갈린다."""
+ got = _run({"mode": "pattern", "cases": [{"seq": seq, "breaths": breaths}]}, tmp_path)[0]
+ want = fit_breathe_pattern(seq, {"breaths": breaths})
+ assert len(got) == len(want)
+ for i, (a, b) in enumerate(zip(want, got)):
+ assert a == b, f"seq={seq} breaths={breaths} slot {i}: py={a!r} js={b!r}"
+ assert len(set(got)) == len(set(want)), "유니크 위상 개수가 다르다 (표현 노이즈)"
+
+
+@node
+ {"depth": 0.5, "breaths": 12, "lag": 0.9},
+ {"depth": 0},
+ {"breaths": 12},
+], ids=["all-three", "depth-zero", "breaths-over"])
+def test_the_curator_never_clamps_an_out_of_range_sidecar(bad, tmp_path):
+ """굽기가 요란하게 거부하는 값을 웹뷰가 조용히 깎아 되쓰면 원본이 파괴된다.
+
+ 실측 (validator 2026-07-25): `depth 0.5 / breaths 12 / lag 0.9` 를 웹뷰가 `0.2 / 8 / 0.45`
+ 로 조용히 로드하고(status 0건) 첫 autosave 가 그 값으로 사이드카를 갈아치웠다 —
+ loud reject 자체가 사라진다. round-3 A(폐기 키 삼킴)와 같은 경로다."""
+ breathe = {"depth": 0.06, "breaths": 1, "lag": 0.1, **bad}
+ run = {"schemaVersion": 1, "fps": 6,
+ "states": [{"name": "idle", "fps": 6,
+ "frames": [{"index": 0, "present": True}, {"index": 1, "present": True}]}],
+ "curation": {"states": {"idle": {"selected": [0, 1], "breathe": breathe}}}}
+ got = _run({"mode": "roundtrip", "run": run}, tmp_path)
+
+ saved = got["payload"]["states"]["idle"].get("breathe")
+ assert saved == breathe, f"웹뷰가 범위 밖 사이드카를 바꿔 썼다: {saved}"
+ errs = [m for kind, m in got["status"] if kind == "err"]
+ assert errs, "범위 밖인데 아무 알림도 없다"
+
+ # 굽기 쪽 게이트가 왕복 후에도 그대로 걸린다
+ with pytest.raises(SystemExit):
+ state_breathe({"states": {"idle": {"breathe": saved}}}, "idle")
+
+
+@node
+def test_the_curator_accepts_what_the_bake_accepts(tmp_path):
+ """굽기가 받는 값(숫자 문자열 포함)을 웹뷰도 호흡 켜짐으로 읽어야 한다.
+
+ `typeof !== "number"` 게이트는 `"0.08"` 을 호흡 없음으로 읽고 저장에서 breathe 키를
+ 통째로 지웠다 — 굽기는 정상 수용하는 값이라 켜짐/꺼짐 자체가 반대였다."""
+ breathe = {"depth": "0.08", "breaths": 3, "lag": 0.1}
+ run = {"schemaVersion": 1, "fps": 6,
+ "states": [{"name": "idle", "fps": 6, "frames": [{"index": 0, "present": True}]}],
+ "curation": {"states": {"idle": {"selected": [0], "breathe": breathe}}}}
+ got = _run({"mode": "roundtrip", "run": run}, tmp_path)
+ saved = got["payload"]["states"]["idle"].get("breathe")
+ assert saved is not None, "굽기가 받는 값을 웹뷰가 호흡 없음으로 읽고 지웠다"
+ assert float(saved["depth"]) == 0.08
+ assert state_breathe({"states": {"idle": {"breathe": saved}}}, "idle")["depth"] == 0.08
+
+
+@node
[email protected]("sidecar", [
+ {"breaths": 2},
+ {"breaths": 2, "lag": 0.1},
+ {"depth": 0.06, "breaths": 2},
+], ids=["depth-omitted", "depth-omitted-with-lag", "depth-explicit"])
+def test_an_omitted_depth_survives_the_round_trip(sidecar, tmp_path):
+ """`depth` 생략은 굽기에서 기본값 0.06 이다 — 왕복이 그걸 파괴하면 안 된다.
+
+ `Number(undefined)` 는 NaN 이고 `JSON.stringify(NaN)` 은 `null` 이라, 기본값 분기가
+ 없으면 첫 autosave 가 사이드카에 `depth: null` 을 박는다. 그러면 **굽기가 정상 수용하던
+ 사이드카를 큐레이터로 한 번 여는 것만으로 굽기가 죽는 사이드카로 바꿔놓고 아무 말도
+ 안 한다** (validator 실측 2026-07-26). `SKILL.md` 가 문서화한 "뷰 없이 에이전트가 breathe
+ 만 쓴 런" 이 정확히 이 모양이다."""
+ before = state_breathe({"states": {"idle": {"breathe": sidecar}}}, "idle")
+ assert before is not None, "이 사이드카는 굽기가 받아야 의미가 있다"
+
+ run = {"schemaVersion": 1, "fps": 6,
+ "states": [{"name": "idle", "fps": 6,
+ "frames": [{"index": 0, "present": True}, {"index": 1, "present": True}]}],
+ "curation": {"states": {"idle": {"selected": [0, 1], "breathe": sidecar}}}}
+ got = _run({"mode": "roundtrip", "run": run}, tmp_path)
+ saved = got["payload"]["states"]["idle"].get("breathe")
+ assert saved is not None, "왕복이 호흡 설정을 통째로 지웠다"
+ assert saved.get("depth") is not None, f"왕복이 depth 를 null 로 박았다: {saved}"
+
+ after = state_breathe({"states": {"idle": {"breathe": saved}}}, "idle")
+ assert after["depth"] == before["depth"], "왕복이 굽기가 쓰는 값을 바꿨다"
+ assert after["breaths"] == before["breaths"]
+
+
+# ── 왕복 계약 전수 매트릭스 ─────────────────────────────────────────
+#
+# 아홉 라운드 동안 같은 실패 모드가 값 모양만 바꿔 네 번 반복됐다 (round-3 `splits`,
+# round-6 `depth:"0.08"`, round-7 `breaths:"3.5"`, round-9 `depth` 생략, round-10 `lag:null`).
+# 매번 지적된 한 칸만 메웠기 때문이다. 여기서는 **키 × 값 모양을 전수 열거**해 굽기와
+# 큐레이터의 판정이 어긋나는 칸이 하나도 없음을 한 번에 고정한다.
+
+_VALUE_SHAPES = {
+ "omitted": None, # 키 자체를 안 넣는다
+ "null": None,
+ "string": None,
+ "zero": 0,
+ "negative": -1,
+ "huge": 999,
+ "fractional": 2.5,
+ # `Number("")` 과 `Number([])` 는 **0** 이다 — 정수 검사만 하는 미러는 이 둘을 통과시켜
+ # 첫 autosave 가 사용자 값을 0 으로 덮었다. 파이썬은 `float("")` 이 터져 거부한다.
+ "empty-string": "",
+ "empty-list": [],
+}
+
+
+# 매트릭스가 도는 키 = 사이드카 `breathe` 의 **전체 키**. 한때 `depth`·`breaths`·`lag`
+# 셋뿐이었고, 그동안 `rigid_row` 는 빈 문자열·빈 리스트를 0 으로 덮으면서 알림도 없었다
+# (validator 실측 2026-07-26) — "전수 매트릭스" 가 안 도는 키에 같은 실패 모드가 남아 있었다.
+# `anatomy` 는 값 모양 매트릭스에 넣지 않는다: 굽기가 dict 아닌 값을 전부 `None` 으로
+# 보므로 `0`/`""`/`[]` 가 서로 **동치**이고, 그 칸들은 통과해도 아무것도 보증하지 못한다.
+# 대신 의미 있는 계약(유효한 해부가 왕복에서 그대로 살아남는가)을 아래 전용 테스트로 건다.
+MATRIX_KEYS = ["depth", "breaths", "lag", "rigid_row"]
+
+
+def _sidecar_for(key, shape):
+ base = {"depth": 0.06, "breaths": 2, "lag": 0.1, "rigid_row": 12,
+ # `anatomy` 는 서버가 써넣는 파생 캐시다. 굽기는 이 값을 안 읽지만(매번 다시
+ # 잰다) 큐레이터가 손상된 값을 **조용히 갈아치우면** 안 된다 — 미러가 거부할
+ # 근거이자 사용자가 무엇을 들고 있었는지의 증거다.
+ "anatomy": {"width": 40, "height": 50, "axis_x": 20, "neck_row": 10,
+ "neck_source": "bottleneck", "rigid_row": 12,
+ "rigid_source": "neck", "basis_row": 12, "torso_half": 9.0,
+ "max_half": 11.0, "face": None, "warnings": [],
+ "fingerprint": "pixel:0:deadbeef"}}
+ if shape == "omitted":
+ base.pop(key)
+ elif shape == "null":
+ base[key] = None
+ elif shape == "string":
+ base[key] = "0.08" if key in ("depth", "lag") else "3"
+ elif shape in ("empty-string", "empty-list"):
+ base[key] = "" if shape == "empty-string" else []
+ else:
+ base[key] = _VALUE_SHAPES[shape]
+ return base
+
+
+def _bake_verdict(sidecar):
+ """굽기의 판정 — (수용?, 정규화 결과)."""
+ try:
+ return True, state_breathe({"states": {"idle": {"breathe": sidecar}}}, "idle")
+ except SystemExit:
+ return False, None
+
+
+@node
[email protected]("shape", sorted(_VALUE_SHAPES))
[email protected]("key", MATRIX_KEYS)
+def test_the_curator_agrees_with_the_bake_on_every_value_shape(key, shape, tmp_path):
+ """굽기가 거부하는 사이드카는 큐레이터도 **원본 그대로 두고 알린다**.
+ 굽기가 받는 사이드카는 큐레이터도 받고, 왕복해도 굽기가 쓰는 값이 안 바뀐다.
+
+ 어느 쪽이든 **첫 autosave 가 사용자의 원래 숫자를 바꾸면 안 된다** — 그게 이
+ 플랜에서 네 번 반복된 실패 모드다(굽기가 거부하던 근거가 조용히 사라진다)."""
+ sidecar = _sidecar_for(key, shape)
+ accepted, before = _bake_verdict(sidecar)
+
+ run = {"schemaVersion": 1, "fps": 6,
+ "states": [{"name": "idle", "fps": 6,
+ "frames": [{"index": 0, "present": True}, {"index": 1, "present": True}]}],
+ "curation": {"states": {"idle": {"selected": [0, 1], "breathe": sidecar}}}}
+ got = _run({"mode": "roundtrip", "run": run}, tmp_path)
+ saved = got["payload"]["states"]["idle"].get("breathe")
+ errs = [m for kind, m in got["status"] if kind == "err"]
+
+ if not accepted:
+ assert saved == sidecar, (
+ f"{key}={shape}: 굽기가 거부하는 사이드카를 큐레이터가 바꿔 썼다 — "
+ f"거부 근거가 사라진다\n 원본={sidecar}\n 저장={saved}")
+ assert errs, f"{key}={shape}: 굽기가 거부하는데 화면 알림이 없다"
+ after_accepted, _ = _bake_verdict(saved)
+ assert not after_accepted, f"{key}={shape}: 왕복이 거부를 통과로 바꿨다"
+ else:
+ assert saved is not None, f"{key}={shape}: 굽기가 받는 설정을 큐레이터가 지웠다"
+ after_accepted, after = _bake_verdict(saved)
+ assert after_accepted, (
+ f"{key}={shape}: 왕복이 굽기가 죽는 사이드카를 만들었다\n"
+ f" 원본={sidecar}\n 저장={saved}")
+ assert after == before, (
+ f"{key}={shape}: 왕복이 굽기가 쓰는 값을 바꿨다\n 전={before}\n 후={after}")
+
+
+@node
+def test_a_valid_anatomy_survives_the_round_trip_verbatim(tmp_path):
+ """서버가 얼린 해부는 왕복에서 **한 글자도** 안 바뀐다.
+
+ 특히 `fingerprint` 다: 이 값이 왕복에서 사라지거나 바뀌면 미러의 신선도 판정이
+ 통째로 무력해지고(지문 없음 = 확인 불가 = 거부), 사용자는 호흡 프리뷰가 영구
+ 거부되는 상태에 빠진다. 값 모양 매트릭스는 이 계약을 못 본다 — 굽기가 dict 아닌
+ 해부를 전부 `None` 으로 보므로 손상 모양끼리 동치라서다."""
+ anatomy = {"width": 40, "height": 50, "axis_x": 20, "neck_row": 10,
+ "neck_source": "bottleneck", "rigid_row": 12, "rigid_source": "neck",
+ "basis_row": 12, "torso_half": 9.0, "max_half": 11.0,
+ "face": None, "warnings": [], "fingerprint": "pixel:0:deadbeef"}
+ sidecar = {"depth": 0.06, "breaths": 2, "lag": 0.1, "rigid_row": 12, "anatomy": anatomy}
+ run = {"schemaVersion": 1, "fps": 6,
+ "states": [{"name": "idle", "fps": 6,
+ "frames": [{"index": 0, "present": True}, {"index": 1, "present": True}]}],
+ "curation": {"states": {"idle": {"selected": [0, 1], "breathe": sidecar}}}}
+ got = _run({"mode": "roundtrip", "run": run}, tmp_path)
+ saved = got["payload"]["states"]["idle"].get("breathe")
+ assert saved.get("anatomy") == anatomy, (
+ f"왕복이 해부를 바꿨다 — 신선도 판정의 근거가 사라진다\n"
+ f" 전={anatomy}\n 후={saved.get('anatomy')}")
diff --git a/tests/effects/test_frame_interpolation.py b/tests/effects/test_frame_interpolation.py
new file mode 100644
index 0000000..5b80cdb
--- /dev/null
+++ b/tests/effects/test_frame_interpolation.py
@@ -0,0 +1,138 @@
+# SPDX-License-Identifier: Apache-2.0
+"""AI 프레임 보간(sprite_gen.effects.interpolate) 배관 회귀.
+
+실 생성(provider CLI)은 CI 에서 돌리지 않는다 — interpolator 주입 시그니처로
+배관만 검증: 정합 캔버스 계약(/32 패딩·동일 크기·크로마 배경), 테이크 raw 기록,
+request 갱신 멱등성, 프롬프트 조립, 인덱스/라벨/프로바이더 검증의 요란한 실패.
+"""
+
+import json
+from pathlib import Path
+
+import pytest
+from PIL import Image
+
+from sprite_gen.effects.interpolate import aligned_pair_on_chroma, interpolate_between
+
+MAGENTA = (255, 0, 255)
+
+
+def _figure(canvas: Image.Image, left: int, top: int, eye_open: bool) -> None:
+ for y in range(top, top + 40):
+ for x in range(left, left + 24):
+ canvas.putpixel((x, y), (90, 60, 30, 255))
+ eye_rows = range(top + 10, top + 14) if eye_open else range(top + 12, top + 14)
+ for y in eye_rows:
+ for x in (left + 6, left + 16):
+ canvas.putpixel((x, y), (10, 10, 10, 255))
+
+
+def _build_run(tmp_path: Path) -> Path:
+ run = tmp_path / "run"
+ (run / "raw").mkdir(parents=True)
+ request = {
+ "version": 1, "kind": "sprite-gen-request", "engine": "component-row",
+ "character": {"id": "tween-test", "description": "plumbing fixture"},
+ "cell": {"shape": "square", "size": 64, "safe_margin": 6},
+ "chroma_key": {"name": "magenta", "hex": "#FF00FF", "rgb": list(MAGENTA)},
+ "states": {"wave": {"frames": 2, "fps": 4, "loop": True, "action": "test"}},
+ }
+ (run / "sprite-request.json").write_text(json.dumps(request), encoding="utf-8")
+ strip = Image.new("RGBA", (160, 64), MAGENTA + (255,))
+ _figure(strip, 12, 12, eye_open=True)
+ _figure(strip, 92, 12, eye_open=False)
+ strip.save(run / "raw" / "wave.png")
+ return run
+
+
+def _blend_stub(img0: Image.Image, img1: Image.Image, t: float, prompt: str) -> Image.Image:
+ assert img0.size == img1.size
+ assert "IN-BETWEEN" in prompt and "#FF00FF" in prompt # 프롬프트 조립 검증
+ return Image.blend(img0.convert("RGB"), img1.convert("RGB"), t)
+
+
+def test_aligned_pair_contract(tmp_path: Path) -> None:
+ run = _build_run(tmp_path)
+ strip = Image.open(run / "raw" / "wave.png").convert("RGBA")
+ img0, img1 = aligned_pair_on_chroma(strip, 2, 0, 1, MAGENTA)
+ assert img0.size == img1.size
+ assert img0.width % 32 == 0 and img0.height % 32 == 0
+ assert img0.getpixel((0, 0)) == MAGENTA # 크로마 배경 상수
+ assert img0.mode == "RGB" and img1.mode == "RGB"
+
+
+def test_interpolate_writes_take_and_updates_request(tmp_path: Path) -> None:
+ run = _build_run(tmp_path)
+ target = interpolate_between(run, "wave", 0, 1, t=0.5, label="mid",
+ interpolator=_blend_stub)
+ assert target == run / "raw" / "wave.takes" / "mid.png"
+ assert target.is_file()
+ request = json.loads((run / "sprite-request.json").read_text(encoding="utf-8"))
+ assert request["states"]["wave"]["takes"] == [{"label": "mid", "frames": 1}]
+ # 같은 라벨 재실행 = 덮어쓰기 멱등 (takes 항목이 불어나지 않는다)
+ interpolate_between(run, "wave", 0, 1, t=0.5, label="mid", interpolator=_blend_stub)
+ request = json.loads((run / "sprite-request.json").read_text(encoding="utf-8"))
+ assert request["states"]["wave"]["takes"] == [{"label": "mid", "frames": 1}]
+
+
+def test_interpolate_rejects_bad_inputs(tmp_path: Path) -> None:
+ run = _build_run(tmp_path)
+ with pytest.raises(SystemExit, match="unknown state"):
+ interpolate_between(run, "nope", 0, 1, interpolator=_blend_stub)
+ with pytest.raises(SystemExit, match="out of range"):
+ interpolate_between(run, "wave", 0, 5, interpolator=_blend_stub)
+ with pytest.raises(SystemExit, match="inside"):
+ interpolate_between(run, "wave", 0, 1, t=1.5, interpolator=_blend_stub)
+ with pytest.raises(SystemExit, match="filesystem-safe"):
+ interpolate_between(run, "wave", 0, 1, label="a/b", interpolator=_blend_stub)
+
+
+def test_unknown_provider_rejected(tmp_path: Path) -> None:
+ from sprite_gen.effects.interpolate import gen_interpolator
+ with pytest.raises(SystemExit, match="unknown interpolation provider"):
+ gen_interpolator("rife")
+
+
+def test_tween_scale_normalized_to_reference_pair(tmp_path: Path) -> None:
+ """회귀 2026-07-17 회귀 (tween 32×58 — 형제 28×48 보다 14% 커짐, maintainer 발견).
+
+ 생성형 백엔드는 피사체 크기를 보장하지 않는다 — 중간 프레임의 콘텐츠 높이를
+ 참조 쌍 평균에 맞춰 리스케일해 테이크로 기록해야 한다."""
+ from sprite_gen.effects.interpolate import normalize_tween_scale, _chroma_content_bbox
+ chroma = MAGENTA
+
+ def frame_with_figure(height: int) -> Image.Image:
+ im = Image.new("RGB", (160, 200), chroma)
+ for y in range(200 - height, 200 - 4):
+ for x in (70, 90):
+ for dx in range(12):
+ im.putpixel((x + dx, y), (90, 60, 30))
+ return im
+
+ img0 = frame_with_figure(120)
+ img1 = frame_with_figure(124)
+ oversized = frame_with_figure(170) # 모델이 피사체를 크게 그린 경우
+ fixed = normalize_tween_scale(oversized, img0, img1, chroma)
+ assert fixed.size == img0.size
+ box = _chroma_content_bbox(fixed, chroma)
+ got_h = box[3] - box[1]
+ assert abs(got_h - 118) <= 2, f"normalized content height {got_h}, expected ~118 (mean of 116/120)"
+
+
+def test_interpolate_normalizes_stub_output(tmp_path: Path) -> None:
+ """interpolate_between 경로에서도 정규화가 걸린다 — 스텁이 큰 출력을 내도 테이크는 참조 스케일."""
+ from sprite_gen.effects.interpolate import _chroma_content_bbox
+ run = _build_run(tmp_path)
+
+ def oversized_stub(img0: Image.Image, img1: Image.Image, t: float, prompt: str) -> Image.Image:
+ big = img0.convert("RGB").resize((img0.width * 2, img0.height * 2), Image.Resampling.NEAREST)
+ return big
+
+ target = interpolate_between(run, "wave", 0, 1, t=0.5, label="mid", interpolator=oversized_stub)
+ took = Image.open(target)
+ strip = Image.open(run / "raw" / "wave.png").convert("RGBA")
+ img0, _ = aligned_pair_on_chroma(strip, 2, 0, 1, MAGENTA)
+ assert took.size == img0.size
+ ref_h = (lambda b: b[3] - b[1])(_chroma_content_bbox(img0, MAGENTA))
+ mid_h = (lambda b: b[3] - b[1])(_chroma_content_bbox(took, MAGENTA))
+ assert abs(mid_h - ref_h) <= 2, f"take content height {mid_h} vs reference {ref_h}"
diff --git a/tests/effects/test_palette_post_only.py b/tests/effects/test_palette_post_only.py
new file mode 100644
index 0000000..b3bd6be
--- /dev/null
+++ b/tests/effects/test_palette_post_only.py
@@ -0,0 +1,108 @@
+# SPDX-License-Identifier: Apache-2.0
+"""팔레트 = 절단 후 후처리 전용 불변식 (maintainer 확정 2026-07-20, plan
+sprite-gen/per-frame-pixel-grid).
+
+팔레트(락 포함)는 격자 검출·절단에 어떤 영향도 주면 안 된다. 같은 raw 를
+전혀 다른 팔레트로 두 번 추출하면 절단선(input_grids)·프레임 콘텐츠
+bbox·논리 크기는 완전히 동일하고 색만 달라져야 한다.
+"""
+
+import json
+import random
+from pathlib import Path
+
+from PIL import Image
+
+import sprite_gen.frames.extract as extract_module
+
+MAGENTA = (255, 0, 255)
+
+
+def _logical_art(width, height, seed):
+ rng = random.Random(seed)
+ art = Image.new("RGB", (width, height), MAGENTA)
+ for y in range(height):
+ for x in range(width):
+ if rng.random() < 0.55:
+ art.putpixel((x, y), (rng.randrange(30, 220), rng.randrange(30, 220), rng.randrange(30, 220)))
+ return art
+
+
+def _strip(frames, seed, pitch=8, logical=(20, 36), gap=40):
+ frame = _logical_art(*logical, seed=seed).resize(
+ (logical[0] * pitch, logical[1] * pitch), Image.Resampling.NEAREST)
+ strip = Image.new("RGB", (frame.width * frames + gap * (frames + 1), frame.height + gap * 2), MAGENTA)
+ for i in range(frames):
+ strip.paste(frame, (gap + i * (frame.width + gap), gap))
+ return strip
+
+
+def _build_run(root: Path) -> Path:
+ run_dir = root / "run"
+ (run_dir / "raw").mkdir(parents=True)
+ _strip(2, seed=7).save(run_dir / "raw" / "walk.png")
+ request = {
+ "version": 1,
+ "kind": "sprite-gen-request",
+ "engine": "component-row",
+ "character": {"id": "palettebot", "description": "palette invariant fixture", "base_image": None},
+ "cell": {"shape": "square", "width": 96, "height": 96, "safe_margin_x": 8,
+ "safe_margin_y": 8, "size": 96, "safe_margin": 8},
+ "chroma_key": {"name": "magenta", "hex": "#FF00FF", "rgb": [255, 0, 255], "selection": "fallback"},
+ "states": {"walk": {"frames": 2, "fps": 8, "loop": True, "action": "palette fixture"}},
+ "fit": {"pixel_unfake": True, "logical_height": 48},
+ }
+ (run_dir / "sprite-request.json").write_text(
+ json.dumps(request, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
+ return run_dir
+
+
+def _manifest(run_dir: Path) -> dict:
+ return json.loads((run_dir / "frames" / "frames-manifest.json").read_text(encoding="utf-8"))
+
+
+def _grid_and_geometry(run_dir: Path) -> tuple:
+ row = _manifest(run_dir)["rows"][0]
+ geometry = []
+ for rel in row["files"]:
+ with Image.open(run_dir / rel) as im:
+ alpha = im.getchannel("A")
+ geometry.append((im.size, alpha.getbbox(), alpha.tobytes()))
+ return row.get("input_grids"), geometry
+
+
+def test_palette_never_touches_the_grid(tmp_path: Path) -> None:
+ # run A: 자동 팔레트 산출. run B: 추출 전에 괴상한 2색 팔레트를 핀으로 강제.
+ run_a = _build_run(tmp_path / "a")
+ run_b = _build_run(tmp_path / "b")
+ extract_module.write_pinned_palette(run_b, [(255, 0, 0), (0, 0, 255)], "test-pin")
+
+ assert extract_module.run(run_dir=run_a) == 0
+ assert extract_module.run(run_dir=run_b) == 0
+
+ grids_a, geometry_a = _grid_and_geometry(run_a)
+ grids_b, geometry_b = _grid_and_geometry(run_b)
+
+ # 절단선 자체가 팔레트와 무관해야 한다 (검출 경로에 팔레트 참조 금지)
+ assert grids_a == grids_b
+ # 프레임 논리 크기·콘텐츠 bbox·알파(형상)까지 동일 — 색만 다르다
+ for (size_a, bbox_a, alpha_a), (size_b, bbox_b, alpha_b) in zip(geometry_a, geometry_b):
+ assert size_a == size_b
+ assert bbox_a == bbox_b
+ assert alpha_a == alpha_b
+
+ # 팔레트는 실제로 적용됐어야 한다 (불변식이 '팔레트 무시'로 위장 통과하면 안 됨):
+ # 2색(순적/순청) 강제 런의 불투명 픽셀은 그 두 색조뿐이다 — outline 후처리가
+ # 색을 어둡게 만들 수 있으므로(예: (96,0,0)) 채널 패턴으로 판정한다.
+ row_b = _manifest(run_b)["rows"][0]
+ seen = set()
+ for rel in row_b["files"]:
+ with Image.open(run_b / rel) as im:
+ for r, g, b, a in im.convert("RGBA").getdata():
+ if a:
+ seen.add((r, g, b))
+ assert seen
+ for r, g, b in seen:
+ is_reddish = g == 0 and b == 0
+ is_bluish = r == 0 and g == 0
+ assert is_reddish or is_bluish, (r, g, b)
diff --git a/tests/effects/test_recolor_bake.py b/tests/effects/test_recolor_bake.py
new file mode 100644
index 0000000..17d0fe9
--- /dev/null
+++ b/tests/effects/test_recolor_bake.py
@@ -0,0 +1,186 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Palette-swap bake: determinism, exact/tolerance substitution accuracy, and
+the No-Silent-Fallback reporting contract (nothing outside the map vanishes
+silently — it is named and counted)."""
+
+import json
+from pathlib import Path
+
+import numpy as np
+from PIL import Image
+
+import sprite_gen.effects.recolor as recolor
+
+# Flat art colours in the fixture sheet.
+COAT = (180, 40, 40) # mapped by every variant
+TRIM = (40, 80, 180) # opaque, never mapped -> passthrough
+GLOW = (10, 200, 90) # opaque, never mapped -> passthrough
+NEAR_COAT = (182, 42, 41) # 2 away from COAT (Chebyshev) -> tolerance only
+
+
+def _build_sheet(path: Path) -> None:
+ arr = np.zeros((4, 8, 4), dtype=np.uint8) # H=4, W=8, fully transparent
+ # row 0: four COAT pixels
+ arr[0, 0:4, :3] = COAT
+ arr[0, 0:4, 3] = 255
+ # row 1: two TRIM, two GLOW
+ arr[1, 0:2, :3] = TRIM
+ arr[1, 0:2, 3] = 255
+ arr[1, 2:4, :3] = GLOW
+ arr[1, 2:4, 3] = 255
+ # row 2: one NEAR_COAT (opaque) + one COAT-coloured but nearly transparent
+ arr[2, 0, :3] = NEAR_COAT
+ arr[2, 0, 3] = 255
+ arr[2, 1, :3] = COAT
+ arr[2, 1, 3] = 4 # below alpha threshold -> ignored, not recoloured
+ Image.fromarray(arr, "RGBA").save(path)
+
+
+def _spec(path: Path, *, match: str = "exact", tolerance: int = 0, extra_source: bool = False) -> None:
+ variant_map = {recolor.format_hex(COAT): "#14c814"}
+ if extra_source:
+ variant_map["#010203"] = "#ffffff" # source absent from the sheet -> unused
+ spec = {
+ "version": 1,
+ "kind": "sprite-gen-recolor",
+ "match": match,
+ "tolerance": tolerance,
+ "variants": [
+ {"name": "green", "map": variant_map},
+ {"name": "gold", "map": {recolor.format_hex(COAT): "#f0c000"}},
+ ],
+ }
+ path.write_text(json.dumps(spec), encoding="utf-8")
+
+
+def test_bake_is_byte_deterministic(tmp_path: Path) -> None:
+ base = tmp_path / "base.png"
+ spec = tmp_path / "spec.json"
+ _build_sheet(base)
+ _spec(spec)
+
+ recolor.bake(base, spec, tmp_path / "a")
+ recolor.bake(base, spec, tmp_path / "b")
+
+ for name in ("green.png", "gold.png"):
+ assert (tmp_path / "a" / name).read_bytes() == (tmp_path / "b" / name).read_bytes()
+
+
+def test_exact_swap_hits_only_exact_colour_and_keeps_geometry(tmp_path: Path) -> None:
+ base = tmp_path / "base.png"
+ spec = tmp_path / "spec.json"
+ _build_sheet(base)
+ _spec(spec)
+
+ recolor.bake(base, spec, tmp_path / "out")
+
+ baked = np.asarray(Image.open(tmp_path / "out" / "green.png").convert("RGBA"), dtype=np.uint8)
+ original = np.asarray(Image.open(base).convert("RGBA"), dtype=np.uint8)
+
+ # COAT pixels became the target; alpha unchanged.
+ assert tuple(baked[0, 0, :3]) == (0x14, 0xc8, 0x14)
+ assert baked[0, 0, 3] == 255
+ # TRIM / GLOW untouched.
+ assert tuple(baked[1, 0, :3]) == TRIM
+ assert tuple(baked[1, 2, :3]) == GLOW
+ # NEAR_COAT untouched under exact match.
+ assert tuple(baked[2, 0, :3]) == NEAR_COAT
+ # Sub-threshold COAT pixel not recoloured (RGB preserved).
+ assert tuple(baked[2, 1, :3]) == COAT
+ # Geometry never moves: alpha channel is identical to the base.
+ assert np.array_equal(baked[:, :, 3], original[:, :, 3])
+
+
+def test_report_names_substitutions_passthrough_and_unused(tmp_path: Path) -> None:
+ base = tmp_path / "base.png"
+ spec = tmp_path / "spec.json"
+ _build_sheet(base)
+ _spec(spec, extra_source=True)
+
+ report = recolor.bake(base, spec, tmp_path / "out")
+ green = next(v for v in report["variants"] if v["name"] == "green")
+
+ # 4 COAT pixels swapped (the sub-threshold one does not count).
+ hit = next(s for s in green["substitutions"] if s["from"] == recolor.format_hex(COAT))
+ assert hit["pixels"] == 4
+ assert green["substituted_pixels"] == 4
+
+ # The absent source is reported as unused, not silently ignored.
+ assert any(u["from"] == "#010203" for u in green["unused_sources"])
+
+ # TRIM, GLOW, NEAR_COAT pass through — named and counted, never dropped.
+ passthrough = {c["hex"]: c["pixels"] for c in green["passthrough_colors"]}
+ assert passthrough[recolor.format_hex(TRIM)] == 2
+ assert passthrough[recolor.format_hex(GLOW)] == 2
+ assert passthrough[recolor.format_hex(NEAR_COAT)] == 1
+ assert green["passthrough_pixels"] == 5
+ assert green["passthrough_color_count"] == 3
+
+
+def test_tolerance_matches_near_colour_nearest_wins(tmp_path: Path) -> None:
+ base = tmp_path / "base.png"
+ spec = tmp_path / "spec.json"
+ _build_sheet(base)
+ _spec(spec, match="tolerance", tolerance=3)
+
+ report = recolor.bake(base, spec, tmp_path / "out")
+ baked = np.asarray(Image.open(tmp_path / "out" / "green.png").convert("RGBA"), dtype=np.uint8)
+
+ # NEAR_COAT (2 away) now snaps to COAT's target under tolerance 3.
+ assert tuple(baked[2, 0, :3]) == (0x14, 0xc8, 0x14)
+ green = next(v for v in report["variants"] if v["name"] == "green")
+ hit = next(s for s in green["substitutions"] if s["from"] == recolor.format_hex(COAT))
+ assert hit["pixels"] == 5 # 4 exact + 1 near
+
+
+def test_exact_with_nonzero_tolerance_fails_loud(tmp_path: Path) -> None:
+ base = tmp_path / "base.png"
+ spec = tmp_path / "spec.json"
+ _build_sheet(base)
+ _spec(spec, match="exact", tolerance=3)
+ try:
+ recolor.bake(base, spec, tmp_path / "out")
+ except SystemExit as exc:
+ assert "contradictory" in str(exc)
+ else:
+ raise AssertionError("expected SystemExit on exact+tolerance")
+
+
+def test_extract_palette_orders_by_frequency(tmp_path: Path) -> None:
+ base = tmp_path / "base.png"
+ _build_sheet(base)
+ palette = recolor.extract_palette(base)
+
+ hexes = [c["hex"] for c in palette["colors"]]
+ # COAT is the most frequent opaque colour (4 px), so it leads.
+ assert hexes[0] == recolor.format_hex(COAT)
+ # Sub-threshold pixel excluded -> COAT count is 4, not 5.
+ coat = next(c for c in palette["colors"] if c["hex"] == recolor.format_hex(COAT))
+ assert coat["pixels"] == 4
+ assert palette["color_count"] == len(palette["colors"])
+
+
+def test_extract_palette_max_colors_reports_drop(tmp_path: Path) -> None:
+ base = tmp_path / "base.png"
+ _build_sheet(base)
+ palette = recolor.extract_palette(base, max_colors=1)
+ assert palette["color_count"] == 1
+ # The dropped colours' pixels are reported, not silently cut.
+ assert palette["dropped_colors_pixels"] > 0
+
+
+def test_manifest_propagates_per_variant(tmp_path: Path) -> None:
+ base = tmp_path / "base.png"
+ spec = tmp_path / "spec.json"
+ manifest = tmp_path / "manifest.json"
+ _build_sheet(base)
+ _spec(spec)
+ manifest.write_text(json.dumps({"atlas": "base.png", "sprite_sheet_alpha": "base.png", "cell": {"width": 8}}), encoding="utf-8")
+
+ recolor.bake(base, spec, tmp_path / "out", manifest=manifest)
+
+ for name in ("green", "gold"):
+ data = json.loads((tmp_path / "out" / f"{name}.manifest.json").read_text(encoding="utf-8"))
+ assert data["atlas"] == f"{name}.png"
+ assert data["sprite_sheet_alpha"] == f"{name}.png"
+ assert data["cell"] == {"width": 8} # unrelated fields untouched
diff --git a/tests/effects/test_recolor_docs.py b/tests/effects/test_recolor_docs.py
new file mode 100644
index 0000000..a501922
--- /dev/null
+++ b/tests/effects/test_recolor_docs.py
@@ -0,0 +1,124 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Doc surface lock for the recolor feature.
+
+An external user who only reads the docs must be able to bake colourways. The
+implementation is already covered by `test_recolor_bake` / `test_recolor_curation_view`;
+this file only asserts that the hub and the leaf teach the same commands, that the
+curation sidecar field is named, and that the changelog records the feature.
+Internal project names and absolute personal paths must not appear in the new leaf
+(open-source vocabulary rule for this repo).
+"""
+
+from __future__ import annotations
+
+import re
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[2]
+
+# A denylist is itself published. Anything that would only be secret until this
+# file is read (an operator's login name, a private address, an unpublished
+# project id) is expressed as a *class* below, never as a literal — otherwise the
+# guard leaks exactly what it guards.
+#
+# Literals here are limited to names this repository already prints in its own
+# tracked tree (CHANGELOG / docs / other tests), so naming them again costs
+# nothing new.
+FORBIDDEN_LITERALS_IN_RECOLOR_LEAF = (
+ "synthetic fixture",
+)
+
+# Classes of operator context that must never reach a published doc.
+FORBIDDEN_PATTERNS_IN_RECOLOR_LEAF = (
+ # An absolute path inside somebody's home directory — leaks a login name and
+ # is unusable for every reader who is not that person.
+ (re.compile(r"/(?:Users|home)/[A-Za-z0-9._-]+"), "an absolute personal home path"),
+ # A contact address of any kind.
+ (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_recolor_leaf_doc_exists_and_teaches_both_commands() -> None:
+ text = _read("docs/recolor.md")
+ assert "sprite-gen recolor" in text
+ assert "sprite-gen recolor-palette" in text
+ assert "sprite-gen-recolor" in text # spec kind
+ assert "sprite-gen-recolor-report" in text # report kind
+ assert "variants/" in text
+ assert "recolor.picked" in text
+ assert "curation.json" in text
+ # Exact is the default; tolerance is opt-in — both must be named.
+ assert "exact" in text
+ assert "tolerance" in text
+ assert "No Silent Fallback" in text or "passthrough" in text
+
+
+def test_skill_hub_routes_recolor_triggers_and_points_at_leaf() -> None:
+ text = _read("SKILL.md")
+ # Frontmatter description carries the trigger vocabulary for skill routers.
+ assert "palette swap" in text or "팔레트 스왑" in text
+ assert "recolor" in text
+ 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.
+ assert "scripts/recolor.py" in text
+
+
+def test_curation_and_run_contract_name_the_sidecar_and_folder() -> None:
+ curation = _read("docs/curation.md")
+ assert "recolor" in curation
+ assert "picked" in curation
+ assert "recolor.md" in curation
+
+ run_contract = _read("docs/run-contract.md")
+ assert "variants/" in run_contract
+ assert "recolor" in run_contract
+
+
+def test_readme_and_changelog_surface_the_feature() -> None:
+ readme = _read("README.md")
+ assert "recolor" in readme
+ assert "docs/recolor.md" in readme
+
+ changelog = _read("CHANGELOG.md")
+ # The Unreleased recolor section must exist before a version pin is cut.
+ assert "palette-swap" in changelog or "palette swap" in changelog.lower() or "recolor" in changelog
+ assert "recolor-palette" in changelog
+ assert "recolor.picked" in changelog or "colourway" in changelog.lower() or "colorway" in changelog.lower()
+
+
+# Every file this feature adds to the published tree. The leak found in review was
+# in a *test* file, not in the leaf — so the vocabulary lock covers all of them.
+RECOLOR_SURFACE = (
+ "docs/recolor.md",
+ "scripts/recolor.py",
+ "sprite_gen/effects/recolor.py",
+ "sprite_gen/serve/curator/src/recolor.js",
+ "tests/effects/test_recolor_bake.py",
+ "tests/packaging/test_recolor_cli_entrypoint.py",
+ "tests/serve/test_recolor_curation_view.py",
+ "tests/effects/test_recolor_docs.py",
+)
+
+
+def test_recolor_leaf_stays_open_source_vocabulary() -> None:
+ lowered = _read("docs/recolor.md").lower()
+ for token in FORBIDDEN_LITERALS_IN_RECOLOR_LEAF:
+ assert token.lower() not in lowered, f"docs/recolor.md must not mention {token!r}"
+
+
+def test_recolor_surface_carries_no_operator_context() -> None:
+ for rel in RECOLOR_SURFACE:
+ raw = _read(rel)
+ for pattern, what in FORBIDDEN_PATTERNS_IN_RECOLOR_LEAF:
+ hit = pattern.search(raw)
+ assert hit is None, f"{rel} must not carry {what} (found at offset {hit.start()})"
diff --git a/tests/fixtures/expected-frames-manifest.json b/tests/fixtures/expected-frames-manifest.json
new file mode 100644
index 0000000..efc7d90
--- /dev/null
+++ b/tests/fixtures/expected-frames-manifest.json
@@ -0,0 +1,138 @@
+{
+ "ok": true,
+ "engine": "component-row",
+ "cell": {
+ "shape": "square",
+ "width": 96,
+ "height": 96,
+ "safe_margin_x": 8,
+ "safe_margin_y": 8,
+ "size": 96,
+ "safe_margin": 8
+ },
+ "chroma_key": {
+ "name": "magenta",
+ "hex": "#FF00FF",
+ "rgb": [
+ 255,
+ 0,
+ 255
+ ],
+ "selection": "fallback"
+ },
+ "rows": [
+ {
+ "state": "idle",
+ "frames": 4,
+ "method": "components",
+ "files": [
+ "frames/idle/frame-0.png",
+ "frames/idle/frame-1.png",
+ "frames/idle/frame-2.png",
+ "frames/idle/frame-3.png"
+ ],
+ "frame_records": [
+ {
+ "index": 0,
+ "nontransparent_pixels": 2400,
+ "bbox": [
+ 28,
+ 28,
+ 68,
+ 88
+ ],
+ "edge_pixels": 0,
+ "chroma_adjacent_pixels": 0
+ },
+ {
+ "index": 1,
+ "nontransparent_pixels": 2500,
+ "bbox": [
+ 23,
+ 38,
+ 73,
+ 88
+ ],
+ "edge_pixels": 0,
+ "chroma_adjacent_pixels": 0
+ },
+ {
+ "index": 2,
+ "nontransparent_pixels": 2348,
+ "bbox": [
+ 23,
+ 28,
+ 73,
+ 88
+ ],
+ "edge_pixels": 0,
+ "chroma_adjacent_pixels": 0
+ },
+ {
+ "index": 3,
+ "nontransparent_pixels": 2000,
+ "bbox": [
+ 18,
+ 28,
+ 78,
+ 88
+ ],
+ "edge_pixels": 0,
+ "chroma_adjacent_pixels": 0
+ }
+ ],
+ "ok": true
+ },
+ {
+ "state": "walk",
+ "frames": 3,
+ "method": "components",
+ "files": [
+ "frames/walk/frame-0.png",
+ "frames/walk/frame-1.png",
+ "frames/walk/frame-2.png"
+ ],
+ "frame_records": [
+ {
+ "index": 0,
+ "nontransparent_pixels": 4320,
+ "bbox": [
+ 18,
+ 16,
+ 78,
+ 88
+ ],
+ "edge_pixels": 0,
+ "chroma_adjacent_pixels": 0
+ },
+ {
+ "index": 1,
+ "nontransparent_pixels": 2500,
+ "bbox": [
+ 23,
+ 38,
+ 73,
+ 88
+ ],
+ "edge_pixels": 0,
+ "chroma_adjacent_pixels": 0
+ },
+ {
+ "index": 2,
+ "nontransparent_pixels": 2625,
+ "bbox": [
+ 10,
+ 23,
+ 70,
+ 88
+ ],
+ "edge_pixels": 0,
+ "chroma_adjacent_pixels": 0
+ }
+ ],
+ "ok": true
+ }
+ ],
+ "errors": [],
+ "warnings": []
+}
diff --git a/tests/fixtures/expected-fused-frames-manifest.json b/tests/fixtures/expected-fused-frames-manifest.json
new file mode 100644
index 0000000..ac4e7a9
--- /dev/null
+++ b/tests/fixtures/expected-fused-frames-manifest.json
@@ -0,0 +1,112 @@
+{
+ "ok": true,
+ "engine": "component-row",
+ "cell": {
+ "shape": "square",
+ "width": 96,
+ "height": 96,
+ "safe_margin_x": 8,
+ "safe_margin_y": 8,
+ "size": 96,
+ "safe_margin": 8
+ },
+ "chroma_key": {
+ "name": "magenta",
+ "hex": "#FF00FF",
+ "rgb": [
+ 255,
+ 0,
+ 255
+ ],
+ "selection": "fallback"
+ },
+ "rows": [
+ {
+ "state": "kick",
+ "frames": 3,
+ "method": "components",
+ "files": [
+ "frames/kick/frame-0.png",
+ "frames/kick/frame-1.png",
+ "frames/kick/frame-2.png"
+ ],
+ "frame_records": [
+ {
+ "index": 0,
+ "nontransparent_pixels": 1926,
+ "bbox": [
+ 13,
+ 28,
+ 82,
+ 88
+ ],
+ "edge_pixels": 0,
+ "chroma_adjacent_pixels": 0
+ },
+ {
+ "index": 1,
+ "nontransparent_pixels": 1932,
+ "bbox": [
+ 13,
+ 28,
+ 83,
+ 88
+ ],
+ "edge_pixels": 0,
+ "chroma_adjacent_pixels": 0
+ },
+ {
+ "index": 2,
+ "nontransparent_pixels": 1926,
+ "bbox": [
+ 13,
+ 28,
+ 82,
+ 88
+ ],
+ "edge_pixels": 0,
+ "chroma_adjacent_pixels": 0
+ }
+ ],
+ "ok": true
+ },
+ {
+ "state": "pair",
+ "frames": 2,
+ "method": "components",
+ "files": [
+ "frames/pair/frame-0.png",
+ "frames/pair/frame-1.png"
+ ],
+ "frame_records": [
+ {
+ "index": 0,
+ "nontransparent_pixels": 2400,
+ "bbox": [
+ 28,
+ 28,
+ 68,
+ 88
+ ],
+ "edge_pixels": 0,
+ "chroma_adjacent_pixels": 0
+ },
+ {
+ "index": 1,
+ "nontransparent_pixels": 2400,
+ "bbox": [
+ 28,
+ 28,
+ 68,
+ 88
+ ],
+ "edge_pixels": 0,
+ "chroma_adjacent_pixels": 0
+ }
+ ],
+ "ok": true
+ }
+ ],
+ "errors": [],
+ "warnings": []
+}
diff --git a/tests/fixtures/generate_fixtures.py b/tests/fixtures/generate_fixtures.py
new file mode 100644
index 0000000..df1ad7d
--- /dev/null
+++ b/tests/fixtures/generate_fixtures.py
@@ -0,0 +1,97 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: Apache-2.0
+"""Regenerate the checked-in golden fixture row strips.
+
+The PNGs under tests/fixtures/run/raw/ are the canonical fixture inputs; this
+script is only the recorded recipe that produced them. The shapes are sized to
+fit inside the cell safe area so extraction never hits the LANCZOS resize
+path — every downstream number (bbox, pixel counts) is then pure integer math
+and stable across Pillow versions and platforms.
+
+After regenerating, re-record the golden expectations:
+ python3 scripts/extract_sprite_row_frames.py --run-dir <copy of tests/fixtures/run>
+and refresh tests/fixtures/expected-frames-manifest.json (drop the run_dir key).
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from PIL import Image, ImageDraw
+
+MAGENTA = (255, 0, 255)
+CELL = 96
+
+
+def idle_strip() -> Image.Image:
+ strip = Image.new("RGB", (4 * CELL, CELL), MAGENTA)
+ draw = ImageDraw.Draw(strip)
+ # frame 0: plain rectangle
+ draw.rectangle((12, 20, 51, 79), fill=(40, 180, 60))
+ # frame 1: rectangle plus a detached satellite that must group to this seed
+ draw.rectangle((108, 30, 157, 79), fill=(60, 160, 80))
+ draw.rectangle((120, 10, 127, 17), fill=(60, 160, 80))
+ # frame 2: ellipse
+ draw.ellipse((215, 20, 264, 79), fill=(30, 140, 90))
+ # frame 3: connected L-shape
+ draw.rectangle((300, 20, 319, 79), fill=(50, 170, 70))
+ draw.rectangle((300, 60, 359, 79), fill=(50, 170, 70))
+ return strip
+
+
+def walk_strip() -> Image.Image:
+ strip = Image.new("RGB", (3 * CELL, CELL), MAGENTA)
+ draw = ImageDraw.Draw(strip)
+ # frame 0: tall rectangle
+ draw.rectangle((10, 16, 69, 87), fill=(40, 180, 60))
+ # frame 1: square
+ draw.rectangle((120, 40, 169, 89), fill=(60, 160, 80))
+ # frame 2: two overlapping rectangles (single connected component)
+ draw.rectangle((200, 20, 229, 49), fill=(30, 140, 90))
+ draw.rectangle((215, 45, 259, 84), fill=(30, 140, 90))
+ return strip
+
+
+def fused_kick_strip() -> Image.Image:
+ # Three poses whose arms touch the neighbouring pose: connected-component
+ # extraction sees ONE blob and fails; projection-profile + DP segmentation
+ # (fit.segmentation: "projection") must recover exactly 3 frames by cutting
+ # through the thin arm columns. Shapes stay inside the 80x80 safe area of
+ # each recovered slice so extraction never hits the LANCZOS resize path.
+ strip = Image.new("RGB", (3 * CELL, CELL), MAGENTA)
+ draw = ImageDraw.Draw(strip)
+ # pose bodies: tall rectangles (the projection peaks)
+ draw.rectangle((40, 20, 67, 79), fill=(40, 180, 60))
+ draw.rectangle((130, 16, 157, 75), fill=(60, 160, 80))
+ draw.rectangle((220, 22, 247, 81), fill=(30, 140, 90))
+ # connecting arms: thin bridges (the projection valleys the DP cuts through)
+ draw.rectangle((64, 44, 133, 49), fill=(200, 120, 60))
+ draw.rectangle((154, 52, 223, 57), fill=(200, 120, 60))
+ return strip
+
+
+def separated_pair_strip() -> Image.Image:
+ # Control state for the fused fixture: two cleanly separated poses. It
+ # extracts through plain connected components, so the run keeps writing a
+ # frames manifest even when the fused state fails without the opt-in.
+ strip = Image.new("RGB", (2 * CELL, CELL), MAGENTA)
+ draw = ImageDraw.Draw(strip)
+ draw.rectangle((30, 24, 69, 83), fill=(40, 180, 60))
+ draw.rectangle((126, 24, 165, 83), fill=(60, 160, 80))
+ return strip
+
+
+def main() -> None:
+ raw_dir = Path(__file__).parent / "run" / "raw"
+ raw_dir.mkdir(parents=True, exist_ok=True)
+ idle_strip().save(raw_dir / "idle.png")
+ walk_strip().save(raw_dir / "walk.png")
+ fused_raw_dir = Path(__file__).parent / "run-fused" / "raw"
+ fused_raw_dir.mkdir(parents=True, exist_ok=True)
+ fused_kick_strip().save(fused_raw_dir / "kick.png")
+ separated_pair_strip().save(fused_raw_dir / "pair.png")
+ print(f"wrote fixtures to {raw_dir} and {fused_raw_dir}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tests/fixtures/moe/moe_green.png b/tests/fixtures/moe/moe_green.png
new file mode 100644
index 0000000..910c37e
Binary files /dev/null and b/tests/fixtures/moe/moe_green.png differ
diff --git a/tests/fixtures/moe/moe_heart.png b/tests/fixtures/moe/moe_heart.png
new file mode 100644
index 0000000..d101ad6
Binary files /dev/null and b/tests/fixtures/moe/moe_heart.png differ
diff --git a/tests/fixtures/moe/moe_mirror.png b/tests/fixtures/moe/moe_mirror.png
new file mode 100644
index 0000000..e655f17
Binary files /dev/null and b/tests/fixtures/moe/moe_mirror.png differ
diff --git a/tests/fixtures/moe/moe_red.png b/tests/fixtures/moe/moe_red.png
new file mode 100644
index 0000000..ce7677d
Binary files /dev/null and b/tests/fixtures/moe/moe_red.png differ
diff --git a/tests/fixtures/run-fused/raw/kick.png b/tests/fixtures/run-fused/raw/kick.png
new file mode 100644
index 0000000..eb5a984
Binary files /dev/null and b/tests/fixtures/run-fused/raw/kick.png differ
diff --git a/tests/fixtures/run-fused/raw/pair.png b/tests/fixtures/run-fused/raw/pair.png
new file mode 100644
index 0000000..10e95c8
Binary files /dev/null and b/tests/fixtures/run-fused/raw/pair.png differ
diff --git a/tests/fixtures/run-fused/sprite-request.json b/tests/fixtures/run-fused/sprite-request.json
new file mode 100644
index 0000000..9f1b763
--- /dev/null
+++ b/tests/fixtures/run-fused/sprite-request.json
@@ -0,0 +1,45 @@
+{
+ "version": 1,
+ "kind": "sprite-gen-request",
+ "engine": "component-row",
+ "character": {
+ "id": "fusedbot",
+ "description": "fused-pose synthetic fixture for projection-DP segmentation",
+ "base_image": null
+ },
+ "cell": {
+ "shape": "square",
+ "width": 96,
+ "height": 96,
+ "safe_margin_x": 8,
+ "safe_margin_y": 8,
+ "size": 96,
+ "safe_margin": 8
+ },
+ "chroma_key": {
+ "name": "magenta",
+ "hex": "#FF00FF",
+ "rgb": [255, 0, 255],
+ "selection": "fallback"
+ },
+ "states": {
+ "kick": {
+ "frames": 3,
+ "fps": 8,
+ "loop": true,
+ "action": "three touching poses whose arms fuse into one connected component"
+ },
+ "pair": {
+ "frames": 2,
+ "fps": 4,
+ "loop": true,
+ "action": "two separated control poses that extract without segmentation"
+ }
+ },
+ "fit": {
+ "segmentation": "projection",
+ "align_x": "bbox-center"
+ },
+ "style": "synthetic fused fixture, flat solid shapes on magenta",
+ "motion_phase_guides": false
+}
diff --git a/tests/fixtures/run/raw/idle.png b/tests/fixtures/run/raw/idle.png
new file mode 100644
index 0000000..cd35d41
Binary files /dev/null and b/tests/fixtures/run/raw/idle.png differ
diff --git a/tests/fixtures/run/raw/walk.png b/tests/fixtures/run/raw/walk.png
new file mode 100644
index 0000000..d169ff4
Binary files /dev/null and b/tests/fixtures/run/raw/walk.png differ
diff --git a/tests/fixtures/run/sprite-request.json b/tests/fixtures/run/sprite-request.json
new file mode 100644
index 0000000..8b485ea
--- /dev/null
+++ b/tests/fixtures/run/sprite-request.json
@@ -0,0 +1,41 @@
+{
+ "version": 1,
+ "kind": "sprite-gen-request",
+ "engine": "component-row",
+ "character": {
+ "id": "goldenbot",
+ "description": "deterministic synthetic fixture character",
+ "base_image": null
+ },
+ "cell": {
+ "shape": "square",
+ "width": 96,
+ "height": 96,
+ "safe_margin_x": 8,
+ "safe_margin_y": 8,
+ "size": 96,
+ "safe_margin": 8
+ },
+ "chroma_key": {
+ "name": "magenta",
+ "hex": "#FF00FF",
+ "rgb": [255, 0, 255],
+ "selection": "fallback"
+ },
+ "states": {
+ "idle": {
+ "frames": 4,
+ "fps": 4,
+ "loop": true,
+ "action": "synthetic shapes for golden regression"
+ },
+ "walk": {
+ "frames": 3,
+ "fps": 8,
+ "loop": true,
+ "action": "synthetic shapes for golden regression"
+ }
+ },
+ "style": "synthetic golden fixture, flat solid shapes on magenta",
+ "motion_phase_guides": false
+}
diff --git a/tests/frames/test_alpha_centroid_align.py b/tests/frames/test_alpha_centroid_align.py
new file mode 100644
index 0000000..cee4710
--- /dev/null
+++ b/tests/frames/test_alpha_centroid_align.py
@@ -0,0 +1,91 @@
+# SPDX-License-Identifier: Apache-2.0
+"""align_x "alpha-centroid" (perfectpixel-studio port) unit tests.
+
+The mode is opt-in: defaults must keep producing foot-centroid placement
+(covered bit-for-bit by test_extraction_golden.py). Here we pin the mode's
+own contract: fringe-insensitive alpha-weighted centroid on the cell axis,
+and per-frame placement in the pixel-perfect row path that cancels residual
+registration jitter.
+"""
+
+from PIL import Image
+
+from sprite_gen.frames.extract import (
+ ALPHA_CENTROID_MIN_ALPHA,
+ _alpha_centroid_row_left,
+ _alpha_centroid_x,
+ fit_to_cell,
+ place_row_frame,
+)
+
+
+def _body_with_arm(arm_alpha: int = 255) -> Image.Image:
+ # 16x16 dense body on the right + long 20x2 arm reaching left.
+ sprite = Image.new("RGBA", (40, 20), (0, 0, 0, 0))
+ for y in range(2, 18):
+ for x in range(22, 38):
+ sprite.putpixel((x, y), (200, 60, 60, 255))
+ for y in range(8, 10):
+ for x in range(2, 22):
+ sprite.putpixel((x, y), (60, 60, 200, arm_alpha))
+ return sprite
+
+
+def test_alpha_centroid_ignores_soft_matte_fringe() -> None:
+ fringe = _body_with_arm(arm_alpha=ALPHA_CENTROID_MIN_ALPHA) # α=10 → 프린지 취급
+ with_fringe = _alpha_centroid_x(fringe, 1.0, ALPHA_CENTROID_MIN_ALPHA)
+ plain = _alpha_centroid_x(fringe, 1.0, 0)
+ body_only = _alpha_centroid_x(_body_with_arm(arm_alpha=0), 1.0, 0)
+ assert with_fringe == body_only # 프린지가 무게중심을 못 끈다
+ assert plain < body_only # 임계 없는 기존 centroid 는 왼쪽으로 끌린다
+
+
+def test_fit_to_cell_alpha_centroid_centers_body_mass() -> None:
+ sprite = _body_with_arm()
+ cell = fit_to_cell(sprite, 64, 64, 0, 0, {"align_x": "alpha-centroid", "align_y": "bottom"})
+ placed_cx = _alpha_centroid_x(cell, 1.0, ALPHA_CENTROID_MIN_ALPHA)
+ assert abs(placed_cx - 32.0) <= 1.0 # 무게중심이 셀 중앙에
+ bbox_center = fit_to_cell(sprite, 64, 64, 0, 0, {"align_x": "bbox-center", "align_y": "bottom"})
+ bbox_cx = _alpha_centroid_x(bbox_center, 1.0, ALPHA_CENTROID_MIN_ALPHA)
+ assert abs(bbox_cx - 32.0) > 2.0 # bbox 중심은 뻗은 팔이 몸통을 민다
+
+
+def test_default_fit_is_unchanged_foot_centroid() -> None:
+ sprite = _body_with_arm()
+ default = fit_to_cell(sprite, 64, 64, 0, 0, {})
+ explicit = fit_to_cell(sprite, 64, 64, 0, 0, {"align_x": "foot-centroid"})
+ assert default.tobytes() == explicit.tobytes()
+ opted_in = fit_to_cell(sprite, 64, 64, 0, 0, {"align_x": "alpha-centroid"})
+ assert default.tobytes() != opted_in.tobytes() # 옵트인이 실제로 다르다
+
+
+def test_row_per_frame_left_cancels_registration_jitter() -> None:
+ # 같은 몸통이 행 캔버스 안에서 3px 어긋나 등록된 두 프레임 —
+ # union 공동 left 라면 그 3px 이 그대로 재생 지터로 남는다.
+ frames = []
+ for offset in (0, 3):
+ canvas = Image.new("RGBA", (48, 24), (0, 0, 0, 0))
+ for y in range(4, 20):
+ for x in range(10 + offset, 26 + offset):
+ canvas.putpixel((x, y), (90, 160, 90, 255))
+ frames.append(canvas)
+ scale = 2
+ cell_w = cell_h = 128
+ centroids = []
+ for frame in frames:
+ left = _alpha_centroid_row_left(frame, cell_w, scale)
+ placed = place_row_frame(frame, cell_w, cell_h, scale, left, 0, 4, True)
+ centroids.append(_alpha_centroid_x(placed, 1.0, ALPHA_CENTROID_MIN_ALPHA))
+ assert abs(centroids[0] - centroids[1]) <= float(scale) # 논리 격자 스냅 오차 이내
+ assert abs(centroids[0] - cell_w / 2.0) <= float(scale)
+
+
+def test_row_left_snaps_to_logical_grid_and_clamps() -> None:
+ frame = Image.new("RGBA", (30, 10), (0, 0, 0, 0))
+ for y in range(10):
+ for x in range(30):
+ frame.putpixel((x, y), (10, 10, 10, 255))
+ scale = 3
+ left = _alpha_centroid_row_left(frame, 96, scale)
+ assert left % scale == 0
+ assert 0 <= left <= 96 - frame.width * scale
diff --git a/tests/frames/test_cutout.py b/tests/frames/test_cutout.py
new file mode 100644
index 0000000..9ed3915
--- /dev/null
+++ b/tests/frames/test_cutout.py
@@ -0,0 +1,166 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Tests for the matte-based `cutout` background remover (imported-image utility).
+
+Synthetic fixtures are built in-process (no binary assets): an ivory canvas with
+a centered green square, optionally carrying a pure-white highlight *inside* the
+square. The interior highlight is the crux — a colour-only key would punch a hole
+in it, but the corner flood-fill keys by position so it must survive.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+from PIL import Image
+
+from sprite_gen.frames.cutout import cutout, estimate_background, _detect_key_kind
+
+IVORY = (248, 247, 242)
+GREEN = (86, 133, 39)
+MAGENTA = (255, 0, 255)
+KEY_GREEN = (0, 255, 0)
+
+
+def _make_icon(with_interior_white: bool = False) -> Image.Image:
+ """128x128 ivory bg, centered 64x64 green square, optional white dot inside it."""
+ img = Image.new("RGBA", (128, 128), IVORY + (255,))
+ px = img.load()
+ for y in range(32, 96):
+ for x in range(32, 96):
+ px[x, y] = GREEN + (255,)
+ if with_interior_white:
+ for y in range(56, 72):
+ for x in range(56, 72):
+ px[x, y] = (255, 255, 255, 255) # pure white highlight buried in the object
+ return img
+
+
+def test_uniform_background_removed(tmp_path: Path) -> None:
+ src = tmp_path / "icon.png"
+ _make_icon().save(src)
+ out = tmp_path / "icon_cutout.png"
+ stats = cutout(src, out)
+
+ result = Image.open(out).convert("RGBA")
+ px = result.load()
+ # corners (background) fully transparent
+ for cx, cy in [(0, 0), (127, 0), (0, 127), (127, 127)]:
+ assert px[cx, cy][3] == 0
+ # object center fully opaque and still green
+ r, g, b, a = px[64, 64]
+ assert a == 255
+ assert (r, g, b) == GREEN
+ assert stats["keyed_pixels"] > 0
+
+
+def test_interior_white_highlight_preserved(tmp_path: Path) -> None:
+ """A pure-white region *inside* the object must not be keyed out (no pinhole)."""
+ src = tmp_path / "icon_hl.png"
+ _make_icon(with_interior_white=True).save(src)
+ out = tmp_path / "icon_hl_cutout.png"
+ cutout(src, out)
+
+ px = Image.open(out).convert("RGBA").load()
+ # the interior white dot stays opaque despite matching the ivory background colour
+ r, g, b, a = px[64, 64]
+ assert a == 255
+ assert (r, g, b) == (255, 255, 255)
+
+
+def test_no_silent_fallback_holds(tmp_path: Path) -> None:
+ """cutout() completes without raising — every transparent pixel has zeroed RGB."""
+ src = tmp_path / "icon.png"
+ _make_icon().save(src)
+ out = tmp_path / "icon_cutout.png"
+ cutout(src, out) # would SystemExit if a transparent pixel kept non-zero RGB
+ px = Image.open(out).convert("RGBA").load()
+ r, g, b, a = px[0, 0]
+ assert (r, g, b, a) == (0, 0, 0, 0)
+
+
+def test_white_check_composites_written(tmp_path: Path) -> None:
+ src = tmp_path / "icon.png"
+ _make_icon().save(src)
+ out = tmp_path / "icon_cutout.png"
+ check_dir = tmp_path / "checks"
+ stats = cutout(src, out, white_check_dir=check_dir)
+ assert "white_check" in stats
+ for name in ("cyan", "magenta", "yellow"):
+ assert (check_dir / f"icon_cutout_{name}.png").exists()
+
+
+def test_missing_background_raises(tmp_path: Path) -> None:
+ """A fully object-filled image (no locatable background corners) fails loudly."""
+ src = tmp_path / "full.png"
+ Image.new("RGBA", (64, 64), GREEN + (255,)).save(src)
+ out = tmp_path / "full_cutout.png"
+ with pytest.raises(SystemExit):
+ cutout(src, out)
+
+
+def test_estimate_background_from_corners(tmp_path: Path) -> None:
+ img = _make_icon()
+ assert estimate_background(img) == IVORY
+
+
+# --- key-colour routing (imported images already on a magenta/green key) ------
+
+
+def _make_key_icon(bg: tuple[int, int, int], obj: tuple[int, int, int]) -> Image.Image:
+ img = Image.new("RGBA", (128, 128), bg + (255,))
+ px = img.load()
+ for y in range(32, 96):
+ for x in range(32, 96):
+ px[x, y] = obj + (255,)
+ return img
+
+
+def test_detect_key_kind_classifies_routes() -> None:
+ assert _detect_key_kind(MAGENTA) == "magenta"
+ assert _detect_key_kind(KEY_GREEN) == "green"
+ assert _detect_key_kind(IVORY) == "white"
+ assert _detect_key_kind((240, 240, 240)) == "white" # low-saturation → matte
+
+
+def test_magenta_background_routes_to_extract(tmp_path: Path) -> None:
+ src = tmp_path / "m.png"
+ _make_key_icon(MAGENTA, (90, 140, 60)).save(src) # green object, no magenta in it
+ out = tmp_path / "m_cutout.png"
+ stats = cutout(src, out, key="auto")
+ assert stats["route"] == "extract:magenta"
+ px = Image.open(out).convert("RGBA").load()
+ assert px[0, 0][3] == 0 # magenta background gone
+ assert px[64, 64][3] == 255 # object intact, no hole
+
+
+def test_green_background_routes_to_extract(tmp_path: Path) -> None:
+ src = tmp_path / "g.png"
+ _make_key_icon(KEY_GREEN, (200, 80, 160)).save(src) # magenta-ish object, no key green in it
+ out = tmp_path / "g_cutout.png"
+ stats = cutout(src, out, key="auto")
+ assert stats["route"] == "extract:green"
+ px = Image.open(out).convert("RGBA").load()
+ assert px[0, 0][3] == 0
+ assert px[64, 64][3] == 255
+
+
+def test_white_background_stays_on_matte(tmp_path: Path) -> None:
+ src = tmp_path / "w.png"
+ _make_icon().save(src)
+ stats = cutout(src, tmp_path / "w_cutout.png", key="auto")
+ assert stats["route"] == "matte"
+
+
+def test_explicit_key_overrides_detection(tmp_path: Path) -> None:
+ src = tmp_path / "m.png"
+ _make_key_icon(MAGENTA, (90, 140, 60)).save(src)
+ stats = cutout(src, tmp_path / "m_cutout.png", key="magenta")
+ assert stats["route"] == "extract:magenta"
+
+
+def test_unknown_key_raises(tmp_path: Path) -> None:
+ src = tmp_path / "icon.png"
+ _make_icon().save(src)
+ with pytest.raises(SystemExit):
+ cutout(src, tmp_path / "o.png", key="blue")
diff --git a/tests/frames/test_extract_perf_equivalence.py b/tests/frames/test_extract_perf_equivalence.py
new file mode 100644
index 0000000..0f24477
--- /dev/null
+++ b/tests/frames/test_extract_perf_equivalence.py
@@ -0,0 +1,391 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Byte-identity guard for the extract-performance optimizations (plan
+sprite-gen/extract-performance).
+
+The hot paths `_grid_score_edges`/`_best_phase`, `_matte_ycc`,
+`_flood_clear_background_ycc`, `_cleanup_alpha_ycc` and `_dominant_block_color`
+were rewritten for speed under an absolute determinism contract: same input ->
+byte-identical output. These tests pin that contract structurally by running a
+**naive reference** implementation beside the optimized one and asserting exact
+equality — so any future edit that changes a value, not just the golden run,
+trips here.
+
+For the grid scorer the reference is the *integer-exact* naive form, not the
+original float reduction (plan `sprite-gen/best-phase-hotspot`, 2026-07-25).
+The metric is unchanged; only its evaluation is. See
+`test_grid_uniformity_matches_the_exact_rational_value` for why the rational
+value — not the old float's bit pattern — is the truth being pinned.
+"""
+
+from __future__ import annotations
+
+import math
+from fractions import Fraction
+
+from PIL import Image
+
+from sprite_gen.frames import extract
+
+
+def _synthetic_keyed(width: int = 60, height: int = 48) -> Image.Image:
+ """Green-screen-ish RGBA: flat key bg + shaded key + subject blob + AA
+ fringe + an enclosed key-family pixel (connectivity) + spill band."""
+ img = Image.new("RGBA", (width, height), (0, 0, 0, 0))
+ px = img.load()
+ for y in range(height):
+ for x in range(width):
+ # base key background, slightly shaded by position (gradient noise)
+ g = 238 - ((x + y) % 7)
+ r = 11 + ((x * 3) % 5)
+ b = 27 + ((y * 2) % 5)
+ a = 255
+ # subject blob (a magenta-ish body) in the center
+ if 18 <= x <= 40 and 12 <= y <= 38:
+ r, g, b = 180 + (x % 20), 40 + (y % 15), 150 - (x % 12)
+ # spill band on the blob's left edge (key-direction chroma)
+ if x <= 22:
+ r, g, b = 120, 180, 90
+ # an enclosed key-family pixel deep inside the subject (must survive)
+ if x == 30 and y == 25:
+ r, g, b = 12, 236, 26
+ px[x, y] = (r, g, b, a)
+ return img
+
+
+# --- reference (naive, pre-optimization) implementations --------------------
+
+
+def _ref_cells(component, pitch, phase):
+ """Cell-by-cell opaque pixels, in the scorer's iteration order."""
+ xs = extract._grid_edges(component.width, pitch[0], phase[0])
+ ys = extract._grid_edges(component.height, pitch[1], phase[1])
+ p = component.load()
+ for yi in range(len(ys) - 1):
+ for xi in range(len(xs) - 1):
+ acc = []
+ for y in range(ys[yi], min(ys[yi + 1], component.height)):
+ for x in range(xs[xi], min(xs[xi + 1], component.width)):
+ q = p[x, y]
+ if q[3] >= 128:
+ acc.append(q[:3])
+ yield acc
+
+
+def _ref_grid_uniformity(component, pitch, phase):
+ """Naive form of the integer-exact contract: the cell term is `T / n` with
+ `T = sum |n*v - s|` an exact integer, spelled out pixel by pixel with no
+ symmetry identity and no translate tables. Bit-identical to the optimized
+ scorer — same cell order, same single rounding per cell."""
+ total_dev = 0.0
+ total_n = 0
+ for acc in _ref_cells(component, pitch, phase):
+ n = len(acc)
+ if n < 2:
+ continue
+ s = [sum(c[k] for c in acc) for k in range(3)]
+ t = sum(abs(n * c[k] - s[k]) for c in acc for k in range(3))
+ total_dev += t / n
+ total_n += n
+ return (total_dev / total_n) if total_n else 1e9
+
+
+def _ref_grid_uniformity_rational(component, pitch, phase):
+ """Ground truth with no rounding anywhere — the metric as written on paper
+ (`mean absolute deviation from the cell mean, weighted by cell size`).
+ Independent of how either implementation gets there."""
+ total_dev = Fraction(0)
+ total_n = 0
+ for acc in _ref_cells(component, pitch, phase):
+ n = len(acc)
+ if n < 2:
+ continue
+ mean = [Fraction(sum(c[k] for c in acc), n) for k in range(3)]
+ dev = sum(sum(abs(c[k] - mean[k]) for k in range(3)) for c in acc) / n
+ total_dev += dev * n
+ total_n += n
+ return (total_dev / total_n) if total_n else Fraction(10 ** 9)
+
+
+def _ref_grid_uniformity_float(component, pitch, phase):
+ """The pre-2026-07-25 form: float mean, float absolute deviations, float
+ reduction. Kept to show the rewrite did not change the *metric* — only how
+ exactly it is evaluated."""
+ total_dev = 0.0
+ total_n = 0
+ for acc in _ref_cells(component, pitch, phase):
+ n = len(acc)
+ if n < 2:
+ continue
+ mean = [sum(c[k] for c in acc) / n for k in range(3)]
+ dev = sum(sum(abs(c[k] - mean[k]) for k in range(3)) for c in acc) / n
+ total_dev += dev * n
+ total_n += n
+ return (total_dev / total_n) if total_n else 1e9
+
+
+def _ref_matte(source, key):
+ width, height = source.size
+ out = Image.new("RGBA", source.size, (0, 0, 0, 0))
+ src_pixels = source.load()
+ out_pixels = out.load()
+ _, key_cb, key_cr = extract.rgb_to_ycc(*key)
+ key_vb, key_vr = key_cb - 128.0, key_cr - 128.0
+ key_len = math.hypot(key_vb, key_vr)
+ for y in range(height):
+ for x in range(width):
+ red, green, blue, alpha = src_pixels[x, y]
+ if alpha == 0:
+ continue
+ luma, cb, cr = extract.rgb_to_ycc(red, green, blue)
+ dist = math.hypot(cb - key_cb, cr - key_cr)
+ coverage = extract.smoothstep(extract._YCC_CHROMA_IN, extract._YCC_CHROMA_OUT, dist)
+ if coverage <= 0:
+ continue
+ if key_len > 1 and dist < extract._YCC_DESPILL_BAND:
+ pixel_vb, pixel_vr = cb - 128.0, cr - 128.0
+ proj = (pixel_vb * key_vb + pixel_vr * key_vr) / key_len
+ if proj > 0:
+ weight = extract.smoothstep(
+ 0.0, 1.0, (extract._YCC_DESPILL_BAND - dist) / extract._YCC_DESPILL_BAND
+ ) * extract._YCC_DESPILL_SCALE
+ cb = 128.0 + (pixel_vb - key_vb / key_len * proj * weight)
+ cr = 128.0 + (pixel_vr - key_vr / key_len * proj * weight)
+ red, green, blue = extract.ycc_to_rgb(luma, cb, cr)
+ out_pixels[x, y] = (red, green, blue, int(alpha * coverage))
+ # naive border flood, matching pre-optimization semantics
+ _ref_flood(out, source, key_cb, key_cr)
+ return out
+
+
+def _ref_flood(out, source, key_cb, key_cr):
+ width, height = source.size
+ if width < 3 or height < 3:
+ return
+ src_pixels = source.load()
+ out_pixels = out.load()
+ visited = bytearray(width * height)
+ stack = []
+
+ def push(x, y):
+ position = y * width + x
+ if visited[position]:
+ return
+ red, green, blue = src_pixels[x, y][:3]
+ _, cb, cr = extract.rgb_to_ycc(red, green, blue)
+ if math.hypot(cb - key_cb, cr - key_cr) <= extract._YCC_FLOOD_TOL:
+ visited[position] = 1
+ stack.append(position)
+
+ for x in range(width):
+ push(x, 0)
+ push(x, height - 1)
+ for y in range(height):
+ push(0, y)
+ push(width - 1, y)
+ while stack:
+ position = stack.pop()
+ x, y = position % width, position // width
+ red, green, blue, _ = out_pixels[x, y]
+ out_pixels[x, y] = (red, green, blue, 0)
+ if x > 0:
+ push(x - 1, y)
+ if x < width - 1:
+ push(x + 1, y)
+ if y > 0:
+ push(x, y - 1)
+ if y < height - 1:
+ push(x, y + 1)
+
+
+def _ref_cleanup(image):
+ width, height = image.size
+ if width < 3 or height < 3:
+ return
+ before = image.getchannel("A").tobytes()
+ pixels = image.load()
+
+ def opaque(x, y):
+ if x < 0 or y < 0 or x >= width or y >= height:
+ return 0
+ return 1 if before[y * width + x] > extract._YCC_ALPHA_EMPTY else 0
+
+ for y in range(height):
+ for x in range(width):
+ neighbors = (
+ opaque(x - 1, y) + opaque(x + 1, y) + opaque(x, y - 1) + opaque(x, y + 1)
+ + opaque(x - 1, y - 1) + opaque(x + 1, y - 1)
+ + opaque(x - 1, y + 1) + opaque(x + 1, y + 1)
+ )
+ if before[y * width + x] > extract._YCC_ALPHA_EMPTY:
+ if neighbors == 0:
+ red, green, blue, _ = pixels[x, y]
+ pixels[x, y] = (red, green, blue, 0)
+ elif neighbors >= 7:
+ red, green, blue, _ = pixels[x, y]
+ pixels[x, y] = (red, green, blue, 255)
+
+
+def _ref_dominant(opaque, detail_bias=False):
+ if len(opaque) == 1:
+ return opaque[0][:3]
+
+ def luma(p):
+ return p[0] * 299 + p[1] * 587 + p[2] * 114
+
+ lo = min(opaque, key=luma)
+ hi = max(opaque, key=luma)
+ centroids = [lo[:3], hi[:3]]
+ assign = [0] * len(opaque)
+ for _ in range(3):
+ for i, p in enumerate(opaque):
+ d0 = sum((p[c] - centroids[0][c]) ** 2 for c in range(3))
+ d1 = sum((p[c] - centroids[1][c]) ** 2 for c in range(3))
+ assign[i] = 0 if d0 <= d1 else 1
+ for cluster in (0, 1):
+ members = [p for i, p in enumerate(opaque) if assign[i] == cluster]
+ if members:
+ centroids[cluster] = tuple(sum(p[c] for p in members) // len(members) for c in range(3))
+ dominant = 0 if assign.count(0) >= assign.count(1) else 1
+ if detail_bias:
+ darker = 0 if luma(centroids[0]) <= luma(centroids[1]) else 1
+ share = assign.count(darker) / len(assign)
+ if (
+ darker != dominant
+ and share >= 0.40
+ and luma(centroids[darker]) < 70000
+ and luma(centroids[1 - darker]) - luma(centroids[darker]) > 50000
+ ):
+ dominant = darker
+ members = [p for i, p in enumerate(opaque) if assign[i] == dominant]
+ return tuple(sum(p[c] for p in members) // len(members) for c in range(3))
+
+
+# --- equivalence tests ------------------------------------------------------
+
+
+def test_grid_uniformity_byte_identical_to_reference():
+ img = _synthetic_keyed()
+ for pitch in [(7.0, 7.0), (7.82, 8.28), (6.17, 6.32), (5.0, 9.0)]:
+ for phase in [(0.0, 0.0), (1.3, 2.9), (3.0, 3.0), (pitch[0] * 5 / 8, pitch[1] * 3 / 8)]:
+ ref = _ref_grid_uniformity(img, pitch, phase)
+ got = extract._grid_uniformity(img, pitch, phase)
+ # exact float equality — determinism contract, not approximate
+ assert got == ref, f"pitch={pitch} phase={phase}: {got!r} != {ref!r}"
+
+
+def test_grid_uniformity_matches_the_exact_rational_value():
+ """The scorer's only rounding is one division per cell plus the float
+ accumulation across cells — so it tracks the on-paper value to ~1e-15.
+
+ This is the contract that replaced "byte-identical to the old float
+ reduction" (plan `sprite-gen/best-phase-hotspot`, 2026-07-25). The old form
+ accumulated floats per pixel; the integer-exact form is the same metric
+ evaluated without that accumulation, which lands a last-ulp apart (measured
+ max relative gap 1.8e-16 on synthetic_fixture_b). The truth is the rational value,
+ not the old float's bit pattern — so both are checked against it here.
+ """
+ img = _synthetic_keyed()
+ for pitch in [(7.0, 7.0), (7.82, 8.28), (6.17, 6.32)]:
+ for phase in [(0.0, 0.0), (1.3, 2.9), (pitch[0] * 5 / 8, pitch[1] * 3 / 8)]:
+ exact = float(_ref_grid_uniformity_rational(img, pitch, phase))
+ got = extract._grid_uniformity(img, pitch, phase)
+ old = _ref_grid_uniformity_float(img, pitch, phase)
+ assert math.isclose(got, exact, rel_tol=1e-14), f"{pitch} {phase}: {got!r} vs {exact!r}"
+ assert math.isclose(old, exact, rel_tol=1e-14), f"{pitch} {phase}: {old!r} vs {exact!r}"
+
+
+def test_grid_rows_rejects_a_non_rgba_component():
+ """The row index reads alpha at stride 4 — a 3-channel image would silently
+ read colour bytes as alpha, so it has to fail loudly instead."""
+ import pytest
+
+ with pytest.raises(ValueError, match="RGBA"):
+ extract._grid_rows(_synthetic_keyed().convert("RGB"))
+
+
+def _sparse_alpha_grid() -> Image.Image:
+ """12x12 / 4px cells, built to exercise the two edges `_synthetic_keyed` misses.
+
+ That fixture is opaque everywhere (alpha 255) and its smallest scored cell holds
+ 3 opaque pixels, so the alpha cutoff and the `n < 2` guard never actually run —
+ mutating either survived the suite (demo-hero, 2026-07-25). Here:
+
+ - cell (0,0) holds **exactly two** opaque pixels of different colours, so its
+ deviation is non-zero and dropping it (`n < 3`) moves the total.
+ - cell (1,1) mixes alpha 127 and 128 in colours far apart, so shifting the
+ cutoff by one moves both the membership and the mean.
+ """
+ img = Image.new("RGBA", (12, 12), (0, 0, 0, 0))
+ px = img.load()
+ px[0, 0] = (10, 20, 30, 255)
+ px[1, 0] = (200, 210, 220, 255) # cell (0,0): n == 2 exactly
+ px[4, 4] = (0, 0, 0, 128) # cell (1,1): on the cutoff — opaque
+ px[5, 4] = (255, 255, 255, 127) # cell (1,1): one below — transparent
+ px[6, 4] = (90, 40, 160, 255)
+ px[4, 5] = (30, 200, 70, 200)
+ for y in range(8, 12): # cell (2,2): a plain populated cell
+ for x in range(8, 12):
+ px[x, y] = (120 + x, 60 + y, 200 - x, 255)
+ return img
+
+
+def test_grid_uniformity_honours_the_alpha_cutoff_and_the_two_pixel_floor():
+ """Pins the cell-membership rules, not just the arithmetic — the reference
+ re-derives both from the pixels, so a drifted cutoff or floor shows up as a
+ score mismatch."""
+ img = _sparse_alpha_grid()
+ for phase in [(0.0, 0.0), (1.0, 2.0)]:
+ ref = _ref_grid_uniformity(img, (4.0, 4.0), phase)
+ got = extract._grid_uniformity(img, (4.0, 4.0), phase)
+ assert got == ref, f"phase={phase}: {got!r} != {ref!r}"
+ # the fixture is only meaningful if those cells actually reach the scorer
+ assert got != 1e9, "fixture scored nothing — the cells were all skipped"
+
+
+def test_best_phase_byte_identical_to_reference():
+ img = _synthetic_keyed()
+ for pitch in [(7.0, 7.0), (7.82, 8.28), (6.17, 6.32)]:
+ # reference argmin over the same 8x8 grid, same tie-break (strict <)
+ best = (0.0, 0.0)
+ best_score = None
+ for i in range(8):
+ for j in range(8):
+ phase = (pitch[0] * i / 8, pitch[1] * j / 8)
+ score = _ref_grid_uniformity(img, pitch, phase)
+ if best_score is None or score < best_score:
+ best_score = score
+ best = phase
+ assert extract._best_phase(img, pitch) == best, f"pitch={pitch}"
+
+
+def test_matte_and_flood_byte_identical_to_reference():
+ img = _synthetic_keyed()
+ key = (0, 255, 0)
+ ref = _ref_matte(img, key)
+ got, frac = extract._matte_ycc(img, key)
+ assert got.tobytes() == ref.tobytes()
+ # frac is derived from the matted alpha histogram — must match too
+ opaque = sum(ref.getchannel("A").histogram()[extract._YCC_ALPHA_EMPTY + 1:])
+ assert frac == opaque / (img.width * img.height)
+
+
+def test_cleanup_alpha_byte_identical_to_reference():
+ img = _synthetic_keyed()
+ got, _ = extract._matte_ycc(img, (0, 255, 0))
+ ref = got.copy()
+ extract._cleanup_alpha_ycc(got)
+ _ref_cleanup(ref)
+ assert got.tobytes() == ref.tobytes()
+
+
+def test_dominant_block_color_byte_identical_to_reference():
+ # deterministic pixel sets covering single, two-cluster, and detail-bias cases
+ cases = [
+ [(200, 30, 40)],
+ [(10, 10, 10), (240, 240, 240), (12, 8, 9), (250, 249, 248), (11, 11, 12)],
+ [(5, 5, 5)] * 3 + [(250, 250, 250)] * 4,
+ [(i * 7 % 256, i * 13 % 256, i * 29 % 256) for i in range(50)],
+ ]
+ for opaque in cases:
+ for bias in (False, True):
+ assert extract._dominant_block_color(list(opaque), bias) == _ref_dominant(list(opaque), bias)
diff --git a/tests/frames/test_extraction_golden.py b/tests/frames/test_extraction_golden.py
new file mode 100644
index 0000000..051d010
--- /dev/null
+++ b/tests/frames/test_extraction_golden.py
@@ -0,0 +1,58 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Golden regression for connected-component frame extraction.
+
+Fixed synthetic row strips (tests/fixtures/run/raw/) go through
+extract_sprite_row_frames.py and the resulting frames-manifest.json must match
+the recorded expectations bit-for-bit: frame counts, extraction method, per
+frame bbox and pixel counts. Any change in extraction behaviour shows up here.
+"""
+
+import json
+from pathlib import Path
+
+from PIL import Image
+
+from conftest import run_script
+
+EXPECTED = json.loads(
+ (Path(__file__).resolve().parent.parent / "fixtures" / "expected-frames-manifest.json").read_text(encoding="utf-8")
+)
+
+
+def test_extraction_matches_golden_manifest(fixture_run_dir: Path) -> None:
+ result = run_script("extract_sprite_row_frames.py", "--run-dir", str(fixture_run_dir))
+ assert result.returncode == 0, result.stdout + result.stderr
+
+ manifest = json.loads((fixture_run_dir / "frames" / "frames-manifest.json").read_text(encoding="utf-8"))
+ manifest.pop("run_dir")
+ # 엔진 소스 해시/기록 플래그는 휘발성 스탬프 — 골든 비교 대상이 아니다
+ manifest.pop("engine_revision", None)
+ manifest.pop("extract_args", None)
+ for _row in manifest.get("rows", []):
+ _row.pop("engine_revision", None)
+ assert manifest == EXPECTED
+
+
+def test_extracted_frames_are_cell_sized_rgba(fixture_run_dir: Path) -> None:
+ result = run_script("extract_sprite_row_frames.py", "--run-dir", str(fixture_run_dir))
+ assert result.returncode == 0, result.stdout + result.stderr
+
+ for row in EXPECTED["rows"]:
+ for relative in row["files"]:
+ frame_path = fixture_run_dir / relative
+ assert frame_path.is_file(), f"missing {relative}"
+ with Image.open(frame_path) as frame:
+ assert frame.mode == "RGBA"
+ assert frame.size == (EXPECTED["cell"]["width"], EXPECTED["cell"]["height"])
+
+
+def test_extraction_fails_without_raw_strip(fixture_run_dir: Path) -> None:
+ (fixture_run_dir / "raw" / "walk.png").unlink()
+ result = run_script("extract_sprite_row_frames.py", "--run-dir", str(fixture_run_dir))
+ assert result.returncode == 1
+ # Strict whole-generation atomicity: a failed FIRST extract publishes no partial generation
+ # to canonical frames/; the observable ok:false failure signal lives in extract-failure.json.
+ assert not (fixture_run_dir / "frames").exists()
+ failure = json.loads((fixture_run_dir / "extract-failure.json").read_text(encoding="utf-8"))
+ assert failure["ok"] is False
+ assert any("missing raw strip" in error for error in failure["errors"])
diff --git a/tests/frames/test_grid_record_exactness.py b/tests/frames/test_grid_record_exactness.py
new file mode 100644
index 0000000..78c51fc
--- /dev/null
+++ b/tests/frames/test_grid_record_exactness.py
@@ -0,0 +1,166 @@
+# SPDX-License-Identifier: Apache-2.0
+"""기록된 격자가 진실인가 — 칸수 불변식 + 쌍둥이 풋프린트 (plan sprite-gen/grid-record-exactness).
+
+회귀 (2026-07-18 side_idle): kCentroid 가 실제 샘플한 격자(31×58)와 manifest 에 기록된
+절단선(45×83 — 반피치 하모닉)이 **서로 다른 검출 패스**에서 나와, 오버레이가 최종 픽셀과 무관한
+격자를 그렸다. 그 이중 검출은 프레임별 검출 엔진(v1.56.75+)이 제거했지만, **"기록 칸수 == 최종
+픽셀 수" 를 단정으로 못박은 곳은 없었다** — 표시측 `display.js` 의 ±1 관용 가드만 있었고, 그건
+엔진이 거짓을 기록해도 조용히 격자를 접는 쪽으로 실패한다.
+
+계측 근거 (2026-07-25, `_measure_grid_slack.py`, 피치 4·8·9.5·13·17.24·21.7 × 셀 48~256 =
+10조합): 칸수 delta 전부 0, 쌍둥이 어긋남 전부 0.0 논리픽셀. 관용치가 아니라 **정확 일치**가
+현재 엔진의 실제 동작이므로, 그 사실을 단정으로 고정한다 (여유를 재고 나서 조인다).
+"""
+
+from __future__ import annotations
+
+import json
+import random
+
+from PIL import Image
+
+import sprite_gen.frames.extract as extract_module
+from sprite_gen.curate.curation import pixel_snap_scale
+
+MAGENTA = (255, 0, 255)
+
+
+def _logical_art(width: int, height: int, seed: int) -> Image.Image:
+ rng = random.Random(seed)
+ art = Image.new("RGB", (width, height), MAGENTA)
+ for y in range(height):
+ for x in range(width):
+ if rng.random() < 0.55:
+ art.putpixel((x, y), (rng.randrange(30, 220), rng.randrange(30, 220),
+ rng.randrange(30, 220)))
+ return art
+
+
+def _build_run(root, pitch: float, cell: int = 96, logical_height: int = 48,
+ frames: int = 2, logical=(20, 36)) -> "object":
+ """pp 런 하나. 비정수 피치는 실수 배율 리샘플로 만든다 — AI 도트의 블록 폭은 정수로
+ 떨어지지 않으므로(예 17.24px) 정수 피치만 재면 라운딩 여유를 과소평가한다."""
+ run_dir = root / "run"
+ (run_dir / "raw").mkdir(parents=True)
+ base = max(2, int(round(pitch)))
+ frame = _logical_art(*logical, seed=7).resize(
+ (logical[0] * base, logical[1] * base), Image.Resampling.NEAREST)
+ if abs(pitch - base) > 1e-6:
+ ratio = pitch / base
+ frame = frame.resize((round(frame.width * ratio), round(frame.height * ratio)),
+ Image.Resampling.LANCZOS)
+ gap = 40
+ strip = Image.new("RGB", (frame.width * frames + gap * (frames + 1),
+ frame.height + gap * 2), MAGENTA)
+ for index in range(frames):
+ strip.paste(frame, (gap + index * (frame.width + gap), gap))
+ strip.save(run_dir / "raw" / "walk.png")
+ margin = max(2, cell // 16)
+ (run_dir / "sprite-request.json").write_text(json.dumps({
+ "version": 1, "kind": "sprite-gen-request", "engine": "component-row",
+ "character": {"id": "gridbot", "description": "grid record fixture", "base_image": None},
+ "cell": {"shape": "square", "width": cell, "height": cell, "safe_margin_x": margin,
+ "safe_margin_y": margin, "size": cell, "safe_margin": margin},
+ "chroma_key": {"name": "magenta", "hex": "#FF00FF", "rgb": [255, 0, 255],
+ "selection": "fallback"},
+ "states": {"walk": {"frames": frames, "fps": 8, "loop": True, "action": "grid fixture"}},
+ "fit": {"pixel_unfake": True, "logical_height": logical_height},
+ }, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
+ return run_dir
+
+
+def _row_and_scale(run_dir):
+ manifest = json.loads((run_dir / "frames" / "frames-manifest.json").read_text(encoding="utf-8"))
+ request = json.loads((run_dir / "sprite-request.json").read_text(encoding="utf-8"))
+ return manifest["rows"][0], (pixel_snap_scale(request) or 1)
+
+
+def _content_logical_size(path, scale: int) -> tuple[int, int]:
+ with Image.open(path) as im:
+ box = im.convert("RGBA").getchannel("A").getbbox()
+ return (box[2] - box[0]) // scale, (box[3] - box[1]) // scale
+
+
+def _cell_counts(grid: dict) -> tuple[int, int]:
+ return len(grid["x"]) - 1, len(grid["y"]) - 1
+
+
+def test_recorded_grid_cell_count_equals_final_pixel_count(tmp_path) -> None:
+ """기록 칸수 == 최종 콘텐츠 픽셀 수. **정확 일치**다 (관용치 없음).
+
+ 이게 깨지면 기록이 진실이 아니라는 뜻이고, 오버레이는 최종 픽셀과 무관한 격자를 그린다."""
+ run_dir = _build_run(tmp_path, pitch=8)
+ assert extract_module.run(run_dir=run_dir) == 0
+ row, scale = _row_and_scale(run_dir)
+ grids = row.get("input_grids")
+ assert grids, "input_grids 가 기록되지 않았다 — 격자 진실의 소유자가 없어진다"
+ for index, rel in enumerate(row["files"]):
+ final = _content_logical_size(run_dir / rel, scale)
+ assert _cell_counts(grids[index]) == final, (
+ f"frame {index}: 기록 칸수 {_cell_counts(grids[index])} != 최종 픽셀 수 {final}")
+
+
+def test_cell_count_invariant_catches_a_half_pitch_harmonic(tmp_path) -> None:
+ """mutant 검증: 반피치 하모닉으로 기록을 오염시키면 위 단정이 **실제로** 잡는가.
+
+ 2026-07-18 회귀의 형태를 그대로 재현한다 (기록 45칸 vs 최종 31칸). 단정이 잡지 못하면
+ 그 테스트는 통과만 하는 장식이다."""
+ run_dir = _build_run(tmp_path, pitch=8)
+ assert extract_module.run(run_dir=run_dir) == 0
+ row, scale = _row_and_scale(run_dir)
+ grid = dict(row["input_grids"][0])
+ # 반피치: 절단선 사이에 중간점을 끼워 칸수를 2배로 만든다 (하모닉 오검출과 같은 결과)
+ harmonic_x = [grid["x"][0]]
+ for a, b in zip(grid["x"], grid["x"][1:]):
+ harmonic_x += [(a + b) / 2, b]
+ mutant = {"x": harmonic_x, "y": grid["y"]}
+ final = _content_logical_size(run_dir / row["files"][0], scale)
+ assert _cell_counts(grid) == final # 원본은 통과
+ assert _cell_counts(mutant) != final, "mutant 가 단정을 통과했다 — 불변식이 아무것도 막지 못한다"
+
+
+def test_twin_footprint_matches_the_final_frame_exactly(tmp_path) -> None:
+ """orig 쌍둥이의 콘텐츠 bbox 가 최종 프레임과 **논리픽셀 단위로 정확히** 겹친다.
+
+ 어긋나면 픽셀퍼펙트 토글에서 스프라이트가 튄다 (회귀 2026-07-18 항목 2: final top 0 vs
+ orig top 1). `tests/test_pixel_snap.py` 는 같은 축을 ±2 논리픽셀 경계로 지키는데, 실측
+ (10조합)에서 실제 어긋남은 0.0 이므로 여기서 정확 일치를 단정한다 — 경계 테스트는 회귀
+ 안전망으로 남기고, 이 테스트가 정확성을 잃는 순간을 잡는다."""
+ run_dir = _build_run(tmp_path, pitch=8)
+ assert extract_module.run(run_dir=run_dir) == 0
+ row, scale = _row_and_scale(run_dir)
+ assert row.get("orig_files"), "orig 쌍둥이가 없다 — 이 축을 검증할 재료가 없다"
+ checked = 0
+ for index, rel in enumerate(row["files"]):
+ head, _, name = rel.rpartition("/")
+ orig_path = run_dir / f"{head}/orig/{name}"
+ if not orig_path.is_file():
+ continue
+ with Image.open(run_dir / rel) as pixel, Image.open(orig_path) as orig:
+ pixel_box = pixel.convert("RGBA").getchannel("A").getbbox()
+ orig_box = orig.convert("RGBA").getchannel("A").getbbox()
+ orig_scale = max(1, orig.width // pixel.width)
+ for edge, (o, p) in enumerate(zip(orig_box, pixel_box)):
+ assert o / orig_scale / scale == p / scale, (
+ f"frame {index} edge {edge}: orig {o}/{orig_scale} vs final {p} (논리픽셀 어긋남)")
+ checked += 1
+ assert checked, "쌍둥이를 한 장도 검사하지 못했다"
+
+
+def test_grid_record_stays_exact_across_pitches_and_cells(tmp_path) -> None:
+ """정수/비정수 피치·여러 셀 크기에서 두 불변식이 함께 성립한다.
+
+ 비정수 피치(17.24)는 AI 도트의 실제 성질이고, 셀 크기는 pp_scale 을 1/2/4 로 가른다 —
+ 라운딩이 걸릴 조건을 골라 넣었다 (계측 표: 플랜 Notes)."""
+ cases = [(8, 48, 30), (17.24, 48, 42), (9.5, 64, 48), (4, 96, 48)]
+ for pitch, cell, logical_height in cases:
+ run_dir = _build_run(tmp_path / f"p{pitch}c{cell}", pitch=pitch, cell=cell,
+ logical_height=logical_height)
+ assert extract_module.run(run_dir=run_dir) == 0, f"pitch {pitch} cell {cell} 추출 실패"
+ row, scale = _row_and_scale(run_dir)
+ for index, rel in enumerate(row["files"]):
+ final = _content_logical_size(run_dir / rel, scale)
+ grid = (row.get("input_grids") or [None])[index]
+ assert grid, f"pitch {pitch} cell {cell} frame {index}: 기록 없음"
+ assert _cell_counts(grid) == final, (
+ f"pitch {pitch} cell {cell} frame {index}: {_cell_counts(grid)} != {final}")
diff --git a/tests/frames/test_heal_async.py b/tests/frames/test_heal_async.py
new file mode 100644
index 0000000..eb468ad
--- /dev/null
+++ b/tests/frames/test_heal_async.py
@@ -0,0 +1,159 @@
+# SPDX-License-Identifier: Apache-2.0
+"""장기 heal 의 비차단 계약 (plan sprite-gen/long-op-loading-ux).
+
+엔진 갱신 후 첫 /api/run 이 heal 을 요청 안에서 동기로 돌리면 첫 탭이 진행률
+UI 없이 빈 화면으로 수십 분 멈춘다 (회귀 2026-07-20). maybe_heal 은 heal 을
+백그라운드로 발사하고 그레이스만 대기하며 busy 여부만 반환한다. heal 리포트의
+소비자는 take_heal_report() 하나 — /api/run 성공 스냅샷 경로 — 뿐이다.
+/api/progress 폴링·다운로드가 heal 완료 직후 먼저 호출돼도 리포트가 유실되지
+않는다 (validator validator 재현 결함의 회귀 가드, 단일 소비자 원칙).
+"""
+
+from __future__ import annotations
+
+import time
+from pathlib import Path
+
+import pytest
+
+ROOT = Path(__file__).resolve().parents[2]
+
+import sprite_gen.serve.serve_curation as serve_curation # noqa: E402
+
+
[email protected](autouse=True)
+def _reset_heal_state():
+ serve_curation._heal_state["thread"] = None
+ serve_curation._heal_state["pending_report"] = None
+ serve_curation._heal_state["failed_attempt"] = None
+ yield
+ thread = serve_curation._heal_state["thread"]
+ if thread is not None:
+ thread.join(timeout=10)
+ serve_curation._heal_state["thread"] = None
+ serve_curation._heal_state["pending_report"] = None
+ serve_curation._heal_state["failed_attempt"] = None
+
+
+def _walk_report(run_dir):
+ return {"healed": ["walk"], "kept_stale": [], "failed": [], "notes": []}
+
+
+def _noop_report(run_dir):
+ return {"healed": [], "kept_stale": [], "failed": [], "notes": []}
+
+
+def test_long_heal_returns_busy_within_grace(tmp_path: Path, monkeypatch) -> None:
+ release = {"at": time.monotonic() + 4.0}
+
+ def slow_heal(run_dir):
+ while time.monotonic() < release["at"]:
+ time.sleep(0.05)
+ return _walk_report(run_dir)
+
+ monkeypatch.setattr(serve_curation, "heal_run", slow_heal)
+ started = time.monotonic()
+ busy = serve_curation.maybe_heal(tmp_path)
+ elapsed = time.monotonic() - started
+ assert busy is True
+ # 그레이스(1.5s) + 여유 안에 응답해야 첫 탭이 로딩 UI 를 본다
+ assert elapsed < serve_curation._HEAL_GRACE_SECONDS + 1.0
+
+ # heal 완료 후: busy 해제 + 리포트가 단일 소비자에서 1회 나온다
+ serve_curation._heal_state["thread"].join(timeout=10)
+ monkeypatch.setattr(serve_curation, "heal_run", _noop_report)
+ assert serve_curation.maybe_heal(tmp_path) is False
+ report = serve_curation.take_heal_report()
+ assert report is not None and report["healed"] == ["walk"]
+ assert serve_curation.take_heal_report() is None # 정확히 1회
+
+
+def test_progress_poll_never_steals_the_heal_report(tmp_path: Path, monkeypatch) -> None:
+ """validator validator 재현 결함의 회귀 가드: 장기 heal 완료 직후
+ /api/progress(또는 다운로드) 역할의 maybe_heal 이 먼저 호출돼도 리포트는
+ 남아 있어야 하고, /api/run 역할의 take_heal_report 가 정확히 1회 가져간다."""
+ release = {"at": time.monotonic() + 1.7}
+
+ def slow_heal(run_dir):
+ while time.monotonic() < release["at"]:
+ time.sleep(0.05)
+ return _walk_report(run_dir)
+
+ monkeypatch.setattr(serve_curation, "heal_run", slow_heal)
+ assert serve_curation.maybe_heal(tmp_path) is True # 장기 heal — busy 즉답
+ serve_curation._heal_state["thread"].join(timeout=10)
+
+ # 완료 직후: 트리 폴링/다운로드 경로가 먼저 도착하는 시나리오
+ monkeypatch.setattr(serve_curation, "heal_run", _noop_report)
+ assert serve_curation.maybe_heal(tmp_path) is False # /api/progress 역할 — 미소비
+ assert serve_curation.maybe_heal(tmp_path) is False # download 역할 — 미소비
+
+ # 그 다음 /api/run 성공 경로가 리포트를 정확히 1회 가져간다
+ report = serve_curation.take_heal_report()
+ assert report is not None and report["healed"] == ["walk"]
+ assert serve_curation.take_heal_report() is None
+
+
+def test_fresh_heal_stays_synchronous(tmp_path: Path, monkeypatch) -> None:
+ monkeypatch.setattr(serve_curation, "heal_run", _noop_report)
+ started = time.monotonic()
+ busy = serve_curation.maybe_heal(tmp_path)
+ assert busy is False
+ assert time.monotonic() - started < 1.0
+ assert serve_curation.take_heal_report() is None # no-op 리포트는 첨부하지 않는다
+
+
+def test_heal_failure_is_observable_not_fatal(tmp_path: Path, monkeypatch) -> None:
+ def broken_heal(run_dir):
+ raise SystemExit("raw missing")
+
+ monkeypatch.setattr(serve_curation, "heal_run", broken_heal)
+ busy = serve_curation.maybe_heal(tmp_path)
+ if busy: # 스케줄링상 그레이스를 넘겼으면 완주 대기
+ thread = serve_curation._heal_state["thread"]
+ if thread is not None:
+ thread.join(timeout=10)
+ report = serve_curation.take_heal_report()
+ assert report is not None
+ assert any("heal skipped" in note for note in report["notes"])
+ assert serve_curation.maybe_heal(tmp_path) is False
+
+
+def test_failed_heal_is_not_retried_until_inputs_change(tmp_path: Path, monkeypatch) -> None:
+ """결정론적 검증 실패를 폴링마다 재실행해 80%→0%가 반복되면 안 된다."""
+ request = tmp_path / "sprite-request.json"
+ request.write_text("{}\n", encoding="utf-8")
+ calls = []
+
+ def failed_heal(run_dir):
+ calls.append(run_dir)
+ return {"healed": [], "kept_stale": [], "failed": ["walk"],
+ "notes": ["validation failed"]}
+
+ monkeypatch.setattr(serve_curation, "heal_run", failed_heal)
+ assert serve_curation.maybe_heal(tmp_path) is False
+ assert len(calls) == 1
+ assert serve_curation.maybe_heal(tmp_path) is False
+ assert serve_curation.maybe_heal(tmp_path) is False
+ assert len(calls) == 1
+
+ request.write_text('{"changed": true}\n', encoding="utf-8")
+ assert serve_curation.maybe_heal(tmp_path) is False
+ assert len(calls) == 2
+
+
+def test_existing_failure_suppresses_retry_after_server_restart(tmp_path: Path, monkeypatch) -> None:
+ """extract-failure 증거는 프로세스 재기동 뒤에도 같은 시도를 막는다."""
+ request = tmp_path / "sprite-request.json"
+ request.write_text("{}\n", encoding="utf-8")
+ revision = serve_curation._heal_attempt_key(tmp_path)[0]
+ (tmp_path / "extract-failure.json").write_text(
+ '{"ok": false, "engine_revision": "' + revision
+ + '", "rows": [{"state": "walk", "ok": false}]}\n', encoding="utf-8")
+ called = []
+ monkeypatch.setattr(serve_curation, "heal_run", lambda run_dir: called.append(run_dir))
+
+ assert serve_curation.maybe_heal(tmp_path) is False
+ assert called == []
+ report = serve_curation.take_heal_report()
+ assert report is not None and report["failed"] == ["walk"]
diff --git a/tests/frames/test_pitch_ground_truth.py b/tests/frames/test_pitch_ground_truth.py
new file mode 100644
index 0000000..4d2308a
--- /dev/null
+++ b/tests/frames/test_pitch_ground_truth.py
@@ -0,0 +1,291 @@
+"""detect_pixel_pitch 를 합성 정답 데이터로 고정한다.
+
+논리 픽셀아트를 정수 배율 k 로 NEAREST 업스케일하면 참 피치는 정확히 k 다.
+예전 구현은 `w = 1 if p >= 8 else 0` 때문에 k=8,10,12,14 에서 약수 k/2 를
+반환했다 (창이 열린 참 피치의 우연 기대치가 3/p 로 부풀어, 창이 닫힌 약수에
+졌다). 이 테스트가 그 회귀를 막는다.
+"""
+import random
+
+import pytest
+from PIL import Image
+
+from sprite_gen.frames.extract import (
+ _best_phase,
+ detect_pixel_grid,
+ detect_pixel_pitch,
+ grid_snap_downscale,
+ _grid_edges,
+ _grid_phase,
+)
+
+PALETTE = [
+ (240, 210, 175),
+ (60, 40, 30),
+ (40, 90, 180),
+ (230, 225, 200),
+ (150, 90, 50),
+ (20, 20, 20),
+]
+
+
+def _logical_art(width: int = 24, height: int = 40, seed: int = 11) -> Image.Image:
+ """비주기 무작위 도트. 주기적 패턴이면 약수도 '진짜' 격자가 되어 테스트가 무의미해진다."""
+ rng = random.Random(seed)
+ img = Image.new("RGB", (width, height))
+ px = img.load()
+ for y in range(height):
+ for x in range(width):
+ px[x, y] = rng.choice(PALETTE)
+ return img
+
+
+def test_integer_pitch_is_detected_exactly():
+ art = _logical_art()
+ for k in (4, 6, 8, 10, 12, 14, 16, 17, 20, 24, 32):
+ upscaled = art.resize((art.width * k, art.height * k), Image.NEAREST)
+ assert detect_pixel_pitch(upscaled) == k, f"pitch {k} misdetected"
+
+
+def test_divisor_is_not_preferred_over_true_pitch():
+ """k=12 에서 6 을 반환하던 회귀의 최소 재현."""
+ art = _logical_art()
+ upscaled = art.resize((art.width * 12, art.height * 12), Image.NEAREST)
+ assert detect_pixel_pitch(upscaled) == 12
+
+
+def test_phase_follows_crop_offset():
+ art = _logical_art()
+ k = 16
+ upscaled = art.resize((art.width * k, art.height * k), Image.NEAREST)
+ for offset in (0, 3, 7, 11):
+ cropped = upscaled.crop((offset, offset, upscaled.width, upscaled.height))
+ assert detect_pixel_pitch(cropped) == k
+ assert _grid_phase(cropped.convert("RGBA"), k)[0] == (-offset) % k
+
+
+def test_no_grid_falls_back_to_one():
+ """격자가 없는 사진 같은 입력은 1(스냅 안 함)로 관측 가능하게 떨어진다."""
+ rng = random.Random(3)
+ noise = Image.new("RGB", (200, 200))
+ px = noise.load()
+ for y in range(200):
+ for x in range(200):
+ px[x, y] = (rng.randrange(256), rng.randrange(256), rng.randrange(256))
+ assert detect_pixel_pitch(noise) == 1
+
+
+def _upscaled(art: Image.Image, scale: float) -> Image.Image:
+ """AI 도트처럼 블록 폭이 정수로 안 떨어지는 판을 만든다 (NEAREST 라 색은 원본 그대로)."""
+ big = art.resize((art.width * 64, art.height * 64), Image.NEAREST)
+ return big.resize((round(art.width * scale), round(art.height * scale)), Image.NEAREST)
+
+
+def _mismatch(a: Image.Image, b: Image.Image) -> int:
+ pa, pb = a.convert("RGB").load(), b.convert("RGB").load()
+ return sum(1 for y in range(a.height) for x in range(a.width) if pa[x, y] != pb[x, y])
+
+
[email protected]("scale", [12.0, 14.35, 16.0, 16.2, 17.24, 20.0, 23.7])
+def test_fractional_pitch_roundtrips_to_the_original_logical_art(scale):
+ """소수 배율로 늘린 도트를 스냅하면 원본 논리 픽셀이 그대로 돌아와야 한다.
+
+ 정수 피치만 보던 예전에는 배율 16.2 / 17.24 에서 셀이 밀려 크기부터 틀렸다
+ (25x41 등). 측정은 소수, 격자선은 길이 등분 -> 결과는 항상 정수 격자다.
+ """
+ art = _logical_art()
+ upscaled = _upscaled(art, scale)
+ pitch, phase = detect_pixel_grid(upscaled)
+ snapped = grid_snap_downscale(upscaled, pitch, phase=phase)
+
+ assert snapped.size == art.size, f"scale {scale}: {snapped.size} != {art.size}"
+ assert abs(pitch[0] - scale) < 0.1, f"scale {scale}: detected {pitch[0]:.3f}"
+ assert abs(pitch[1] - scale) < 0.1, f"scale {scale}: detected {pitch[1]:.3f}"
+ # 소수 배율은 블록 경계가 화면 픽셀 중간에 걸리므로 1% 이내의 색 불일치는 허용한다.
+ assert _mismatch(snapped, art) <= art.width * art.height // 100
+
+
+def test_integer_pitch_still_snaps_exactly():
+ art = _logical_art()
+ for scale in (12, 16, 20):
+ upscaled = _upscaled(art, float(scale))
+ pitch, phase = detect_pixel_grid(upscaled)
+ snapped = grid_snap_downscale(upscaled, pitch, phase=phase)
+ assert snapped.size == art.size
+ assert _mismatch(snapped, art) == 0
+
+
[email protected]("fringe", [1, 7, 14, 20])
+def test_non_integer_bbox_does_not_stretch_the_grid(fringe):
+ """bbox 가 블록의 정수배가 아니어도 셀 폭은 참 피치를 지켜야 한다.
+
+ v1.56.2 회귀: `_grid_edges` 가 length 를 셀 개수로 등분했다. AA 프린지 때문에 bbox 가
+ 27.46 블록이면 셀이 31.44px 로 늘어나(참 블록 30.92px) 칸마다 0.52px 씩 어긋났고,
+ 오른쪽 끝에서 반 블록이 밀려 스냅 결과의 얼굴이 부서졌다 (주인공 chibi-8).
+ """
+ art = _logical_art(width=24, height=30)
+ k = 31
+ upscaled = art.resize((art.width * k, art.height * k), Image.NEAREST)
+ # 오른쪽에 블록의 정수배가 아닌 자투리를 붙인다 (AA 프린지 흉내)
+ padded = Image.new("RGB", (upscaled.width + fringe, upscaled.height), (20, 20, 20))
+ padded.paste(upscaled, (0, 0))
+
+ pitch, phase = detect_pixel_grid(padded)
+ edges = _grid_edges(padded.width, pitch[0], phase[0])
+ widths = [edges[i + 1] - edges[i] for i in range(len(edges) - 1)]
+
+ # 마지막 셀만 자투리를 흡수한다. 나머지는 전부 참 피치 ±1px.
+ for w in widths[:-1]:
+ assert abs(w - k) <= 1, f"cell width {w} drifted from pitch {k} (widths={widths})"
+
+
+def test_pitch_is_detected_per_axis():
+ """가로/세로 블록 크기가 다르면 축별로 따로 잡아야 한다.
+
+ 비균등 리스케일된 생성물은 가로 블록과 세로 블록이 어긋난다 (chibi 베이스:
+ 가로 30.38 / 세로 30.92). 한 피치를 두 축에 강제하면 한 축이 통째로 미끄러졌다
+ — 실측 가로 정렬률 11.7%.
+ """
+ art = _logical_art(width=20, height=24)
+ upscaled = art.resize((art.width * 24, art.height * 30), Image.NEAREST)
+
+ (pitch_x, pitch_y), _ = detect_pixel_grid(upscaled)
+
+ assert abs(pitch_x - 24) < 0.6, f"x pitch {pitch_x:.2f} != 24"
+ assert abs(pitch_y - 30) < 0.6, f"y pitch {pitch_y:.2f} != 30"
+
+
+def test_non_square_pitch_roundtrips():
+ art = _logical_art(width=20, height=24)
+ upscaled = art.resize((art.width * 24, art.height * 30), Image.NEAREST)
+ pitch, phase = detect_pixel_grid(upscaled)
+ snapped = grid_snap_downscale(upscaled, pitch, phase=phase)
+ assert snapped.size == art.size
+ assert _mismatch(snapped, art) == 0
+
+
+def test_wildly_disagreeing_axes_fall_back_to_the_trusted_axis():
+ """한 축의 검출이 무너지면(참 피치의 약수) 엣지가 많은 축의 피치를 쓴다.
+
+ down_carry_walk 회귀: 팔을 위로 든 포즈는 세로로 균일한 막대가 많아 세로 엣지가
+ 적고, 그 축에서 참 피치 9 대신 약수 3 이 이겼다 (가로 9 / 세로 3). 스냅 결과가 짓눌렸다.
+ 축별 피치가 1.5배 넘게 벌어지는 것은 물리적으로 불가능하다 — 비균등 리스케일도 2% 수준이다.
+ """
+ art = _logical_art(width=20, height=30)
+ upscaled = art.resize((art.width * 12, art.height * 12), Image.NEAREST)
+ # 아래쪽 절반을 단색으로 덮어 세로 엣지를 고갈시킨다 (긴 균일 막대 흉내)
+ flat = Image.new("RGB", (upscaled.width, upscaled.height // 2), (40, 90, 180))
+ upscaled.paste(flat, (0, upscaled.height // 2))
+
+ (pitch_x, pitch_y), _ = detect_pixel_grid(upscaled)
+
+ assert max(pitch_x, pitch_y) / min(pitch_x, pitch_y) <= 1.5, (
+ f"axes disagree wildly: {pitch_x:.2f} vs {pitch_y:.2f}"
+ )
+
+
+def test_synthetic_axis_collapse_is_repaired():
+ """한 축 피치를 인위로 약수까지 끌어내려도 최종 반환은 두 축이 붙어 있어야 한다."""
+ art = _logical_art(width=24, height=24)
+ upscaled = art.resize((art.width * 9, art.height * 9), Image.NEAREST)
+ (px, py), _ = detect_pixel_grid(upscaled)
+ assert abs(px - py) < 1.0, f"{px:.2f} vs {py:.2f}"
+ assert px > 5.0 and py > 5.0, "collapsed to a divisor"
+
+
+# --- 피치 패밀리 가드 (resolve_frame_pitch) -------------------------------
+#
+# per-frame own 피치는 합의 '패밀리'(비율 1.1) 이내에서만 진실이다. 하모닉/붕괴
+# 오검출을 own 으로 믿으면 한 프레임의 거대 native 가 conform_row_logical 의
+# 행 일관 배율을 끌어내려 행 전체가 붕괴한다 (회귀 synthetic_fixture_a up_run,
+# 2026-07-22 — resolve_frame_pitch docstring).
+
+def _resolve(own, consensus):
+ from sprite_gen.frames.extract import resolve_frame_pitch
+ return resolve_frame_pitch(own, consensus)
+
+
+def test_in_family_deviation_keeps_own_pitch():
+ # down_jump frame-0 회귀 (합의 13.00 vs 자체 12.50, 4%): own 이 진실
+ use, outlier = _resolve((12.5, 12.5), (13.0, 13.0))
+ assert use == (12.5, 12.5) and not outlier
+
+
+def test_collapsed_divisor_falls_back_to_consensus():
+ # up_run frame-2 회귀: own 3.00x3.00 은 참 피치의 붕괴 약수
+ use, outlier = _resolve((3.0, 3.0), (7.0, 8.86))
+ assert use == (7.0, 8.86) and outlier
+
+
+def test_harmonic_multiple_falls_back_to_consensus():
+ # up_run frame-0 회귀: own 9.00x8.70 — x 축이 패밀리 밖 (9/7 = 1.29)
+ use, outlier = _resolve((9.0, 8.7), (7.0, 8.86))
+ assert use == (7.0, 8.86) and outlier
+
+
+def test_single_axis_drift_beyond_family_falls_back():
+ # up_run frame-3 회귀: own y 8.00 vs 합의 8.86 (10.7%) — native 캡 초과로
+ # 행 전체 5% 축소를 유발했다. 한 축만 밖이어도 폴백한다.
+ use, outlier = _resolve((7.0, 8.0), (7.0, 8.86))
+ assert use == (7.0, 8.86) and outlier
+
+
+def test_inconclusive_consensus_keeps_own_pitch():
+ # 합의가 무근거(<2.0)면 own 이 유일한 측정이다 — 가드는 발동하지 않는다
+ use, outlier = _resolve((9.0, 9.0), (1.0, 1.0))
+ assert use == (9.0, 9.0) and not outlier
+
+
[email protected]("offset", [3, 11])
+def test_measured_phase_survives_an_offset_grid_where_the_histogram_phase_does_not(offset):
+ """참 위상이 비영인 판에서, 실측 위상만 논리 픽셀을 지켜낸다.
+
+ 회귀 (maintainer 2026-07-25, synthetic_fixture_b down_jump frame-0): 히스토그램 위상이 참 위상에서
+ pitch/2 까지 밀려 눈 4행이 3행으로 병합됐다(8칸→7칸). 여기서는 업스케일한 판을
+ 잘라 참 위상을 강제로 비영으로 만든 뒤 두 위상을 나란히 돌린다 — 실측(k=13):
+
+ offset 3 → 히스토그램 위상은 불일치 377픽셀, 실측 위상은 0
+ offset 11 → 히스토그램 위상은 논리 크기가 23x39 로 **한 칸을 잃고**, 실측은 24x40 유지
+
+ 앞의 라운드트립 테스트(오프셋 0)는 `_best_phase` 가 전 케이스 (0,0) 을 돌려주는 탓에
+ 위상 오검출을 못 잡았다. 이 테스트가 그 구멍을 메운다.
+ """
+ art = _logical_art()
+ k = 13
+ upscaled = art.resize((art.width * k, art.height * k), Image.NEAREST)
+ cropped = upscaled.crop((offset, offset, upscaled.width, upscaled.height))
+
+ pitch, _histogram_phase = detect_pixel_grid(cropped)
+ measured = _best_phase(cropped.convert("RGBA"), pitch)
+ snapped = grid_snap_downscale(cropped, pitch, phase=measured)
+
+ # 논리 격자 칸 수는 잘린 첫 칸까지 세어 원본과 같아야 한다 — 한 칸이라도 잃으면
+ # 그 행/열의 디테일(눈 같은 2x4 덩어리)이 이웃 칸에 병합된 것이다.
+ # (offset 11 에서 히스토그램 위상은 23x39 로 한 칸을 잃는다.)
+ assert snapped.size == art.size, f"offset {offset}: {snapped.size} != {art.size}"
+ if offset == 3:
+ # 크기만으로는 offset 3 을 못 가른다(양쪽 다 24x40). 픽셀로 가른다 —
+ # 실측 위상 0 vs 히스토그램 위상 377 이 판별선이다.
+ assert _mismatch(snapped, art) == 0, (
+ f"offset {offset}: 실측 위상인데 픽셀이 어긋난다 ({_mismatch(snapped, art)})")
+
+
[email protected]("scale", [12.0, 14.35, 16.0, 17.24, 20.0])
+def test_measured_phase_roundtrips_like_the_detected_phase(scale):
+ """스냅 경로가 쓰는 위상(`_best_phase`)도 원본 논리 픽셀을 되돌려야 한다.
+
+ 회귀 (maintainer 2026-07-25, synthetic_fixture_b down_jump frame-0): 엣지 히스토그램이 낸
+ 위상이 참 위상에서 pitch/2 만큼 밀려(13.00 에서 2.02 vs 8.12) 눈 4행이 3행으로
+ 병합됐다. `refine_edges_to_boundaries` 는 ±pitch/3 안에서만 절단선을 당기므로
+ 그 크기의 위상 오차는 복구되지 않는다. 그래서 스냅 루프는 위상을 실측
+ (`_best_phase`, 셀 균일도)으로 다시 고른다 — 이 테스트는 그 경로가 기존
+ 라운드트립 보장을 깨지 않음을 고정한다.
+ """
+ art = _logical_art()
+ upscaled = _upscaled(art, scale)
+ pitch, _ = detect_pixel_grid(upscaled)
+ phase = _best_phase(upscaled.convert("RGBA"), pitch)
+ snapped = grid_snap_downscale(upscaled, pitch, phase=phase)
+
+ assert snapped.size == art.size, f"scale {scale}: {snapped.size} != {art.size}"
+ assert _mismatch(snapped, art) <= art.width * art.height // 100
diff --git a/tests/frames/test_pitch_runlen_crosscheck.py b/tests/frames/test_pitch_runlen_crosscheck.py
new file mode 100644
index 0000000..4213a60
--- /dev/null
+++ b/tests/frames/test_pitch_runlen_crosscheck.py
@@ -0,0 +1,184 @@
+# SPDX-License-Identifier: Apache-2.0
+"""동일색 런 최빈값 피치 추정기(perfectpixel unfake 이식)와 교차검증 경고를 고정한다.
+
+detect_pixel_grid 는 정수 씨앗 ±0.75 창 안에서만 소수 피치를 정밀화하므로, 씨앗
+로터리가 실패하면 참 피치가 창 밖에 놓여 조용히 틀린다 — 회귀 두 모드:
+
+- y축 붕괴: 주인공 컴포넌트에서 y 피치가 x 값(29.52)으로 붕괴 (실측 30.56).
+- 약수 오검출: 축별 소수 피치(29.5/30.6) 그림에서 두 축 모두 참값의 절반으로.
+
+런 길이는 경계 히스토그램과 독립인 신호(경계 위치가 아니라 경계 사이 거리)라
+세컨드 오피니언이 된다. 교차검증은 경고 전용 — 스냅 결과에 영향 0 을 여기서
+비트 단위로 고정한다 (자동 교체 금지, No Silent Fallback).
+"""
+import json
+import random
+
+from PIL import Image
+
+import sprite_gen.frames.extract as extract_module
+from sprite_gen.frames.extract import (
+ crosscheck_pitch_runlen,
+ detect_pixel_grid,
+ estimate_pixel_grid_runlen,
+)
+from test_pitch_ground_truth import PALETTE, _logical_art
+
+MAGENTA = (255, 0, 255)
+
+
+def _upscale_axes(art: Image.Image, scale_x: float, scale_y: float) -> Image.Image:
+ """축별 소수 배율 업스케일 — 비균등 리스케일된 AI 도트를 흉내낸다."""
+ big = art.resize((art.width * 64, art.height * 64), Image.NEAREST)
+ return big.resize((round(art.width * scale_x), round(art.height * scale_y)), Image.NEAREST)
+
+
+def test_runlen_integer_pitch_is_exact():
+ art = _logical_art(24, 40)
+ for k in (8, 12, 16, 24):
+ upscaled = art.resize((art.width * k, art.height * k), Image.NEAREST)
+ estimate = estimate_pixel_grid_runlen(upscaled)
+ assert abs(estimate[0] - k) < 0.01, f"k={k}: x={estimate[0]:.3f}"
+ assert abs(estimate[1] - k) < 0.01, f"k={k}: y={estimate[1]:.3f}"
+
+
+def test_runlen_recovers_fractional_per_axis_pitch():
+ """소수 피치는 floor/ceil 런이 섞여 나오고, 그 가중 무게중심이 참값을 복원한다."""
+ upscaled = _upscale_axes(_logical_art(24, 44), 29.5, 30.6)
+ estimate = estimate_pixel_grid_runlen(upscaled)
+ assert abs(estimate[0] - 29.5) < 0.2, f"x={estimate[0]:.3f}"
+ assert abs(estimate[1] - 30.6) < 0.2, f"y={estimate[1]:.3f}"
+
+
+def test_runlen_noise_is_inconclusive():
+ """격자 없는 입력은 (1.0, 1.0) — 관측 가능하게 포기한다."""
+ rng = random.Random(3)
+ noise = Image.new("RGB", (200, 200))
+ pixels = noise.load()
+ for y in range(200):
+ for x in range(200):
+ pixels[x, y] = (rng.randrange(256), rng.randrange(256), rng.randrange(256))
+ assert estimate_pixel_grid_runlen(noise) == (1.0, 1.0)
+
+
+def test_runlen_small_image_is_inconclusive():
+ art = _logical_art(24, 24).resize((24, 24), Image.NEAREST)
+ assert estimate_pixel_grid_runlen(art) == (1.0, 1.0)
+
+
+def test_crosscheck_quiet_when_estimators_agree():
+ """detect 가 맞게 잡는 크기(블록 수 적음)에서는 경고 0 — 오경보 없음."""
+ upscaled = _upscale_axes(_logical_art(18, 30), 29.5, 30.6)
+ grid, _ = detect_pixel_grid(upscaled)
+ assert abs(grid[0] - 29.5) < 0.4 and abs(grid[1] - 30.6) < 0.4, "전제: 검출 정상"
+ assert crosscheck_pitch_runlen(grid, estimate_pixel_grid_runlen(upscaled)) == []
+
+
+def test_crosscheck_quiet_on_integer_scales():
+ art = _logical_art(24, 40)
+ for k in (8, 12, 16, 24):
+ upscaled = art.resize((art.width * k, art.height * k), Image.NEAREST)
+ grid, _ = detect_pixel_grid(upscaled)
+ notes = crosscheck_pitch_runlen(grid, estimate_pixel_grid_runlen(upscaled))
+ assert notes == [], f"k={k}: {notes}"
+
+
+def test_crosscheck_skips_unconfident_estimates():
+ assert crosscheck_pitch_runlen((1.0, 1.0), (30.0, 30.0)) == []
+ assert crosscheck_pitch_runlen((30.0, 30.0), (1.0, 1.0)) == []
+ assert crosscheck_pitch_runlen((30.0, 31.0), (29.2, 30.4)) == []
+
+
+def test_crosscheck_flags_divisor_misdetection():
+ """약수 오검출 재현: 축별 소수 피치 29.5/30.6 에서 detect 가 두 축 다 절반으로.
+
+ 블록 수가 많아지면 어떤 정수 씨앗도 참 소수 피치의 ±0.75 창을 못 덮고, 정밀화가
+ 씨앗의 /2 약수 창에서 최대점을 찾는다. detect_pixel_grid 가 나중에 고쳐져 참값을
+ 잡게 되면 이 전제 assert 가 먼저 깨진다 — 그때는 픽스처를 더 어렵게 갱신할 것.
+ """
+ upscaled = _upscale_axes(_logical_art(20, 36, seed=11), 29.5, 30.6)
+ grid, _ = detect_pixel_grid(upscaled)
+ assert grid[0] < 20.0 and grid[1] < 20.0, f"전제: 약수 오검출 재현 (grid={grid})"
+
+ runlen = estimate_pixel_grid_runlen(upscaled)
+ assert abs(runlen[0] - 29.5) < 0.2 and abs(runlen[1] - 30.6) < 0.2
+
+ notes = crosscheck_pitch_runlen(grid, runlen)
+ divisor_notes = [note for note in notes if "divisor" in note]
+ assert len(divisor_notes) == 2, notes
+ assert any("x=" in note for note in divisor_notes)
+ assert any("y=" in note for note in divisor_notes)
+
+
+def test_crosscheck_flags_y_axis_collapse():
+ """y축 붕괴 재현: x 는 정수 피치(29)라 씨앗이 잡지만, y 는 소수(30.3)+세로로 길어
+ 정수 씨앗이 전멸 → y 정밀화가 combined 씨앗(=x 값) 창에 갇혀 x 로 붕괴한다.
+ 회귀(주인공, y 29.52 vs 실측 30.56)와 같은 메커니즘.
+
+ 축차 3~4% 는 축별 규칙 임계 밑이라, AA 공통 바이어스가 상쇄되는 축비(y/x)
+ 규칙이 잡는다.
+ """
+ upscaled = _upscale_axes(_logical_art(28, 60, seed=5), 29.0, 30.3)
+ grid, _ = detect_pixel_grid(upscaled)
+ assert abs(grid[0] - 29.0) < 0.6, f"전제: x 정상 검출 (grid={grid})"
+ assert abs(grid[1] - grid[0]) < 1.0 and abs(grid[1] - 30.3) > 0.4, (
+ f"전제: y 가 x 로 붕괴 (grid={grid})"
+ )
+
+ runlen = estimate_pixel_grid_runlen(upscaled)
+ assert abs(runlen[1] - 30.3) < 0.2, f"runlen y={runlen[1]:.3f}"
+
+ notes = crosscheck_pitch_runlen(grid, runlen)
+ assert any("axis ratio" in note for note in notes), notes
+
+
+def _build_pixel_perfect_run(root):
+ """crosscheck 가 발화하는 픽셀퍼펙트 런 디렉토리 (약수 오검출 픽스처 2프레임)."""
+ run_dir = root / "run"
+ (run_dir / "raw").mkdir(parents=True)
+ frame = _upscale_axes(_logical_art(20, 36, seed=11), 29.5, 30.6)
+ gap = 40
+ strip = Image.new("RGB", (frame.width * 2 + gap * 3, frame.height + gap * 2), MAGENTA)
+ strip.paste(frame, (gap, gap))
+ strip.paste(frame, (frame.width + gap * 2, gap))
+ strip.save(run_dir / "raw" / "walk.png")
+ request = {
+ "version": 1,
+ "kind": "sprite-gen-request",
+ "engine": "component-row",
+ "character": {"id": "crosscheckbot", "description": "runlen crosscheck fixture", "base_image": None},
+ "cell": {"shape": "square", "width": 96, "height": 96, "safe_margin_x": 8, "safe_margin_y": 8, "size": 96, "safe_margin": 8},
+ "chroma_key": {"name": "magenta", "hex": "#FF00FF", "rgb": [255, 0, 255], "selection": "fallback"},
+ "states": {"walk": {"frames": 2, "fps": 8, "loop": True, "action": "synthetic crosscheck fixture"}},
+ "fit": {"pixel_unfake": True, "logical_height": 36},
+ }
+ (run_dir / "sprite-request.json").write_text(json.dumps(request, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
+ return run_dir
+
+
+def test_pipeline_reports_crosscheck_warning_without_touching_snap(tmp_path, monkeypatch, capsys):
+ """통합 계약 두 가지를 한 픽스처로 고정한다.
+
+ 1. 오검출 런에서 crosscheck 경고가 report warnings 와 stderr 양쪽에 표면화된다.
+ 2. 경고 전용 — runlen 추정기를 중화(항상 확신 없음)해도 프레임이 비트 동일하다.
+ 스냅은 언제나 detect_pixel_grid 합의만 쓴다는 증명.
+ """
+ run_a = _build_pixel_perfect_run(tmp_path / "a")
+ assert extract_module.run(run_dir=run_a) == 0
+ captured = capsys.readouterr()
+ manifest_a = json.loads((run_a / "frames" / "frames-manifest.json").read_text(encoding="utf-8"))
+ crosscheck_a = [w for w in manifest_a["warnings"] if "pitch crosscheck" in w]
+ assert crosscheck_a, manifest_a["warnings"]
+ assert "[pitch-crosscheck]" in captured.err
+
+ monkeypatch.setattr(extract_module, "estimate_pixel_grid_runlen", lambda *args, **kwargs: (1.0, 1.0))
+ run_b = _build_pixel_perfect_run(tmp_path / "b")
+ assert extract_module.run(run_dir=run_b) == 0
+ manifest_b = json.loads((run_b / "frames" / "frames-manifest.json").read_text(encoding="utf-8"))
+ assert [w for w in manifest_b["warnings"] if "pitch crosscheck" in w] == []
+
+ frames_a = sorted((run_a / "frames").rglob("*.png"))
+ frames_b = sorted((run_b / "frames").rglob("*.png"))
+ assert frames_a and [f.relative_to(run_a) for f in frames_a] == [f.relative_to(run_b) for f in frames_b]
+ for file_a, file_b in zip(frames_a, frames_b):
+ assert file_a.read_bytes() == file_b.read_bytes(), f"{file_a.name} differs — crosscheck touched the snap"
diff --git a/tests/frames/test_posix_manifest_paths.py b/tests/frames/test_posix_manifest_paths.py
new file mode 100644
index 0000000..f2b26c5
--- /dev/null
+++ b/tests/frames/test_posix_manifest_paths.py
@@ -0,0 +1,23 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Regression tests for OS-neutral paths in machine-readable manifests."""
+
+from pathlib import Path, PureWindowsPath
+
+from sprite_gen.spec.runio import relative_posix
+
+
+def test_relative_posix_reproduces_windows_backslash_bug_without_windows() -> None:
+ # PureWindowsPath is a pure stdlib path flavor: it performs Windows path
+ # parsing on any host without touching the OS, so macOS can reproduce this.
+ root = PureWindowsPath("C:/sprite/run")
+ frame = root / "frames" / "walk" / "frame-0.png"
+
+ assert str(frame.relative_to(root)) == r"frames\walk\frame-0.png"
+ assert relative_posix(frame, root) == "frames/walk/frame-0.png"
+
+
+def test_relative_posix_is_noop_for_posix_paths() -> None:
+ root = Path("/sprite/run")
+ frame = root / "frames" / "walk" / "frame-0.png"
+
+ assert relative_posix(frame, root) == str(frame.relative_to(root))
diff --git a/tests/frames/test_segment_projection.py b/tests/frames/test_segment_projection.py
new file mode 100644
index 0000000..4ddfbac
--- /dev/null
+++ b/tests/frames/test_segment_projection.py
@@ -0,0 +1,201 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Projection-profile + DP segmentation (sprite_gen/frames/segment.py) tests.
+
+The fused fixture (tests/fixtures/run-fused/) draws three poses whose arms
+touch the neighbouring pose: connected-component extraction sees ONE blob and
+must fail, while the opt-in projection segmentation (fit.segmentation:
+"projection" or --segmentation projection) must recover exactly the expected
+frame count. The recorded golden manifest pins the split bit-for-bit, and the
+existing separated golden run must stay bit-identical even with projection
+enabled (the gutter rebuild is behaviour-preserving).
+"""
+
+from __future__ import annotations
+
+import json
+import shutil
+from pathlib import Path
+
+import pytest
+from PIL import Image
+
+from conftest import FIXTURE_RUN, run_script
+from sprite_gen.frames.segment import (
+ dp_n_cut,
+ segment_boundaries,
+ segment_strip,
+ separate_fused_poses,
+)
+
+FIXTURES = Path(__file__).resolve().parent.parent / "fixtures"
+FUSED_RUN = FIXTURES / "run-fused"
+
+EXPECTED_FUSED = json.loads(
+ (FIXTURES / "expected-fused-frames-manifest.json").read_text(encoding="utf-8")
+)
+EXPECTED_SEPARATED = json.loads(
+ (FIXTURES / "expected-frames-manifest.json").read_text(encoding="utf-8")
+)
+
+
+def fused_run_dir(tmp_path: Path) -> Path:
+ """A throwaway copy of the fused-pose fixture run dir."""
+ run_dir = tmp_path / "run-fused"
+ shutil.copytree(FUSED_RUN, run_dir)
+ return run_dir
+
+
+def _set_segmentation(run_dir: Path, mode: str | None) -> None:
+ request_path = run_dir / "sprite-request.json"
+ request = json.loads(request_path.read_text(encoding="utf-8"))
+ fit = dict(request.get("fit") or {})
+ if mode is None:
+ fit.pop("segmentation", None)
+ else:
+ fit["segmentation"] = mode
+ request["fit"] = fit
+ request_path.write_text(json.dumps(request, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
+
+
+# --- integration: extract CLI on the fused fixture --------------------------
+
+
+def test_fused_extraction_matches_golden_manifest(fused_run_dir: Path) -> None:
+ result = run_script("extract_sprite_row_frames.py", "--run-dir", str(fused_run_dir))
+ assert result.returncode == 0, result.stdout + result.stderr
+
+ manifest = json.loads((fused_run_dir / "frames" / "frames-manifest.json").read_text(encoding="utf-8"))
+ manifest.pop("run_dir")
+ # 엔진 소스 해시/기록 플래그는 휘발성 스탬프 — 골든 비교 대상이 아니다
+ manifest.pop("engine_revision", None)
+ manifest.pop("extract_args", None)
+ for _row in manifest.get("rows", []):
+ _row.pop("engine_revision", None)
+ assert manifest == EXPECTED_FUSED
+ assert "[segment] kick: projection split at columns" in result.stderr
+
+
+def test_fused_strip_fails_without_opt_in(fused_run_dir: Path) -> None:
+ # Default segmentation is components: the fused strip is one blob and the
+ # run must fail loudly (this is the failure mode the port addresses).
+ _set_segmentation(fused_run_dir, None)
+ result = run_script("extract_sprite_row_frames.py", "--run-dir", str(fused_run_dir))
+ assert result.returncode == 1
+ # Strict whole-generation atomicity: a failed FIRST extract publishes no partial generation
+ # to canonical frames/ — the per-state failure signal is written OUTSIDE frames/ as
+ # extract-failure.json (still observable, still consumed by the correction loop).
+ assert not (fused_run_dir / "frames").exists()
+ failure = json.loads((fused_run_dir / "extract-failure.json").read_text(encoding="utf-8"))
+ assert failure["ok"] is False
+ assert any("could not extract 3 sprite components" in error for error in failure["errors"])
+
+
+def test_cli_flag_enables_projection_without_request_opt_in(fused_run_dir: Path) -> None:
+ _set_segmentation(fused_run_dir, None)
+ result = run_script(
+ "extract_sprite_row_frames.py",
+ "--run-dir", str(fused_run_dir),
+ "--segmentation", "projection",
+ )
+ assert result.returncode == 0, result.stdout + result.stderr
+ manifest = json.loads((fused_run_dir / "frames" / "frames-manifest.json").read_text(encoding="utf-8"))
+ manifest.pop("run_dir")
+ # 엔진 소스 해시/기록 플래그는 휘발성 스탬프 — 골든 비교 대상이 아니다
+ manifest.pop("engine_revision", None)
+ manifest.pop("extract_args", None)
+ for _row in manifest.get("rows", []):
+ _row.pop("engine_revision", None)
+ assert manifest == EXPECTED_FUSED
+
+
+def test_cli_flag_components_overrides_request_projection(fused_run_dir: Path) -> None:
+ # Explicit CLI mode wins over the request opt-in (observable off switch).
+ result = run_script(
+ "extract_sprite_row_frames.py",
+ "--run-dir", str(fused_run_dir),
+ "--segmentation", "components",
+ )
+ assert result.returncode == 1
+ # Failed first extract: no partial frames/ published; failure signal in extract-failure.json.
+ assert not (fused_run_dir / "frames").exists()
+ failure = json.loads((fused_run_dir / "extract-failure.json").read_text(encoding="utf-8"))
+ assert any("could not extract 3 sprite components" in error for error in failure["errors"])
+
+
+def test_projection_is_bit_identical_on_separated_golden_run(tmp_path: Path) -> None:
+ # The gutter rebuild must be behaviour-preserving when poses are already
+ # separated: the separated golden run with projection enabled must produce
+ # the exact same manifest as the recorded components golden.
+ run_dir = tmp_path / "run"
+ shutil.copytree(FIXTURE_RUN, run_dir)
+ result = run_script(
+ "extract_sprite_row_frames.py",
+ "--run-dir", str(run_dir),
+ "--segmentation", "projection",
+ )
+ assert result.returncode == 0, result.stdout + result.stderr
+ manifest = json.loads((run_dir / "frames" / "frames-manifest.json").read_text(encoding="utf-8"))
+ manifest.pop("run_dir")
+ # 엔진 소스 해시/기록 플래그는 휘발성 스탬프 — 골든 비교 대상이 아니다
+ manifest.pop("engine_revision", None)
+ manifest.pop("extract_args", None)
+ for _row in manifest.get("rows", []):
+ _row.pop("engine_revision", None)
+ assert manifest == EXPECTED_SEPARATED
+
+
+# --- unit: pure segmentation functions ---------------------------------------
+
+
+def _bars_strip(spans: list[tuple[int, int]], width: int = 300, height: int = 40) -> Image.Image:
+ image = Image.new("RGBA", (width, height), (0, 0, 0, 0))
+ for start, end in spans:
+ for x in range(start, end):
+ for y in range(height):
+ image.putpixel((x, y), (90, 90, 90, 255))
+ return image
+
+
+def test_segment_strip_counts_natural_poses_from_gutters() -> None:
+ image = _bars_strip([(20, 60), (130, 170), (240, 280)])
+ segments, natural = segment_strip(image, 3)
+ assert natural == 3
+ assert len(segments) == 3
+ boundaries, _ = segment_boundaries(image, 3)
+ assert boundaries is not None
+ assert 60 <= boundaries[0] <= 130
+ assert 170 <= boundaries[1] <= 240
+
+
+def test_segment_boundaries_reports_failure_for_empty_strip() -> None:
+ image = Image.new("RGBA", (200, 40), (0, 0, 0, 0))
+ boundaries, natural = segment_boundaries(image, 3)
+ assert boundaries is None
+ assert natural == 0
+
+
+def test_dp_n_cut_prefers_low_mass_columns() -> None:
+ profile = [10.0] * 100
+ for x in range(30, 36):
+ profile[x] = 1.0
+ for x in range(60, 66):
+ profile[x] = 1.0
+ cuts = dp_n_cut(profile, 0, 100, 3)
+ assert cuts is not None and len(cuts) == 2
+ assert 28 <= cuts[0] <= 38
+ assert 58 <= cuts[1] <= 68
+
+
+def test_separate_fused_poses_is_off_by_default() -> None:
+ image = _bars_strip([(20, 60), (130, 170)])
+ assert separate_fused_poses(image, 2) is image
+ assert separate_fused_poses(image, 2, {"segmentation": "components"}) is image
+
+
+def test_separate_fused_poses_leaves_strip_untouched_on_failure(capsys: pytest.CaptureFixture) -> None:
+ # An empty strip cannot be segmented: the hook must report and return the
+ # strip unchanged so the downstream extraction fails observably.
+ image = Image.new("RGBA", (200, 40), (0, 0, 0, 0))
+ assert separate_fused_poses(image, 3, {"segmentation": "projection"}, None, "empty") is image
+ assert "projection segmentation found 0 pose(s)" in capsys.readouterr().err
diff --git a/tests/frames/test_slice_sheet.py b/tests/frames/test_slice_sheet.py
new file mode 100644
index 0000000..87dc5ae
--- /dev/null
+++ b/tests/frames/test_slice_sheet.py
@@ -0,0 +1,130 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Cell geometry checks for sprite_gen.frames.slice_sheet on a synthetic sheet."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from PIL import Image
+
+from sprite_gen.frames.slice_sheet import parse_chroma_key, slice_sheet
+
+MAGENTA = (255, 0, 255)
+GRID = (3, 2)
+SHEET_SIZE = (300, 200) # 100x100 cells
+CANVAS = (128, 192)
+BASELINE = 180.0
+TARGET = 120.0
+
+
+def _synthetic_sheet() -> Image.Image:
+ """3x2 grid of solid figures at deliberately different sizes, plus:
+ - a detached in-cell effect square (cell 1) that must survive,
+ - a neighbour overhang: cell 0's figure grows a thin arm crossing into
+ cell 1 (fuses the two figures sheet-wide) that must NOT stay in cell 1.
+ """
+ sheet = Image.new("RGB", SHEET_SIZE, MAGENTA)
+ px = sheet.load()
+
+ def rect(x0: int, y0: int, x1: int, y1: int, color=(40, 60, 90)) -> None:
+ for y in range(y0, y1):
+ for x in range(x0, x1):
+ px[x, y] = color
+
+ # cell 0: tall figure (feet at y=90), with an arm crossing into cell 1
+ rect(30, 20, 70, 90)
+ rect(70, 40, 112, 44) # arm overhang into cell 1 (x>=100)
+ # cell 1: shorter figure + detached effect square well inside the cell
+ rect(130, 40, 170, 90)
+ rect(175, 22, 183, 30, color=(200, 40, 40)) # effect
+ # cell 2: medium figure
+ rect(230, 30, 270, 90)
+ # bottom row figures
+ rect(30, 130, 70, 190)
+ rect(130, 120, 170, 190)
+ rect(230, 140, 270, 190)
+ return sheet
+
+
+def _subject_rows(image: Image.Image) -> tuple[int, int]:
+ alpha = image.getchannel("A")
+ bbox = alpha.getbbox()
+ assert bbox is not None
+ return bbox[1], bbox[3]
+
+
+def test_slice_sheet_normalizes_height_and_baseline(tmp_path: Path) -> None:
+ sheet_path = tmp_path / "sheet.png"
+ _synthetic_sheet().save(sheet_path)
+ written = slice_sheet(
+ sheet_path,
+ tmp_path / "out",
+ parse_chroma_key("magenta"),
+ grid=GRID,
+ canvas=CANVAS,
+ baseline_y=BASELINE,
+ target_height=TARGET,
+ noise_min=10,
+ )
+ assert len(written) == GRID[0] * GRID[1]
+ for path in written:
+ image = Image.open(path)
+ assert image.size == CANVAS
+ top, bottom = _subject_rows(image)
+ assert bottom == round(BASELINE), path.name
+ if path.stem != "cell-1": # cell 1 carries an effect above the head
+ assert (bottom - top) == round(TARGET), path.name
+
+
+def test_slice_sheet_drops_neighbour_overhang_keeps_effect(tmp_path: Path) -> None:
+ sheet_path = tmp_path / "sheet.png"
+ _synthetic_sheet().save(sheet_path)
+ written = slice_sheet(
+ sheet_path,
+ tmp_path / "out",
+ parse_chroma_key("magenta"),
+ grid=GRID,
+ canvas=CANVAS,
+ baseline_y=BASELINE,
+ target_height=TARGET,
+ noise_min=10,
+ )
+ cell1 = Image.open(next(p for p in written if p.stem == "cell-1"))
+ pixels = cell1.load()
+ reds = greys = 0
+ for y in range(cell1.size[1]):
+ for x in range(cell1.size[0]):
+ r, g, b, a = pixels[x, y]
+ if a == 0:
+ continue
+ if r > 150 and g < 90:
+ reds += 1
+ if r < 90 and b > 60:
+ greys += 1
+ assert reds > 0, "detached in-cell effect must survive"
+ # 오버행 팔은 셀 좌측 경계에 붙은 얇은 조각으로 들어오므로, 본체+이펙트 외의
+ # 좌측 경계 접촉 픽셀이 남아 있으면 실패다: 경계 3px 안 불투명 픽셀 검사
+ left_edge = sum(1 for y in range(cell1.size[1]) for x in range(0, 3) if pixels[x, y][3] > 0)
+ assert left_edge == 0, "neighbour overhang must be dropped"
+
+
+def test_slice_sheet_no_chroma_residue(tmp_path: Path) -> None:
+ sheet_path = tmp_path / "sheet.png"
+ _synthetic_sheet().save(sheet_path)
+ written = slice_sheet(
+ sheet_path,
+ tmp_path / "out",
+ parse_chroma_key("magenta"),
+ grid=GRID,
+ canvas=CANVAS,
+ baseline_y=BASELINE,
+ target_height=TARGET,
+ noise_min=10,
+ )
+ for path in written:
+ pixels = Image.open(path).load()
+ image = Image.open(path)
+ for y in range(image.size[1]):
+ for x in range(image.size[0]):
+ r, g, b, a = pixels[x, y]
+ assert not (a > 60 and r > 150 and b > 150 and g < 100), f"{path.name} keeps magenta"
diff --git a/tests/frames/test_sliver_guard.py b/tests/frames/test_sliver_guard.py
new file mode 100644
index 0000000..4245866
--- /dev/null
+++ b/tests/frames/test_sliver_guard.py
@@ -0,0 +1,77 @@
+# SPDX-License-Identifier: Apache-2.0
+"""경계 스냅 슬리버 가드 계약 (plan sprite-gen/backbone-sliver-guard).
+
+회귀 (maintainer 2026-07-24, v8 down_jump): 경계 스냅의 최소 간격이 절대 2px 라
+피치 ~13px 소재에서 0.15셀짜리 슬리버 절단 쌍(0.4/1.6)을 허용했고, 인접 절단
+둘이 같은 색경계로 끌려가면 출력 두 행이 소스의 거의 같은 밴드를 이중
+샘플링했다 — f2 턱 늘어남(턱 라인 세로 복제)과 f0 눈물점(50/50 걸침 셀 지배색
+플립)이 한 기전이다. 실측: 가드 후 v8 down 11행 내부 진성 슬리버 45 → 0,
+엔진 출력만으로 f0 눈 대칭 복원(사이드카 보정 불필요), f1 변경 0px (외과적).
+
+계약: 스냅이 만든 절단 간격은 내부에서 피치의 0.6배 미만이 될 수 없다.
+"""
+from __future__ import annotations
+
+from PIL import Image
+
+from sprite_gen.frames.extract import refine_edges_to_boundaries
+
+
+def _double_boundary_image(width: int = 130, height: int = 40) -> Image.Image:
+ """인접 격자선 둘을 서로 향해 당기는 색경계 쌍 픽스처 — 실제 슬리버 기하.
+
+ v8 회귀의 기전: 슬리버는 두 절단선이 "한 점"에 모여서가 아니라, ~5px
+ 간격의 경계 쌍이 각자의 창(±pitch/3=±4) 안에서 **서로를 향해** 절단선을
+ 당겨 태어난다. 격자선 52·65 사이에 경계를 56(55→56)과 61(60→61)에 두면:
+ 가드 전 = 절단선이 56·61 로 끌려가 내부 간격 5px(0.38셀) 슬리버,
+ 가드 후 = 두 번째 절단선이 하한(min_gap=8) 밖으로 못 들어와 슬리버 불가.
+ """
+ im = Image.new("RGBA", (width, height), (200, 60, 60, 255))
+ px = im.load()
+ for y in range(height):
+ for x in range(56, 61):
+ px[x, y] = (30, 30, 30, 255) # 경계 1: 55→56 전이
+ for x in range(61, width):
+ px[x, y] = (60, 120, 200, 255) # 경계 2: 60→61 전이 (5px 옆)
+ return im
+
+
+def test_interior_gaps_never_fall_below_guard_floor():
+ im = _double_boundary_image()
+ pitch = 13.0
+ lattice = list(range(0, im.width + 1, int(pitch)))
+ xs, ys = refine_edges_to_boundaries(im, lattice, [0, 13, 26, im.height], (pitch, pitch))
+ gaps = [b - a for a, b in zip(xs, xs[1:])]
+ interior = gaps[1:-1]
+ floor = round(pitch * 0.6)
+ assert interior and min(interior) >= floor, (
+ f"내부 절단 간격 {min(interior)}px < 가드 하한 {floor}px — 슬리버 쌍 부활 "
+ f"(gaps={gaps}). 턱 늘어남/눈물점 클래스가 돌아온다"
+ )
+
+
+def test_snap_still_follows_boundaries_within_the_guard():
+ """가드는 스냅을 죽이지 않는다 — 창 안 오프-격자 경계 추종은 유지된다."""
+ im = Image.new("RGBA", (130, 40), (200, 60, 60, 255))
+ px = im.load()
+ for y in range(40):
+ for x in range(50, 130): # 경계가 격자선(52)에서 2px 벗어난 x=50 에 하나만
+ px[x, y] = (60, 120, 200, 255)
+ pitch = 13.0
+ lattice = list(range(0, im.width + 1, int(pitch)))
+ xs, _ = refine_edges_to_boundaries(im, lattice, [0, 13, 26, im.height], (pitch, pitch))
+ assert 50 in xs, f"오프-격자 경계(50)로 스냅하지 않았다: {xs} — 경계 조각이 옆 칸으로 샌다"
+
+
+def test_low_pitch_material_keeps_legacy_floor():
+ """피치 < 3.3 소재는 기존 절대 2px 하한 그대로다 (저해상 런 무회귀)."""
+ im = Image.new("RGBA", (30, 12), (200, 60, 60, 255))
+ px = im.load()
+ for y in range(12):
+ for x in range(15, 30):
+ px[x, y] = (60, 120, 200, 255)
+ pitch = 3.0
+ lattice = list(range(0, 31, 3))
+ xs, _ = refine_edges_to_boundaries(im, lattice, [0, 3, 6, 9, 12], (pitch, pitch))
+ gaps = [b - a for a, b in zip(xs, xs[1:])]
+ assert min(gaps[1:-1] or gaps) >= 2, f"저피치 하한(2px) 붕괴: {gaps}"
diff --git a/tests/frames/test_takes_heal.py b/tests/frames/test_takes_heal.py
new file mode 100644
index 0000000..cf9390b
--- /dev/null
+++ b/tests/frames/test_takes_heal.py
@@ -0,0 +1,266 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Takes 1급 계약 + 파생 캐시 자가치유(heal_run).
+
+- 한 상태의 프레임 풀 = primary raw + 선언된 테이크들(`states.<s>.takes`),
+ 각 스트립은 독립 스냅(스트립별 합의 피치), 행 정합·배치는 함께.
+- frames/ 는 (raw + request + 엔진)의 파생 캐시 — 행의 engine_revision 이 현재
+ 엔진과 다르면 heal_run 이 raw 에서 자동 재유도한다. 뷰에 '재추출' 개념이
+ 없는 실시간 계약(maintainer 확정 2026-07-14)의 엔진 반쪽이다.
+"""
+
+import json
+import random
+from pathlib import Path
+
+import pytest
+from PIL import Image
+
+import sprite_gen.frames.extract as extract_module
+from sprite_gen.spec.layout import take_raw_rel
+
+MAGENTA = (255, 0, 255)
+
+
+def _logical_art(width, height, seed):
+ rng = random.Random(seed)
+ art = Image.new("RGB", (width, height), MAGENTA)
+ for y in range(height):
+ for x in range(width):
+ if rng.random() < 0.55:
+ art.putpixel((x, y), (rng.randrange(30, 220), rng.randrange(30, 220), rng.randrange(30, 220)))
+ return art
+
+
+def _strip(frames, seed, pitch=8, logical=(20, 36), gap=40):
+ frame = _logical_art(*logical, seed=seed).resize(
+ (logical[0] * pitch, logical[1] * pitch), Image.Resampling.NEAREST)
+ strip = Image.new("RGB", (frame.width * frames + gap * (frames + 1), frame.height + gap * 2), MAGENTA)
+ for i in range(frames):
+ strip.paste(frame, (gap + i * (frame.width + gap), gap))
+ return strip
+
+
+def _build_run(root: Path, takes=None) -> Path:
+ run_dir = root / "run"
+ (run_dir / "raw").mkdir(parents=True)
+ _strip(2, seed=7).save(run_dir / "raw" / "walk.png")
+ request = {
+ "version": 1,
+ "kind": "sprite-gen-request",
+ "engine": "component-row",
+ "character": {"id": "takebot", "description": "takes fixture", "base_image": None},
+ "cell": {"shape": "square", "width": 96, "height": 96, "safe_margin_x": 8,
+ "safe_margin_y": 8, "size": 96, "safe_margin": 8},
+ "chroma_key": {"name": "magenta", "hex": "#FF00FF", "rgb": [255, 0, 255], "selection": "fallback"},
+ "states": {"walk": {"frames": 2, "fps": 8, "loop": True, "action": "takes fixture"}},
+ "fit": {"pixel_unfake": True, "logical_height": 48},
+ }
+ if takes is not None:
+ request["states"]["walk"]["takes"] = takes
+ (run_dir / "sprite-request.json").write_text(
+ json.dumps(request, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
+ return run_dir
+
+
+def _manifest(run_dir: Path) -> dict:
+ return json.loads((run_dir / "frames" / "frames-manifest.json").read_text(encoding="utf-8"))
+
+
+def test_takes_extend_row_pool(tmp_path: Path) -> None:
+ takes = [{"label": "alt", "frames": 2}]
+ run_dir = _build_run(tmp_path, takes=takes)
+ request = json.loads((run_dir / "sprite-request.json").read_text(encoding="utf-8"))
+ take_path = run_dir / take_raw_rel(request, "walk", "alt")
+ take_path.parent.mkdir(parents=True)
+ _strip(2, seed=11).save(take_path)
+
+ assert extract_module.run(run_dir=run_dir) == 0
+ row = _manifest(run_dir)["rows"][0]
+ assert row["frames"] == 4
+ assert len(row["files"]) == 4
+ assert row["labels"] == ["", "", "alt#0", "alt#1"]
+ assert row["takes"] == [
+ {"label": None, "start": 0, "frames": 2, "raw": "raw/walk.png"},
+ {"label": "alt", "start": 2, "frames": 2, "raw": "raw/walk.takes/alt.png"},
+ ]
+ for rel in row["files"]:
+ assert (run_dir / rel).is_file(), rel
+ # 테이크 프레임은 다른 생성물이다 — primary 프레임과 내용이 달라야 한다
+ primary = Image.open(run_dir / row["files"][0]).tobytes()
+ alt = Image.open(run_dir / row["files"][2]).tobytes()
+ assert primary != alt
+
+
+def test_take_raw_missing_fails_loud(tmp_path: Path) -> None:
+ run_dir = _build_run(tmp_path, takes=[{"label": "alt", "frames": 2}])
+ assert extract_module.run(run_dir=run_dir) == 1 # 선언된 테이크 누락 = 행 실패 (부분 풀 게시 금지)
+ assert not (run_dir / "frames" / "frames-manifest.json").is_file()
+
+
+def test_takes_require_pixel_perfect(tmp_path: Path) -> None:
+ run_dir = _build_run(tmp_path, takes=[{"label": "alt", "frames": 2}])
+ request = json.loads((run_dir / "sprite-request.json").read_text(encoding="utf-8"))
+ del request["fit"]["pixel_unfake"]
+ (run_dir / "sprite-request.json").write_text(json.dumps(request), encoding="utf-8")
+ take_path = run_dir / take_raw_rel(request, "walk", "alt")
+ take_path.parent.mkdir(parents=True)
+ _strip(2, seed=11).save(take_path)
+ assert extract_module.run(run_dir=run_dir) == 1
+
+
+def test_heal_rederives_stale_rows(tmp_path: Path) -> None:
+ run_dir = _build_run(tmp_path)
+ assert extract_module.run(run_dir=run_dir) == 0
+ manifest_path = run_dir / "frames" / "frames-manifest.json"
+
+ # 현재 엔진으로 갓 구운 런은 이미 신선 — no-op
+ report = extract_module.heal_run(run_dir)
+ assert report["healed"] == [] and report["kept_stale"] == []
+
+ # 구엔진 스탬프 시뮬레이션 → heal 이 raw 에서 재유도하고 재스탬프
+ manifest = _manifest(run_dir)
+ manifest["rows"][0]["engine_revision"] = "0" * 12
+ manifest_path.write_text(json.dumps(manifest, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
+ report = extract_module.heal_run(run_dir)
+ assert report["healed"] == ["walk"]
+ assert _manifest(run_dir)["rows"][0]["engine_revision"] == extract_module.engine_revision()
+ assert (run_dir / "frames" / "walk" / "frame-1.png").is_file()
+
+
+def test_heal_keeps_stale_row_without_raw(tmp_path: Path) -> None:
+ run_dir = _build_run(tmp_path)
+ assert extract_module.run(run_dir=run_dir) == 0
+ manifest_path = run_dir / "frames" / "frames-manifest.json"
+ manifest = _manifest(run_dir)
+ manifest["rows"][0]["engine_revision"] = "0" * 12
+ manifest_path.write_text(json.dumps(manifest, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
+ frame_bytes = (run_dir / "frames" / "walk" / "frame-0.png").read_bytes()
+ (run_dir / "raw" / "walk.png").unlink()
+
+ report = extract_module.heal_run(run_dir)
+ assert report["healed"] == []
+ assert report["kept_stale"] == ["walk"]
+ assert report["notes"]
+ # 재료가 없으면 이전 세대를 바이트 그대로 보존한다
+ assert (run_dir / "frames" / "walk" / "frame-0.png").read_bytes() == frame_bytes
+
+
+def test_view_heals_and_downloads_live_state(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ """뷰/다운로드 계약: 스냅샷 요청이 stale 캐시를 자가치유하고, 버튼 3종은
+ 현재 라이브 상태를 계산해 zip 으로 내려준다 (게임 적용 의미 없음)."""
+ import io
+ import zipfile
+
+ run_dir = _build_run(tmp_path)
+ assert extract_module.run(run_dir=run_dir) == 0
+ manifest_path = run_dir / "frames" / "frames-manifest.json"
+ manifest = _manifest(run_dir)
+ manifest["rows"][0]["engine_revision"] = "0" * 12
+ manifest_path.write_text(json.dumps(manifest, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
+
+ import sprite_gen.serve.serve_curation as serve_curation
+
+ # 결정론: 그레이스를 넉넉히 주입해 느린 CI 러너(관측: Python 3.10)에서도 소규모
+ # heal 이 동기 경로로 완료됨을 안정 검증한다. 프로덕션 그레이스(1.5s)는 무변 —
+ # 벽시계 1.5s 에 의존하던 flaky 실패 제거 (validator 2026-07-21, heal 로직 무변).
+ monkeypatch.setattr(serve_curation, "_HEAL_GRACE_SECONDS", 60.0)
+ busy = serve_curation.maybe_heal(run_dir)
+ assert busy is False # 소규모 heal 은 그레이스 안에 끝나 동기 경로 유지
+ heal = serve_curation.take_heal_report() # 단일 소비자 (/api/run 역할)
+ assert heal is not None and heal["healed"] == ["walk"]
+ assert serve_curation.maybe_heal(run_dir) is False # 신선하면 no-op
+ assert serve_curation.take_heal_report() is None
+
+ built = serve_curation.build_download(run_dir, "atlas")
+ assert not isinstance(built, dict), built
+ data, filename = built
+ assert filename == "takebot-atlas.zip"
+ names = set(zipfile.ZipFile(io.BytesIO(data)).namelist())
+ assert names == {"sprite-sheet-alpha.png", "manifest.json"}
+
+ built = serve_curation.build_download(run_dir, "gifs")
+ assert not isinstance(built, dict), built
+ data, filename = built
+ assert filename == "takebot-gifs.zip"
+ assert any(n.endswith("walk.gif") for n in zipfile.ZipFile(io.BytesIO(data)).namelist())
+
+ # 줄 단위 단건 GIF — zip 이 아니라 GIF 원파일, 미지 상태는 fail loud
+ built = serve_curation.build_download(run_dir, "gif:walk")
+ assert not isinstance(built, dict), built
+ data, filename = built
+ assert filename == "takebot-walk.gif"
+ assert data[:6] in (b"GIF87a", b"GIF89a")
+ assert isinstance(serve_curation.build_download(run_dir, "gif:nope"), dict)
+
+
+def test_atlas_reuses_cells_for_identical_instances(tmp_path: Path) -> None:
+ """아틀라스 셀 재사용 (maintainer 승인 2026-07-16): 같은 (원본, 변형, 픽셀편집)의
+ 복제 인스턴스는 칸 하나를 공유한다 — 루프딜레이용 프레임 복제가 텍스처를
+ 늘리지 않는다. rect 는 재생 순서대로 반복되고, durations_ms 계약이 실린다."""
+ import sprite_gen.compose.compose_atlas as compose_module
+
+ run_dir = _build_run(tmp_path)
+ assert extract_module.run(run_dir=run_dir) == 0
+ # 프레임 0 을 두 번 복제(인스턴스 2, 3): 하나는 동일 굽기(재사용), 하나는 변형(별도 칸)
+ curation = {
+ "version": 1, "kind": "sprite-gen-curation",
+ "states": {"walk": {
+ "selected": [0, 1, 2, 3],
+ "clones": {"2": 0, "3": 0},
+ "transforms": {"3": {"rotate": 0, "scale": 1, "dx": 3, "dy": 0,
+ "shx": 0, "shy": 0, "flipX": 0}},
+ }},
+ }
+ from sprite_gen.curate.curation import stamp_curation
+ stamped = stamp_curation(run_dir, curation) # 세대 도장 없는 사이드카는 드롭된다 (정상 쓰기 경로)
+ (run_dir / "curation.json").write_text(json.dumps(stamped), encoding="utf-8")
+ assert compose_module.run(run_dir=run_dir, min_used_pixels=100) == 0
+
+ manifest = json.loads((run_dir / "manifest.json").read_text(encoding="utf-8"))
+ rects = manifest["frame_layout"]["rows"]["walk"]
+ assert len(rects) == 4
+ assert rects[2] == rects[0] # 동일 굽기 복제 = 같은 칸 재사용
+ assert rects[3] != rects[0] # 변형이 다르면 별도 칸
+ unique = {(r["x"], r["y"]) for r in rects}
+ assert len(unique) == 3
+ # 아틀라스 폭 = 고유 칸 수 (인스턴스 수 아님)
+ assert manifest["frame_layout"]["sheetWidth"] == 3 * manifest["frame_layout"]["cellWidth"]
+ anim = manifest["animation"]["rows"]["walk"]
+ assert anim["frames"] == 4
+ assert anim["durations_ms"] == [round(1000 / anim["fps"])] * 4
+
+
+def test_heal_isolates_failures_per_state(tmp_path: Path) -> None:
+ """상태별 격리 (2026-07-22): 한 행의 재추출 실패가 다른 행의 스왑을 막지도,
+ failed 보고에 연좌시키지도 않는다 (회귀 synthetic_fixture_a — 6행 실패가 33행
+ 전체를 "재계산 실패"로 묶었다)."""
+ run_dir = _build_run(tmp_path)
+ request = json.loads((run_dir / "sprite-request.json").read_text(encoding="utf-8"))
+ request["states"]["jump"] = {"frames": 2, "fps": 8, "loop": False, "action": "isolation fixture"}
+ (run_dir / "sprite-request.json").write_text(
+ json.dumps(request, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
+ _strip(2, seed=23).save(run_dir / "raw" / "jump.png")
+ assert extract_module.run(run_dir=run_dir) == 0
+
+ manifest_path = run_dir / "frames" / "frames-manifest.json"
+ manifest = _manifest(run_dir)
+ for row in manifest["rows"]:
+ row["engine_revision"] = "0" * 12
+ manifest_path.write_text(json.dumps(manifest, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
+ jump_bytes = (run_dir / "frames" / "jump" / "frame-0.png").read_bytes()
+ # jump 재료를 컴포넌트 없는 전면 크로마로 바꿔 재추출이 실패하게 만든다
+ Image.new("RGB", (400, 160), MAGENTA).save(run_dir / "raw" / "jump.png")
+
+ report = extract_module.heal_run(run_dir)
+ assert report["healed"] == ["walk"]
+ assert report["failed"] == ["jump"]
+ assert any("jump" in note for note in report["notes"])
+ rows = {row["state"]: row for row in _manifest(run_dir)["rows"]}
+ # 통과 행은 새 엔진으로 스왑, 실패 행은 이전 세대 바이트 그대로
+ assert rows["walk"]["engine_revision"] == extract_module.engine_revision()
+ assert rows["jump"]["engine_revision"] == "0" * 12
+ assert (run_dir / "frames" / "jump" / "frame-0.png").read_bytes() == jump_bytes
+ # durable evidence 는 실패 상태를 상태 단위로 유지한다 (재시도 차단 소재)
+ evidence = json.loads((run_dir / "extract-failure.json").read_text(encoding="utf-8"))
+ assert evidence["ok"] is False
+ assert any(str(error).startswith("jump:") for error in evidence["errors"])
diff --git a/tests/frames/test_taxonomy_layout.py b/tests/frames/test_taxonomy_layout.py
new file mode 100644
index 0000000..b48c464
--- /dev/null
+++ b/tests/frames/test_taxonomy_layout.py
@@ -0,0 +1,92 @@
+# SPDX-License-Identifier: Apache-2.0
+"""File taxonomy (layout: taxonomy/v1) e2e — 방향/자세 폴더 분리.
+
+기본 계약: 방향 계약 런은 raw/<dir>/<pose>.png · frames/<dir>/<pose>/ ·
+references/layout-guides/<dir>/<pose>.png 로 나뉜다. 상태 ID(<dir>_<pose>)와
+manifest row.files 가 소비자(합성/뷰)의 경로 SSoT 다. legacy 런(layout 필드
+없음)은 flat 그대로 — 기존 골든 테스트들이 그 회귀를 잡는다.
+"""
+
+import json
+import random
+from pathlib import Path
+
+from PIL import Image
+
+import sprite_gen.compose.compose_atlas as compose_module
+import sprite_gen.frames.extract as extract_module
+from conftest import run_script
+from sprite_gen.spec.layout import frames_dir_rel, raw_rel, row_frame_rel
+
+MAGENTA = (255, 0, 255)
+
+
+def _figure(width, height, seed):
+ rng = random.Random(seed)
+ art = Image.new("RGB", (width, height), MAGENTA)
+ for y in range(height):
+ for x in range(width):
+ if rng.random() < 0.6:
+ art.putpixel((x, y), (rng.randrange(30, 220), rng.randrange(30, 220), rng.randrange(30, 220)))
+ return art
+
+
+def _strip(frames, width=120, height=200, gap=36, seed=1):
+ figure = _figure(20, 34, seed).resize((width, height), Image.Resampling.NEAREST)
+ strip = Image.new("RGB", (frames * width + gap * (frames + 1), height + gap * 2), MAGENTA)
+ for i in range(frames):
+ strip.paste(figure, (gap + i * (width + gap), gap))
+ return strip
+
+
+def test_taxonomy_end_to_end(tmp_path: Path) -> None:
+ out_dir = tmp_path / "run"
+ result = run_script(
+ "prepare_sprite_run.py",
+ "--out-dir", str(out_dir),
+ "--character-id", "taxobot",
+ "--cell-size", "64", "--safe-margin", "6",
+ "--directions", "down,side", "--mirror", "left=side",
+ "--request-json", json.dumps({
+ "states": {
+ "down_walk": {"frames": 2, "fps": 8, "loop": True, "action": "walk toward viewer"},
+ "side_walk": {"frames": 2, "fps": 8, "loop": True, "action": "walk side view"},
+ },
+ }),
+ )
+ assert result.returncode == 0, result.stdout + result.stderr
+ request = json.loads((out_dir / "sprite-request.json").read_text(encoding="utf-8"))
+
+ # 리졸버 계약: 방향/자세 폴더
+ assert raw_rel(request, "down_idle") == "raw/down/idle.png"
+ assert frames_dir_rel(request, "side_walk") == "frames/side/walk"
+
+ # 택소노미 위치에 raw 를 넣고 추출
+ for seed, state in enumerate(request["states"], start=3):
+ rel = raw_rel(request, state)
+ (out_dir / rel).parent.mkdir(parents=True, exist_ok=True)
+ _strip(int(request["states"][state]["frames"]), seed=seed).save(out_dir / rel)
+ assert extract_module.run(run_dir=out_dir, min_used_pixels=200) == 0
+
+ manifest = json.loads((out_dir / "frames" / "frames-manifest.json").read_text(encoding="utf-8"))
+ rows = {r["state"]: r for r in manifest["rows"]}
+ assert set(rows) == set(request["states"])
+ for state, row in rows.items():
+ assert row["ok"], row
+ for rel in row["files"]:
+ assert rel.startswith(frames_dir_rel(request, state) + "/"), rel
+ assert (out_dir / rel).is_file(), rel
+ # row files 가 소비자 경로 SSoT
+ assert row_frame_rel(rows["down_walk"], 0) == "frames/down/walk/frame-0.png"
+
+ # 합성까지 (manifest 경로 추종 확인)
+ assert compose_module.run(run_dir=out_dir, min_used_pixels=200) == 0
+ atlas_manifest = json.loads((out_dir / "manifest.json").read_text(encoding="utf-8"))
+ assert set(atlas_manifest["frame_layout"]["rows"]) == set(request["states"])
+
+ # 뷰 스냅샷도 같은 경로를 서빙
+ import sprite_gen.serve.serve_curation as serve_curation
+ snapshot = serve_curation.build_run_state(out_dir)
+ walk = next(s for s in snapshot["states"] if s["name"] == "down_walk")
+ assert walk["frames"][0]["present"]
+ assert "/frames/down/walk/frame-0.png" in walk["frames"][0]["url"]
diff --git a/tests/gen/test_chroma_extraction.py b/tests/gen/test_chroma_extraction.py
new file mode 100644
index 0000000..97169b1
--- /dev/null
+++ b/tests/gen/test_chroma_extraction.py
@@ -0,0 +1,390 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Regression tests for chroma-key alpha cleanup and auto key selection.
+
+These guard three ways the extractor used to silently destroy real subject
+colors:
+
+1. ``remove_chroma_background`` ran a "neutralize key tint" pass on every pixel
+ whose channels leaned toward the key's channels, *regardless of color
+ distance* — so a saturated red/orange/blue subject was clamped toward
+ olive/grey under a magenta key even though it sat >200 away from magenta.
+ The destructive pass is gone; near-key antialias fringe is still cleaned.
+2. ``choose_chroma_key`` ranked candidates by the 1st-percentile distance to
+ subject pixels, which discards sub-1% features (eyes, gems, ear lamps): the
+ auto key could look safe while its nearest subject pixel was still inside the
+ extraction erase radius and would be deleted.
+3. The old fringe cut erased every pixel inside the fringe color band *anywhere
+ in the image* — hot pink (~129 from magenta) and purple (~153) subjects fell
+ in the band and were bleached wholesale. Soft-alpha unmix now treats boundary
+ antialiasing as coverage while deeper interior subject pixels survive.
+"""
+
+from __future__ import annotations
+
+import importlib.util
+import sys
+from pathlib import Path
+
+import pytest
+from PIL import Image
+
+SCRIPTS_DIR = Path(__file__).resolve().parents[2] / "scripts"
+if str(SCRIPTS_DIR) not in sys.path:
+ sys.path.insert(0, str(SCRIPTS_DIR))
+
+
+def _load(name: str):
+ spec = importlib.util.spec_from_file_location(name, SCRIPTS_DIR / f"{name}.py")
+ module = importlib.util.module_from_spec(spec)
+ assert spec and spec.loader
+ spec.loader.exec_module(module)
+ return module
+
+
+extract = _load("extract_sprite_row_frames")
+prepare = _load("prepare_sprite_run")
+
+MAGENTA = (255, 0, 255)
+# extract_sprite_row_frames.py main() defaults
+KEY_THRESHOLD = 96.0
+FRINGE_THRESHOLD = 180.0
+FRINGE_DELTA = 18.0
+LEGACY_PEEL_DEPTH = 2
+
+FIXTURES = Path(__file__).resolve().parent.parent / "fixtures"
+MOE_FIXTURES = FIXTURES / "moe"
+
+# Subject colors that sit inside the magenta key's fringe trap band — the
+# position-blind fringe cut used to erase them wholesale. Both are ~129/~153
+# from magenta, i.e. close enough to the key to be trapped, far enough to be
+# real subject material.
+HOT_PINK = (250, 77, 150) # ~129 from magenta
+PURPLE = (213, 112, 246) # ~153 from magenta
+
+
+def _key(pixel: tuple[int, int, int], chroma_key=MAGENTA):
+ image = Image.new("RGBA", (1, 1), (*pixel, 255))
+ out = extract.remove_chroma_background(
+ image,
+ chroma_key,
+ threshold=KEY_THRESHOLD,
+ fringe_threshold=FRINGE_THRESHOLD,
+ fringe_delta=FRINGE_DELTA,
+ )
+ return out.getpixel((0, 0))
+
+
+def _clean(image: Image.Image, chroma_key=MAGENTA) -> Image.Image:
+ return extract.remove_chroma_background(
+ image,
+ chroma_key,
+ threshold=KEY_THRESHOLD,
+ fringe_threshold=FRINGE_THRESHOLD,
+ fringe_delta=FRINGE_DELTA,
+ )
+
+
+def test_optional_chroma_tunables_are_keyword_only() -> None:
+ image = Image.new("RGBA", (1, 1), (*MAGENTA, 255))
+ with pytest.raises(TypeError):
+ extract.remove_chroma_background(image, MAGENTA, KEY_THRESHOLD, FRINGE_THRESHOLD, FRINGE_DELTA, 2)
+
+
+def _open_moe(name: str) -> Image.Image:
+ with Image.open(MOE_FIXTURES / name) as opened:
+ return opened.convert("RGBA")
+
+
+def _fringe_peel_candidates(image: Image.Image, chroma_key: tuple[int, int, int]) -> list[tuple[int, int]]:
+ """Pixels the legacy in-band peel would erase before soft-alpha unmix."""
+ width, height = image.size
+ pixels = image.load()
+ classes = bytearray(width * height)
+ keyed: list[int] = []
+ for y in range(height):
+ for x in range(width):
+ red, green, blue, alpha = pixels[x, y]
+ index = y * width + x
+ color = (red, green, blue)
+ if alpha == 0 or extract.color_distance(color, chroma_key) <= KEY_THRESHOLD:
+ classes[index] = extract._KEYED
+ keyed.append(index)
+ elif extract.key_tint_score(color, chroma_key) < FRINGE_DELTA:
+ classes[index] = extract._SUBJECT
+ elif extract.color_distance(color, chroma_key) <= FRINGE_THRESHOLD:
+ classes[index] = extract._BLEND_IN_BAND
+ else:
+ classes[index] = extract._BLEND_OUT_OF_BAND
+
+ frontier = keyed
+ peeled: list[tuple[int, int]] = []
+ for _ in range(LEGACY_PEEL_DEPTH):
+ next_frontier = []
+ for index in frontier:
+ x = index % width
+ y = index // width
+ for dy in (-1, 0, 1):
+ ny = y + dy
+ if ny < 0 or ny >= height:
+ continue
+ for dx in (-1, 0, 1):
+ nx = x + dx
+ if nx < 0 or nx >= width:
+ continue
+ neighbor = ny * width + nx
+ if classes[neighbor] != extract._BLEND_IN_BAND:
+ continue
+ classes[neighbor] = extract._KEYED
+ next_frontier.append(neighbor)
+ peeled.append((nx, ny))
+ if not next_frontier:
+ break
+ frontier = next_frontier
+ return peeled
+
+
+def _heart_material_pixels(name: str, image: Image.Image) -> list[tuple[int, int]]:
+ pixels = image.load()
+ if name == "moe_heart.png":
+ return [
+ (x, y)
+ for y in range(image.height)
+ for x in range(image.width)
+ if pixels[x, y][0] >= 240 and 60 <= pixels[x, y][1] <= 115 and 130 <= pixels[x, y][2] <= 175
+ ]
+ if name == "moe_mirror.png":
+ return [
+ (x, y)
+ for y in range(image.height)
+ for x in range(image.width)
+ if pixels[x, y][0] <= 30 and 180 <= pixels[x, y][1] <= 225 and 105 <= pixels[x, y][2] <= 145
+ ]
+ raise AssertionError(f"no heart material mask for {name}")
+
+
+MOE_PEEL_REMOVAL_CASES = [
+ ("moe_heart.png", MAGENTA, 160, 260),
+ ("moe_mirror.png", (0, 255, 0), 70, 120),
+]
+
+
+def test_moe_legacy_peel_band_becomes_soft_alpha_not_opaque_crust() -> None:
+ for name, chroma_key, _min_mid_alpha, _max_mid_alpha in MOE_PEEL_REMOVAL_CASES:
+ source = _open_moe(name)
+ peeled = _fringe_peel_candidates(source, chroma_key)
+ assert peeled, f"{name}: fixture lost the legacy peel band"
+
+ out = _clean(source, chroma_key).load()
+ transparent = [(x, y) for x, y in peeled if out[x, y][3] == 0]
+ opaque = [(x, y) for x, y in peeled if out[x, y][3] == 255]
+ assert not transparent, f"{name}: {len(transparent)} legacy peel pixels were still erased"
+ assert not opaque, f"{name}: {len(opaque)} legacy peel pixels survived as opaque crust"
+
+
+def test_moe_fixtures_keep_meaningful_mid_alpha_edges() -> None:
+ for name, chroma_key, min_mid_alpha, max_mid_alpha in MOE_PEEL_REMOVAL_CASES:
+ out = _clean(_open_moe(name), chroma_key)
+ histogram = out.getchannel("A").histogram()
+ mid_alpha = sum(histogram[1:255])
+ assert min_mid_alpha <= mid_alpha <= max_mid_alpha, f"{name}: {mid_alpha} mid-alpha pixels"
+
+
+def test_key_tinted_heart_material_survives_byte_identical() -> None:
+ for name, chroma_key, _min_mid_alpha, _max_mid_alpha in MOE_PEEL_REMOVAL_CASES:
+ source = _open_moe(name)
+ material = _heart_material_pixels(name, source)
+ assert material, f"{name}: fixture lost its heart material pixels"
+
+ source_pixels = source.load()
+ out = _clean(source, chroma_key).load()
+ changed = [(x, y) for x, y in material if out[x, y] != source_pixels[x, y]]
+ assert not changed, f"{name}: {len(changed)} heart material pixels changed, e.g. {changed[:5]}"
+
+
+def test_despill_preserves_far_subject_colors() -> None:
+ # All of these sit >200 color-distance away from magenta: they are the
+ # subject, not key fringe, and must survive completely untouched.
+ for pixel in [(196, 54, 38), (224, 96, 40), (208, 44, 40), (40, 70, 200)]:
+ assert extract.color_distance(pixel, MAGENTA) > FRINGE_THRESHOLD
+ assert _key(pixel) == (*pixel, 255), f"{pixel} was mangled by despill"
+
+
+def test_exact_key_is_removed_everywhere() -> None:
+ assert _key(MAGENTA)[3] == 0
+
+
+FRINGE = (147, 90, 157) # magenta blended with a green subject edge
+
+
+def test_boundary_fringe_gets_soft_alpha() -> None:
+ # Green subject on magenta background with a one-pixel antialias fringe
+ # ring between them: the background must go, the fringe becomes coverage,
+ # and the subject must stay.
+ assert extract.color_distance(FRINGE, MAGENTA) <= FRINGE_THRESHOLD
+ assert extract.key_tint_score(FRINGE, MAGENTA) >= FRINGE_DELTA
+ green = (60, 170, 70)
+ image = Image.new("RGBA", (16, 16), (*MAGENTA, 255))
+ pixels = image.load()
+ for y in range(4, 12):
+ for x in range(4, 12):
+ pixels[x, y] = (*green, 255)
+ for x in range(3, 13): # fringe ring just outside the subject block
+ for y in (3, 12):
+ pixels[x, y] = (*FRINGE, 255)
+ pixels[y, x] = (*FRINGE, 255)
+ out = _clean(image).load()
+ assert out[0, 0][3] == 0 # background gone
+ assert 0 < out[3, 3][3] < 255 and 0 < out[12, 8][3] < 255 # fringe ring is soft alpha
+ assert out[8, 8] == (*green, 255) # subject intact
+
+
+def test_isolated_fringe_band_pixel_is_subject_not_fringe() -> None:
+ # The same fringe-band color *inside* a subject, nowhere near background,
+ # is a real material color and must survive (this is what the old
+ # position-blind cut destroyed).
+ green = (60, 170, 70)
+ image = Image.new("RGBA", (16, 16), (*green, 255))
+ image.load()[8, 8] = (*FRINGE, 255)
+ out = _clean(image).load()
+ assert out[8, 8] == (*FRINGE, 255)
+
+
+def test_key_tinted_subject_interior_survives() -> None:
+ # Hot pink / purple blocks on a magenta background: only the edge layers
+ # nearest the keyed-out background may become soft alpha; the interior must
+ # keep its exact color.
+ for subject in (HOT_PINK, PURPLE):
+ distance = extract.color_distance(subject, MAGENTA)
+ assert KEY_THRESHOLD < distance <= FRINGE_THRESHOLD # inside the trap band
+ assert extract.key_tint_score(subject, MAGENTA) >= FRINGE_DELTA
+ image = Image.new("RGBA", (32, 32), (*MAGENTA, 255))
+ pixels = image.load()
+ for y in range(8, 24):
+ for x in range(8, 24):
+ pixels[x, y] = (*subject, 255)
+ out = _clean(image).load()
+ assert out[0, 0][3] == 0 # background gone
+ # In-band unmix is bounded to the nearest two key-depth layers.
+ for offset in range(8 + LEGACY_PEEL_DEPTH, 24 - LEGACY_PEEL_DEPTH):
+ assert out[offset, offset] == (*subject, 255), f"{subject} interior erased at {offset}"
+
+
+def _trap_band_subject(subject: tuple[int, int, int], size: int = 100, margin: int = 6) -> Image.Image:
+ """A magenta-keyed canvas with a solid subject block whose color sits inside
+ the key's fringe trap band. Generated deterministically so the fringe-survival
+ guard needs no sample art shipped alongside the tests."""
+ canvas = Image.new("RGBA", (size + 2 * margin, size + 2 * margin), (*MAGENTA, 255))
+ pixels = canvas.load()
+ for y in range(margin, margin + size):
+ for x in range(margin, margin + size):
+ pixels[x, y] = (*subject, 255)
+ return canvas
+
+
+def _subject_band_survival(image: Image.Image) -> float:
+ """Survival ratio of fringe-band subject pixels after cleanup."""
+ source = image.load()
+ band = []
+ for y in range(image.height):
+ for x in range(image.width):
+ color = source[x, y][:3]
+ distance = extract.color_distance(color, MAGENTA)
+ if KEY_THRESHOLD < distance <= FRINGE_THRESHOLD and extract.key_tint_score(color, MAGENTA) >= FRINGE_DELTA:
+ band.append((x, y))
+ assert band, "generated subject has no fringe-band pixels; generator is wrong"
+ out = _clean(image).load()
+ survived = sum(1 for x, y in band if out[x, y][3] != 0)
+ return survived / len(band)
+
+
+def test_key_tinted_subject_material_survives() -> None:
+ # Hot-pink and purple subjects sit inside the magenta key's fringe trap. The
+ # old position-blind cut erased ~100% of them; boundary-limited despill must
+ # keep nearly all — only genuine key-blend edge pixels (the outer despill
+ # layers of the block) may go.
+ for subject in (HOT_PINK, PURPLE):
+ ratio = _subject_band_survival(_trap_band_subject(subject))
+ assert ratio >= 0.90, f"{subject}: only {ratio:.1%} of key-tinted subject pixels survived"
+
+
+def test_key_tinted_subject_opaque_pixels_do_not_regress() -> None:
+ # A 100x100 in-band subject block is ~10k opaque pixels; interior is
+ # untouchable and only the outer despill layers may go, so the vast majority
+ # must remain opaque after cleanup.
+ for subject in (HOT_PINK, PURPLE):
+ out = _clean(_trap_band_subject(subject))
+ opaque = out.getchannel("A").histogram()[255]
+ assert opaque >= 9000, f"{subject}: opaque subject pixels regressed to {opaque}"
+
+
+# A small, cyan-leaning teal feature: ~55 from the cyan key, so cyan would erase
+# it, yet it is far enough from magenta/green/blue for those to keep it.
+EYE = (0, 250, 200)
+
+
+def _reference_image(path: Path) -> None:
+ # 128px so PIL never downscales the sample (deterministic across platforms).
+ image = Image.new("RGBA", (128, 128), (0, 0, 0, 0))
+ pixels = image.load()
+ for y in range(128):
+ for x in range(128):
+ if (x - 64) ** 2 + (y - 64) ** 2 < 58 ** 2:
+ pixels[x, y] = (196, 54, 38, 255) # red-orange body (the bulk hue)
+ # Two tiny eyes: well under 1% of the subject, so the 1st-percentile ranking
+ # ignores them and a naive selector happily picks the cyan key that erases them.
+ for cx, cy in ((50, 52), (78, 52)):
+ for dy in range(-1, 2):
+ for dx in range(-2, 3):
+ pixels[cx + dx, cy + dy] = (*EYE, 255)
+ image.save(path)
+
+
+def test_auto_key_avoids_erasing_small_feature(tmp_path: Path) -> None:
+ ref = tmp_path / "base.png"
+ _reference_image(ref)
+
+ opaque = eyes = 0
+ with Image.open(ref) as opened:
+ data = opened.convert("RGBA").load()
+ for y in range(128):
+ for x in range(128):
+ r, g, b, a = data[x, y]
+ if a <= 16:
+ continue
+ opaque += 1
+ if (r, g, b) == EYE:
+ eyes += 1
+ assert opaque and eyes / opaque < 0.01 # the eyes are a sub-1% feature
+
+ pixels = prepare.sampled_reference_pixels(ref)
+ cyan = prepare.parse_hex_color("#00FFFF")
+ cyan_min = min(prepare.color_distance(cyan, pixel) for pixel in pixels)
+ # cyan would win the raw 1st-percentile ranking yet erase the eyes: that is
+ # exactly the trap the guard exists for.
+ assert cyan_min <= prepare.MIN_SUBJECT_KEY_DISTANCE
+
+ result = prepare.choose_chroma_key(ref, "auto")
+ assert result["selection"] == "auto"
+ assert result["name"] != "cyan"
+ # The chosen key clears every subject pixel, including the tiny eyes.
+ assert result["min_subject_distance"] > prepare.MIN_SUBJECT_KEY_DISTANCE
+ assert "warning" not in result
+
+
+def test_auto_key_warns_when_no_candidate_is_safe(tmp_path: Path) -> None:
+ # A subject that parks saturated pixels next to every candidate key: no safe
+ # choice exists, so the selector falls back to the ranking *and* warns.
+ ref = tmp_path / "rainbow.png"
+ image = Image.new("RGBA", (32, 32), (0, 0, 0, 0))
+ pixels = image.load()
+ near_keys = [(235, 30, 235), (30, 235, 30), (30, 235, 235), (20, 80, 235)]
+ for index, color in enumerate(near_keys):
+ for x in range(index * 8, index * 8 + 8):
+ for y in range(32):
+ pixels[x, y] = (*color, 255)
+ image.save(ref)
+
+ result = prepare.choose_chroma_key(ref, "auto")
+ assert result["selection"] == "auto"
+ assert result["min_subject_distance"] <= prepare.MIN_SUBJECT_KEY_DISTANCE
+ assert "warning" in result
diff --git a/tests/gen/test_chroma_key_auto.py b/tests/gen/test_chroma_key_auto.py
new file mode 100644
index 0000000..c084e89
--- /dev/null
+++ b/tests/gen/test_chroma_key_auto.py
@@ -0,0 +1,227 @@
+# SPDX-License-Identifier: Apache-2.0
+"""``--chroma-key auto`` candidate scoring over a base that carries a background.
+
+Every base in this pipeline is a subject drawn on a flat chroma background. The
+scorer used to count those background pixels as subject, which pinned whichever
+candidate matched the current background to ``min_subject_distance ~= 0`` and made
+it permanently unselectable -- ``auto`` could never re-choose the key the base was
+drawn against.
+
+Excluding the background naively would trade that bug for a worse one: a key-hued
+*gem* enclosed by the subject would vanish from the scoring too, and ``auto`` would
+bless the key that erases it. The two are told apart by flatness -- a hole showing
+the background through the silhouette is a flat fill, drawn material is shaded.
+"""
+
+from __future__ import annotations
+
+import importlib.util
+import json
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+from PIL import Image
+
+ROOT = Path(__file__).resolve().parents[2]
+_spec = importlib.util.spec_from_file_location("prepare_sprite_run", ROOT / "scripts" / "prepare_sprite_run.py")
+prepare = importlib.util.module_from_spec(_spec)
+assert _spec.loader is not None
+_spec.loader.exec_module(prepare)
+
+MAGENTA = (255, 0, 255)
+BODY = (196, 54, 38)
+
+
+def _base_on_background(path: Path, background: tuple[int, int, int] = MAGENTA, size: int = 160) -> Image.Image:
+ """A round body on a flat chroma background -- the shape every base has."""
+ image = Image.new("RGBA", (size, size), (*background, 255))
+ pixels = image.load()
+ radius = size * 3 // 8
+ center = size // 2
+ for y in range(size):
+ for x in range(size):
+ if (x - center) ** 2 + (y - center) ** 2 < radius ** 2:
+ pixels[x, y] = (*BODY, 255)
+ image.save(path)
+ return image
+
+
+def _paint_block(path: Path, image: Image.Image, box: tuple[int, int, int, int], color) -> None:
+ pixels = image.load()
+ left, top, right, bottom = box
+ for y in range(top, bottom):
+ for x in range(left, right):
+ pixels[x, y] = color(x, y) if callable(color) else (*color, 255)
+ image.save(path)
+
+
+def _candidate(result: dict, name: str) -> dict:
+ return next(entry for entry in result["candidates"] if entry["name"] == name)
+
+
+def test_flat_background_is_excluded_from_subject_pixels(tmp_path: Path) -> None:
+ ref = tmp_path / "base.png"
+ _base_on_background(ref)
+
+ result = prepare.choose_chroma_key(ref, "auto")
+ assert result["background"]["mode"] == "flat"
+ assert result["background"]["hex"] == "#FF00FF"
+
+ # No sampled subject pixel is the background, so the key the base was drawn
+ # against is scored against the body -- not against itself.
+ for pixel in prepare.sampled_reference_pixels(ref):
+ assert prepare.color_distance(pixel, MAGENTA) > prepare.BACKGROUND_TOLERANCE
+ assert _candidate(result, "magenta")["min_subject_distance"] > prepare.MIN_SUBJECT_KEY_DISTANCE
+ assert "warning" not in result
+
+
+def test_auto_can_reselect_the_key_the_base_was_drawn_against(tmp_path: Path) -> None:
+ # Subject material sits inside the erase radius of green, cyan and blue, so
+ # magenta is the only safe key -- and magenta is also the base's background.
+ ref = tmp_path / "base.png"
+ image = _base_on_background(ref)
+ for index, color in enumerate(((30, 235, 30), (30, 235, 235), (20, 80, 235))):
+ left = 55 + index * 20
+ _paint_block(ref, image, (left, 70, left + 18, 90), color)
+
+ result = prepare.choose_chroma_key(ref, "auto")
+ assert result["name"] == "magenta", result["candidates"]
+ assert result["min_subject_distance"] > prepare.MIN_SUBJECT_KEY_DISTANCE
+ for name in ("green", "cyan", "blue"):
+ assert _candidate(result, name)["clears_erase_radius"] is False
+ assert "warning" not in result
+
+
+def test_enclosed_flat_hole_is_background_not_material(tmp_path: Path) -> None:
+ # A flat key-colored square inside the body: the background showing through.
+ ref = tmp_path / "base.png"
+ image = _base_on_background(ref)
+ _paint_block(ref, image, (70, 70, 92, 92), MAGENTA)
+
+ result = prepare.choose_chroma_key(ref, "auto")
+ background = result["background"]
+ assert background["enclosed_background_pixels"] > 0
+ assert background["enclosed_material_pixels"] == 0
+ assert _candidate(result, "magenta")["clears_erase_radius"] is True
+
+
+def test_enclosed_shaded_key_hued_material_blocks_that_key(tmp_path: Path) -> None:
+ # A *shaded* magenta gem inside the body. It is not a hole, so it must stay in
+ # the subject and push magenta inside the erase radius (v1.10.1 key-tint
+ # protection: magenta material must not be silently deleted by a magenta key).
+ ref = tmp_path / "base.png"
+ image = _base_on_background(ref)
+
+ def gem(x: int, _y: int) -> tuple[int, int, int, int]:
+ ramp = (x - 70) / 22
+ return (int(200 + 50 * ramp), int(10 + 70 * (1 - ramp)), int(190 + 60 * ramp), 255)
+
+ _paint_block(ref, image, (70, 70, 92, 92), gem)
+
+ result = prepare.choose_chroma_key(ref, "auto")
+ assert result["background"]["enclosed_material_pixels"] > 0
+ assert _candidate(result, "magenta")["clears_erase_radius"] is False
+ assert result["name"] != "magenta"
+
+
+def test_transparent_base_keeps_its_pre_background_behaviour(tmp_path: Path) -> None:
+ # Regression: a base with no background at all. Nothing beyond the alpha rule
+ # is excluded, and a sub-1% feature still drives the erase-radius gate.
+ ref = tmp_path / "transparent.png"
+ image = Image.new("RGBA", (128, 128), (0, 0, 0, 0))
+ pixels = image.load()
+ for y in range(128):
+ for x in range(128):
+ if (x - 64) ** 2 + (y - 64) ** 2 < 58 ** 2:
+ pixels[x, y] = (*BODY, 255)
+ for center_x in (50, 78):
+ for y in range(50, 55):
+ for x in range(center_x - 2, center_x + 3):
+ pixels[x, y] = (0, 250, 200, 255) # teal eye: ~55 from cyan
+ image.save(ref)
+
+ result = prepare.choose_chroma_key(ref, "auto")
+ assert result["background"]["mode"] == "transparent"
+ assert "enclosed_background_pixels" not in result["background"]
+ assert result["name"] != "cyan"
+ assert _candidate(result, "cyan")["clears_erase_radius"] is False
+ assert result["min_subject_distance"] > prepare.MIN_SUBJECT_KEY_DISTANCE
+
+
+def test_heterogeneous_border_is_reported_instead_of_silently_assumed(
+ tmp_path: Path, capsys: pytest.CaptureFixture[str]
+) -> None:
+ # A full-bleed image has no background ring to detect. Excluding nothing is the
+ # only honest answer, and it is reported rather than passed off as a clean read.
+ ref = tmp_path / "rainbow.png"
+ image = Image.new("RGBA", (32, 32), (0, 0, 0, 0))
+ pixels = image.load()
+ for index, color in enumerate(((235, 30, 235), (30, 235, 30), (30, 235, 235), (20, 80, 235))):
+ for x in range(index * 8, index * 8 + 8):
+ for y in range(32):
+ pixels[x, y] = (*color, 255)
+ image.save(ref)
+
+ result = prepare.choose_chroma_key(ref, "auto")
+ assert result["background"]["mode"] == "heterogeneous"
+ assert "note" in result["background"]
+ assert "border ring is not a flat fill" in capsys.readouterr().err
+ # No candidate can clear a subject that hugs all four keys.
+ assert result["min_subject_distance"] <= prepare.MIN_SUBJECT_KEY_DISTANCE
+ assert "warning" in result
+
+
+def test_background_only_base_warns_instead_of_defaulting_quietly(
+ tmp_path: Path, capsys: pytest.CaptureFixture[str]
+) -> None:
+ ref = tmp_path / "empty.png"
+ Image.new("RGBA", (64, 64), (*MAGENTA, 255)).save(ref)
+
+ result = prepare.choose_chroma_key(ref, "auto")
+ assert result["selection"] == "fallback"
+ assert "no subject pixels" in result["selection_reason"]
+ assert "no subject pixels" in capsys.readouterr().err
+
+
+def test_absent_reference_defaults_without_a_warning(capsys: pytest.CaptureFixture[str]) -> None:
+ result = prepare.choose_chroma_key(None, "auto")
+ assert result["selection"] == "fallback"
+ assert result["background"]["mode"] == "absent"
+ assert result["selection_reason"] == "no base reference to sample"
+ assert capsys.readouterr().err == ""
+
+
+def test_manual_key_skips_reference_analysis(tmp_path: Path) -> None:
+ ref = tmp_path / "base.png"
+ _base_on_background(ref)
+ result = prepare.choose_chroma_key(ref, "#00FF00")
+ assert result == {"name": "green", "hex": "#00FF00", "rgb": [0, 255, 0], "selection": "manual"}
+
+
+def test_request_json_records_the_selection_basis(tmp_path: Path) -> None:
+ ref = tmp_path / "base.png"
+ _base_on_background(ref)
+ out_dir = tmp_path / "run"
+
+ subprocess.run(
+ [
+ sys.executable,
+ str(ROOT / "scripts" / "prepare_sprite_run.py"),
+ "--out-dir", str(out_dir),
+ "--character-id", "probe",
+ "--base-image", str(ref),
+ "--chroma-key", "auto",
+ ],
+ check=True,
+ capture_output=True,
+ )
+
+ chroma = json.loads((out_dir / "sprite-request.json").read_text())["chroma_key"]
+ assert chroma["selection"] == "auto"
+ assert chroma["background"]["mode"] == "flat"
+ assert chroma["background"]["hex"] == "#FF00FF"
+ assert {entry["name"] for entry in chroma["candidates"]} == {"magenta", "green", "cyan", "blue"}
+ assert all("min_subject_distance" in entry for entry in chroma["candidates"])
+ assert "erase radius" in chroma["selection_reason"]
diff --git a/tests/gen/test_chroma_rcb_byte_identity.py b/tests/gen/test_chroma_rcb_byte_identity.py
new file mode 100644
index 0000000..22f841e
--- /dev/null
+++ b/tests/gen/test_chroma_rcb_byte_identity.py
@@ -0,0 +1,1482 @@
+# SPDX-License-Identifier: Apache-2.0
+"""바이트 동일 게이트 — 크로마 제거 스칼라 픽셀 루프의 벡터화 대비 동결 참조.
+
+플랜 `sprite-gen/extract-numpy-vectorization` 체크리스트 2번. 최적화 **전에** 세운다.
+
+## 왜 새 파일인가 (부모 파일을 확장하지 않은 근거)
+
+부모 플랜의 `tests/test_extract_perf_equivalence.py` 는 좋은 설계지만 그 참조들이
+프로덕션 프리미티브를 **그대로 호출한다** (`extract.rgb_to_ycc`, `extract.ycc_to_rgb`,
+`extract.smoothstep`, `extract._grid_edges`, `extract._YCC_*`). 부모가 깎은 함수들은
+그 프리미티브를 건드리지 않았으니 그 파일 안에서는 유효한 계약이다. 그러나 이 플랜은
+정확히 그 층(픽셀 단위 산수)을 배열 연산으로 바꾸므로, 같은 파일에 새 단정을 얹으면
+**참조가 프로덕션을 따라 움직여** 새 코드를 새 코드와 비교하고 무조건 통과한다.
+
+그래서 분리했다. 격리는 이 파일의 **파일 단위 불변식**이고, 아래 동결 구역은
+`test_frozen_reference_is_isolated_from_production` 이 소스를 직접 읽어 강제한다 —
+동결 구역이 프로덕션 모듈을 참조하는 순간 그 테스트가 빨개진다. 부모 파일에 섞으면
+이 불변식을 단정별로 사람이 눈으로 지켜야 하는데, 그건 게이트가 아니다.
+
+## 무엇을 고정하는가 (이중 잠금)
+
+1. **동결 스칼라 사본 대조** — 최적화 전 커밋(`5dd3118`, `engine_revision 3adf0169561a`)의
+ 스칼라 구현을 상수 리터럴까지 이 파일 안에 복사해 두고, 프로덕션 출력과
+ `.tobytes()` 로 완전 일치를 요구한다. 참조는 프로덕션을 import 하지 않으므로
+ 프로덕션이 바뀌어도 따라 움직이지 않는다.
+2. **절대 해시 고정** — 케이스별 출력 SHA-256 을 리터럴로 박는다. 누군가 프로덕션과
+ 참조를 **같이** 고쳐도(1번을 우회) 여기서 걸린다. 픽스처 PNG 바이트 해시도 함께
+ 박아 픽스처가 조용히 바뀌는 경로를 막는다.
+
+## 공개 픽스처 경계
+
+pytest 는 레포 안의 공개 또는 합성 입력만 읽으며 외부 런, 로컬 경로, 비공개 아트에
+의존하지 않는다. `tests/fixtures/moe/` 두 장은 AA 프린지와 마젠타·그린 키를 덮고,
+합성 픽스처는 입력 alpha==0, 과대 스필 클러스터, coverage<=0, 축퇴 키와 임계
+경계값을 결정론적으로 채운다. 난수나 외부 골든 파일은 사용하지 않는다.
+
+## 경계값이 게이트의 본체다
+
+첫 판은 39개 전부 통과했지만 소스 mutant 23종 중 **6종이 살아남았다** — 임계에서 정확히
+같은 값을 갖는 픽셀이 없으면 `<=` 를 `<` 로 바꿔도 출력이 그대로다. 살아남은 6종에 맞춰
+경계 픽스처를 추가한 뒤 **23/23 killed** 이 됐다. 각 픽스처 docstring 에 "어떤 변형을
+잡기 위한 자리인지" 를 적어 뒀으니 값을 바꿀 때 그 이유를 먼저 읽을 것 —
+숫자 하나(예: 클러스터 41px == spill_limit 41)가 mutant 두 종을 잡고 있다.
+
+## 노드 3 (체크리스트 3번) 에서 다시 만든 부분
+
+모듈 소스 전체를 변형해 갈아끼우는 하네스로 mutant 64종을 돌렸다
+(`_assets/extract-numpy-vectorization/mutants_node3.py`). 함수 단위 치환과 달리
+프리미티브 mutant 가 `remove_chroma_background` 안쪽까지 전파되고 모듈 상수도 대상이
+된다. 1라운드 50/63 killed → 살아남은 13종 중 **8종이 진짜 게이트 구멍**이라
+아래를 추가했다 (나머지 5종은 관측 불가능한 등가 mutant — 노드 3 결과 문서에 논증):
+
+- `_KEYS` 에 `(192, 255, 0)`·`(0, 255, 64)` — `key_tint_score` 의 채널 선택 임계
+ `>= 192`·`< 64` 를 정확히 밟는 키가 없어 두 연산자가 안 잠겨 있었다.
+- `_synthetic_spill_semantics_field` — 스필 한도 산식의 입력(`subject_count`),
+ 클러스터 축약(`max` vs `mean`), 알파 보존, 반올림 규약(half-to-even).
+- `_synthetic_reach_geometry_field` — 거리변환의 연결성 패리티와 경계 padding
+ (`np.roll` wrap).
+
+**여기 숫자는 하나도 임의값이 아니다.** 각 값이 어떤 변형을 잡는지 픽스처 docstring 에
+적어 뒀다.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import math
+import re
+from pathlib import Path
+
+import numpy as np
+import pytest
+from PIL import Image
+
+from sprite_gen.frames import extract
+
+FIXTURES = Path(__file__).resolve().parent.parent / "fixtures" / "moe"
+
+# extract CLI 기본값 (SSoT: sprite_gen/frames/extract.py argparse) — cutout.py 도 이 값을 쓴다
+CLI_KEY_THRESHOLD = 96.0
+CLI_FRINGE_THRESHOLD = 180.0
+CLI_FRINGE_DELTA = 18.0
+CLI_UNMIX_REACH = 4
+CLI_SPILL_MAX_FRACTION = 0.005
+
+MAGENTA = (255, 0, 255)
+GREEN = (0, 255, 0)
+
+
+# ===========================================================================
+# --- FROZEN SCALAR REFERENCE (BEGIN) ---------------------------------------
+# 최적화 전 커밋 5dd3118 / engine_revision 3adf0169561a 의 스칼라 구현 사본.
+# **이 구역은 프로덕션 모듈을 참조하지 않는다.** 상수도 리터럴로 복사한다.
+# 성능은 목적이 아니다 — 느려도 된다. 강제: test_frozen_reference_is_isolated_from_production
+# ===========================================================================
+
+_REF_KEYED = 0
+_REF_SUBJECT = 1
+_REF_BLEND_IN_BAND = 2
+_REF_BLEND_OUT_OF_BAND = 3
+_REF_IN_BAND_UNMIX_KEY_DEPTH = 2
+_REF_SPILL_MIN_TINT = 40.0
+_REF_COMPONENT_ALPHA_CUTOFF = 16
+_REF_EDGE_HISTOGRAM_DELTA = 96
+_REF_BOUNDARY_ALPHA_CUTOFF = 128
+_REF_BOUNDARY_COLOR_DELTA = 48
+
+
+def _ref_color_distance(left, right):
+ return math.sqrt(sum((left[index] - right[index]) ** 2 for index in range(3)))
+
+
+def _ref_key_tint_score(color, chroma_key):
+ keyed_channels = [index for index, value in enumerate(chroma_key) if value >= 192]
+ unkeyed_channels = [index for index, value in enumerate(chroma_key) if value < 64]
+ if not keyed_channels or not unkeyed_channels:
+ return 0.0
+ keyed_average = sum(color[index] for index in keyed_channels) / len(keyed_channels)
+ unkeyed_average = sum(color[index] for index in unkeyed_channels) / len(unkeyed_channels)
+ return keyed_average - unkeyed_average
+
+
+def _ref_despill_color(color, chroma_key, key_tint, tint):
+ k = min(tint / key_tint, 1.0)
+ coverage = 1.0 - k
+ if coverage <= 0:
+ return 0.0, (0, 0, 0)
+ red, green, blue = (
+ min(255, max(0, round((color[index] - k * chroma_key[index]) / coverage)))
+ for index in range(3)
+ )
+ return coverage, (red, green, blue)
+
+
+def _ref_unmix_key_blend(color, alpha, chroma_key, key_tint, tint):
+ coverage, despilled = _ref_despill_color(color, chroma_key, key_tint, tint)
+ out_alpha = round(alpha * coverage)
+ if out_alpha <= 0:
+ return (0, 0, 0, 0)
+ return (*despilled, out_alpha)
+
+
+def _ref_remove_chroma_background(
+ image,
+ chroma_key,
+ threshold,
+ fringe_threshold,
+ fringe_delta,
+ *,
+ unmix_reach=4,
+ spill_max_fraction=0.005,
+ counters=None,
+):
+ """동결 사본. `counters` 는 참조 전용 계측(분기 도달 확인)이며 출력에 영향이 없다."""
+ def bump(name, amount=1):
+ if counters is not None:
+ counters[name] = counters.get(name, 0) + amount
+
+ rgba = image.convert("RGBA")
+ width, height = rgba.size
+ pixels = rgba.load()
+ classes = bytearray(width * height)
+ unseen = 255
+ depths = bytearray(b"\xff" * (width * height))
+ keyed = []
+ for y in range(height):
+ for x in range(width):
+ red, green, blue, alpha = pixels[x, y]
+ index = y * width + x
+ color = (red, green, blue)
+ if alpha == 0 or _ref_color_distance(color, chroma_key) <= threshold:
+ pixels[x, y] = (0, 0, 0, 0)
+ classes[index] = _REF_KEYED
+ depths[index] = 0
+ keyed.append(index)
+ bump("keyed_alpha_zero" if alpha == 0 else "keyed_by_distance")
+ elif _ref_key_tint_score(color, chroma_key) < fringe_delta:
+ classes[index] = _REF_SUBJECT
+ bump("subject")
+ elif _ref_color_distance(color, chroma_key) <= fringe_threshold:
+ classes[index] = _REF_BLEND_IN_BAND
+ bump("blend_in_band")
+ else:
+ classes[index] = _REF_BLEND_OUT_OF_BAND
+ bump("blend_out_of_band")
+
+ key_tint = _ref_key_tint_score(chroma_key, chroma_key)
+ max_reach = min(unseen - 1, unmix_reach if key_tint > 0 else 0)
+ bump("degenerate_key_tint", 1 if key_tint <= 0 else 0)
+
+ frontier = keyed
+ depth = 0
+ while frontier and depth < max_reach:
+ depth += 1
+ next_frontier = []
+ for index in frontier:
+ x = index % width
+ y = index // width
+ for dy in (-1, 0, 1):
+ ny = y + dy
+ if ny < 0 or ny >= height:
+ continue
+ for dx in (-1, 0, 1):
+ nx = x + dx
+ if nx < 0 or nx >= width:
+ continue
+ neighbor = ny * width + nx
+ if depths[neighbor] == unseen:
+ depths[neighbor] = depth
+ next_frontier.append(neighbor)
+ frontier = next_frontier
+ bump("depth_reached_max", 1 if depth == max_reach and max_reach else 0)
+ bump("depth_positive", sum(1 for value in depths if 0 < value < unseen))
+
+ if key_tint > 0 and unmix_reach > 0:
+ for y in range(height):
+ for x in range(width):
+ index = y * width + x
+ if not 0 < depths[index] <= unmix_reach:
+ continue
+ pixel_class = classes[index]
+ if pixel_class == _REF_BLEND_IN_BAND:
+ if depths[index] > _REF_IN_BAND_UNMIX_KEY_DEPTH:
+ bump("unmix_in_band_skipped_deep")
+ continue
+ bump("unmix_in_band")
+ elif pixel_class != _REF_BLEND_OUT_OF_BAND:
+ continue
+ else:
+ bump("unmix_out_of_band")
+ red, green, blue, alpha = pixels[x, y]
+ color = (red, green, blue)
+ out = _ref_unmix_key_blend(
+ color, alpha, chroma_key, key_tint, _ref_key_tint_score(color, chroma_key)
+ )
+ bump("unmix_collapsed_to_transparent", 1 if out[3] == 0 else 0)
+ # 조건부 bump — 안 걸리면 키 자체가 안 생겨 기존 13 케이스의 기대표가
+ # 그대로다. 이 자리가 옛 경로에서 PIL 클램프에 기대던 유일한 지점이다:
+ # `pixels[x, y] = out` 이 258 을 255 로 조여서 넣었다.
+ if out[3] > 255:
+ bump("unmix_alpha_over_255")
+ pixels[x, y] = out
+
+ if key_tint > 0 and keyed and spill_max_fraction > 0:
+ subject_count = sum(1 for pixel_class in classes if pixel_class != _REF_KEYED)
+ spill_limit = max(32, round(subject_count * spill_max_fraction))
+ bump("spill_limit_from_fraction", 1 if round(subject_count * spill_max_fraction) > 32 else 0)
+ tints_left = {}
+ for y in range(height):
+ for x in range(width):
+ red, green, blue, alpha = pixels[x, y]
+ if not alpha:
+ continue
+ tint = _ref_key_tint_score((red, green, blue), chroma_key)
+ if tint >= fringe_delta:
+ tints_left[y * width + x] = tint
+ bump("spill_candidates", len(tints_left))
+ visited = set()
+ for start in tints_left:
+ if start in visited:
+ continue
+ stack = [start]
+ visited.add(start)
+ cluster = []
+ while stack:
+ index = stack.pop()
+ cluster.append(index)
+ x = index % width
+ y = index // width
+ for dy in (-1, 0, 1):
+ for dx in (-1, 0, 1):
+ if 0 <= x + dx < width and 0 <= y + dy < height:
+ neighbor = (y + dy) * width + (x + dx)
+ if neighbor in tints_left and neighbor not in visited:
+ visited.add(neighbor)
+ stack.append(neighbor)
+ if len(cluster) > spill_limit:
+ bump("spill_cluster_too_big")
+ continue
+ if max(tints_left[index] for index in cluster) <= _REF_SPILL_MIN_TINT:
+ bump("spill_cluster_low_tint")
+ continue
+ bump("spill_cluster_treated")
+ bump("spill_treated_px", len(cluster))
+ for index in cluster:
+ x = index % width
+ y = index // width
+ red, green, blue, alpha = pixels[x, y]
+ color = (red, green, blue)
+ coverage, despilled = _ref_despill_color(
+ color, chroma_key, key_tint, _ref_key_tint_score(color, chroma_key)
+ )
+ if coverage > 0:
+ pixels[x, y] = (*despilled, alpha)
+ else:
+ bump("spill_zero_coverage")
+ return rgba
+
+
+def _ref_connected_components(image):
+ alpha = image.getchannel("A")
+ width, height = image.size
+ data = alpha.tobytes()
+ visited = bytearray(width * height)
+ components = []
+
+ for start, alpha_value in enumerate(data):
+ if alpha_value <= _REF_COMPONENT_ALPHA_CUTOFF or visited[start]:
+ continue
+ stack = [start]
+ visited[start] = 1
+ pixels = []
+ min_x = width
+ min_y = height
+ max_x = 0
+ max_y = 0
+
+ while stack:
+ current = stack.pop()
+ pixels.append(current)
+ x = current % width
+ y = current // width
+ min_x = min(min_x, x)
+ min_y = min(min_y, y)
+ max_x = max(max_x, x)
+ max_y = max(max_y, y)
+
+ for neighbor in (current - 1, current + 1, current - width, current + width):
+ if neighbor < 0 or neighbor >= len(data) or visited[neighbor]:
+ continue
+ nx = neighbor % width
+ if abs(nx - x) > 1:
+ continue
+ if data[neighbor] > _REF_COMPONENT_ALPHA_CUTOFF:
+ visited[neighbor] = 1
+ stack.append(neighbor)
+
+ components.append(
+ {
+ "pixels": pixels,
+ "area": len(pixels),
+ "bbox": (min_x, min_y, max_x + 1, max_y + 1),
+ "center_x": (min_x + max_x + 1) / 2,
+ }
+ )
+ return components
+
+
+def _ref_edge_histograms(image):
+ pixels = image.convert("RGBA").load()
+ width, height = image.size
+ col_edges = [0] * width
+ row_edges = [0] * height
+ for y in range(0, height, 2):
+ for x in range(1, width):
+ a = pixels[x, y]
+ b = pixels[x - 1, y]
+ if (abs(a[0] - b[0]) + abs(a[1] - b[1]) + abs(a[2] - b[2]) + abs(a[3] - b[3])
+ > _REF_EDGE_HISTOGRAM_DELTA):
+ col_edges[x] += 1
+ for x in range(0, width, 2):
+ for y in range(1, height):
+ a = pixels[x, y]
+ b = pixels[x, y - 1]
+ if (abs(a[0] - b[0]) + abs(a[1] - b[1]) + abs(a[2] - b[2]) + abs(a[3] - b[3])
+ > _REF_EDGE_HISTOGRAM_DELTA):
+ row_edges[y] += 1
+ return col_edges, row_edges, width, height
+
+
+def _ref_boundary_mass(image):
+ px = image.load()
+ w, h = image.size
+ col = [0] * max(1, w)
+ row = [0] * max(1, h)
+ cut = _REF_BOUNDARY_ALPHA_CUTOFF
+ delta = _REF_BOUNDARY_COLOR_DELTA
+ for y in range(h):
+ for x in range(w - 1):
+ a, b = px[x, y], px[x + 1, y]
+ if (a[3] >= cut) != (b[3] >= cut) or (
+ a[3] >= cut and b[3] >= cut
+ and abs(a[0] - b[0]) + abs(a[1] - b[1]) + abs(a[2] - b[2]) > delta
+ ):
+ col[x + 1] += 1
+ for x in range(w):
+ for y in range(h - 1):
+ a, b = px[x, y], px[x, y + 1]
+ if (a[3] >= cut) != (b[3] >= cut) or (
+ a[3] >= cut and b[3] >= cut
+ and abs(a[0] - b[0]) + abs(a[1] - b[1]) + abs(a[2] - b[2]) > delta
+ ):
+ row[y + 1] += 1
+ return col, row
+
+
+# ===========================================================================
+# --- FROZEN SCALAR REFERENCE (END) -----------------------------------------
+# ===========================================================================
+
+
+# --- 픽스처 ----------------------------------------------------------------
+# 실촬본은 이미 레포에 있는 moe raw 축소본이고, 합성본은 실촬본이 못 밟는
+# 분기만 결정론적 산수로 채운다 (난수 없음).
+
+# 픽스처 PNG 바이트 고정 — 픽스처가 조용히 바뀌면 골든이 의미를 잃는다
+MOE_FIXTURE_SHA256 = {
+ "moe_green.png": "91fe50bfd640fa2e029723e1859a1578e780221d5870f0614fbc73f0b788c825",
+ "moe_red.png": "28279535eaca2ce603b7671b26d30a1475763f7d9ae7674f19b6d28a8cfb8eaa",
+}
+
+
+def _open_moe(name: str) -> Image.Image:
+ with Image.open(FIXTURES / name) as opened:
+ return opened.convert("RGBA")
+
+
+def _synthetic_branch_field(width: int = 96, height: int = 72) -> Image.Image:
+ """그린 키 합성 입력 — 실촬 moe 픽스처가 못 밟는 분기를 채운다.
+
+ - 상단 2행은 입력 alpha==0 (실촬 raw 는 전부 불투명이라 이 분기가 안 밟힌다)
+ - 피험체 안쪽 8x8 틴트 패치 = 스필 한도 초과 클러스터 (untouched 분기)
+ - 안쪽 3x3 강한 틴트 패치 = 작은 스필 클러스터 (despill 분기)
+ - 안쪽 4x2 약한 틴트 패치 = tint <= 40 (untouched 분기)
+ - 실루엣 프린지 링 = in-band/out-of-band 블렌드 + depth 1~4
+ """
+ img = Image.new("RGBA", (width, height), (0, 0, 0, 0))
+ px = img.load()
+ for y in range(height):
+ for x in range(width):
+ # 흔들리는 키 배경 — 평탄색이 아니어야 거리 임계가 실제로 판정을 한다
+ red = 11 + ((x * 3) % 5)
+ green = 238 - ((x + y) % 7)
+ blue = 27 + ((y * 2) % 5)
+ alpha = 255
+ if y < 2: # 입력 alpha==0 밴드
+ px[x, y] = (red, green, blue, 0)
+ continue
+ if 20 <= x < 76 and 16 <= y < 64: # 피험체 (마젠타 계열 → tint 음수)
+ red, green, blue = 180 + (x % 20), 40 + (y % 15), 150 - (x % 12)
+ if x < 24 or x >= 72 or y < 20 or y >= 60:
+ # 프린지 링: in-band (거리 <= 180, tint >= 18)
+ red, green, blue = 95, 150, 80
+ if x == 24 or x == 71:
+ # 프린지 안쪽 한 겹: out-of-band (거리 > 180, tint >= 18)
+ red, green, blue = 30, 200, 220
+ if 30 <= x < 38 and 30 <= y < 38:
+ red, green, blue = 120, 200, 90 # 과대 스필 클러스터 (64px)
+ if 52 <= x < 55 and 30 <= y < 33:
+ red, green, blue = 120, 200, 90 # 작은 스필 클러스터 (9px)
+ if 52 <= x < 56 and 44 <= y < 46:
+ red, green, blue = 150, 180, 140 # 약한 틴트 (tint 35)
+ if 60 <= x < 63 and 44 <= y < 47:
+ red, green, blue = 160, 200, 160 # tint 정확히 40.0 (경계)
+ # tint 정확히 18.0 픽셀이 강한 틴트 클러스터에 **붙어** 있어야
+ # `tint >= fringe_delta` 를 `>` 로 뒤집는 변경이 출력을 바꾼다
+ # (혼자 있으면 어느 쪽이든 max tint <= 40 으로 통과돼 무해해진다)
+ if 40 <= x < 42 and 50 <= y < 52:
+ red, green, blue = 120, 200, 90 # tint 95
+ if x == 42 and y == 50:
+ red, green, blue = 100, 118, 100 # tint 정확히 18.0
+ # 대각선으로만 이어진 강/약 틴트 쌍 — 스필 flood 의 8-이웃 계약.
+ # 4-이웃으로 바뀌면 약한 쪽이 별도 클러스터가 되어 despill 을 면한다
+ if 46 <= x < 48 and 54 <= y < 56:
+ red, green, blue = 120, 200, 90 # tint 95
+ if 48 <= x < 50 and 56 <= y < 58:
+ red, green, blue = 150, 180, 140 # tint 35 (대각선 접촉만)
+ px[x, y] = (red, green, blue, alpha)
+ return img
+
+
+def _synthetic_zero_coverage(width: int = 40, height: int = 32) -> Image.Image:
+ """coverage <= 0 분기용 — 포화되지 않은 키가 필요하다.
+
+ 포화 키(green/magenta)에서는 `tint >= key_tint` 가 곧 "키 자기 자신"이라
+ P1 이 이미 지워버려 이 분기에 도달할 수 없다. 공개 픽스처의 포화 키에서도
+ non-keyed tint 가 `key_tint` 에 도달하지 않는다.
+ 그래서 키를 (0,200,0)/threshold 20 으로 두고 tint 228 픽셀을 심는다.
+
+ 두 자리에 심는다 — coverage<=0 은 두 패스에 각각 있고 결과가 다르다:
+ - 실루엣 경계(depth 1~4): unmix 가 `(0,0,0,0)` 으로 지운다
+ - 피험체 깊은 안쪽(depth > reach): 갇힌 스필 패스가 도달하지만
+ `if coverage > 0` 이 거짓이라 **아무것도 쓰지 않는다** (원본 유지)
+ """
+ img = Image.new("RGBA", (width, height), (5, 198, 3, 255))
+ px = img.load()
+ for y in range(6, 26):
+ for x in range(8, 32):
+ px[x, y] = (200, 40, 180, 255) # 피험체 24x20
+ for y in range(5, 27):
+ px[7, y] = (27, 255, 27, 255) # 경계 tint 228 → unmix coverage <= 0
+ px[32, y] = (27, 255, 27, 255)
+ for y in range(14, 17):
+ for x in range(18, 21):
+ px[x, y] = (27, 255, 27, 255) # 깊은 안쪽 3x3 → 스필 패스 coverage <= 0
+ return img
+
+
+def _synthetic_fraction_limit_field(width: int = 140, height: int = 110) -> Image.Image:
+ """`spill_limit = max(32, round(subject_count * spill_max_fraction))` 의 산식
+ 자체를 고정한다. 작은 캔버스에서는 항상 32 로 클램프돼 이 분기가 죽는다.
+
+ 비-키 픽셀을 **정확히 8,120** 개로 맞춘다 (피험체 박스 100x80 = 8,000 +
+ 별도 블록 12x10 = 120). 8120 x 0.005 = **40.6** 이라
+ `round` → 41, `int` → 40 으로 갈린다. 그 안에 심은 강한 틴트 클러스터는
+ 정확히 **41px** (8x5 + 1) 이므로:
+
+ - 현행 `round` + `len(cluster) > spill_limit`: 41 > 41 거짓 → **despill 됨**
+ - `round` 를 `int` 로 바꾸면: limit 40, 41 > 40 → too_big → **안 건드림**
+ - `>` 를 `>=` 로 바꾸면: 41 >= 41 → too_big → **안 건드림**
+
+ 즉 세 변형이 모두 출력을 바꾼다 — 클러스터 크기를 한도와 정확히 같게 두는 게
+ 핵심이다(36px 이던 첫 판은 두 변형을 다 놓쳤다).
+ """
+ img = Image.new("RGBA", (width, height), (0, 0, 0, 0))
+ px = img.load()
+ for y in range(height):
+ for x in range(width):
+ red = 11 + ((x * 3) % 5)
+ green = 238 - ((x + y) % 7)
+ blue = 27 + ((y * 2) % 5)
+ if 20 <= x < 120 and 15 <= y < 95: # 피험체 박스 100x80 = 8,000px
+ red, green, blue = 180 + (x % 20), 40 + (y % 15), 150 - (x % 12)
+ if x < 22 or x >= 118 or y < 17 or y >= 93:
+ red, green, blue = 95, 150, 80 # in-band 프린지 링
+ if (60 <= x < 68 and 50 <= y < 55) or (x == 68 and y == 50):
+ red, green, blue = 120, 200, 90 # 41px 강한 틴트 클러스터
+ elif 125 <= x < 137 and 15 <= y < 25: # 별도 피험체 블록 12x10 = 120px
+ red, green, blue = 200, 40, 180
+ px[x, y] = (red, green, blue, 255)
+ return img
+
+
+def _synthetic_threshold_boundary_field(width: int = 48, height: int = 40) -> Image.Image:
+ """분류 임계의 **경계값** 전용 — `<=` 를 `<` 로 바꾸면 출력이 실제로 달라지게.
+
+ 임계에서 정확히 같은 값을 갖는 픽셀이 없으면 비교 연산자 뒤집기가 게이트를
+ 빠져나간다(실측으로 확인: 첫 판의 게이트는 `_SPILL_MIN_TINT 40->39` 를 놓쳤다).
+ 키 배경 위에 서로 3px 이상 떨어진 고립 픽셀로 심어 각자 독립 클러스터가 되게 한다.
+
+ | 색 | 값 | 걸리는 경계 |
+ |----------------|---------------------------|--------------------------------|
+ | (0, 159, 0) | 키 거리 정확히 96.0 | `<= threshold` (지움) |
+ | (1, 159, 0) | 키 거리 96.005 | 바로 위 — 지우지 않음 |
+ | (0, 75, 0) | 키 거리 정확히 180.0 | `<= fringe_threshold` (in-band)|
+ | (1, 75, 0) | 키 거리 180.003 | 바로 위 — out-of-band |
+ | (100,118,100) | tint 정확히 18.0 | `< fringe_delta` (블렌드) |
+ | (101,118,100) | tint 17.5 | 바로 아래 — subject |
+ """
+ img = Image.new("RGBA", (width, height), (0, 0, 0, 0))
+ px = img.load()
+ for y in range(height):
+ for x in range(width):
+ px[x, y] = (11, 238, 27, 255)
+ probes = [
+ (0, 159, 0), (1, 159, 0), (0, 75, 0), (1, 75, 0),
+ (100, 118, 100), (101, 118, 100), (200, 40, 180), (12, 236, 26),
+ ]
+ for slot, color in enumerate(probes):
+ for repeat in range(3): # 같은 경계값을 3자리에 — 깊이 1 고립 픽셀
+ x = 4 + (slot % 4) * 11 + repeat * 3
+ y = 6 + (slot // 4) * 12 + repeat * 4
+ px[x, y] = (*color, 255)
+ px[45, 2] = (200, 40, 180, 0) # 입력 alpha==0 (색은 피험체) → 지워져야 한다
+ # 깊이 3·4 자리의 프린지 경계 프로브. 깊이 1 에서는 in-band 와 out-of-band 가
+ # **똑같이** unmix 되므로 `<= fringe_threshold` 를 뒤집어도 출력이 안 바뀐다.
+ # 깊이 3 이상에서만 in-band 는 건너뛰고 out-of-band 는 unmix 되어 갈라진다.
+ for y in range(30, 37):
+ for x in range(6, 13):
+ px[x, y] = (200, 40, 180, 255) # 7x7 피험체 블록 → 중심이 깊이 4
+ px[8, 33] = (0, 75, 0, 255) # 키 거리 정확히 180.0, 깊이 3
+ px[9, 33] = (0, 75, 0, 255) # 키 거리 정확히 180.0, 깊이 4
+ return img
+
+
+def _alpha_boundary_field(width: int = 40, height: int = 24) -> Image.Image:
+ """티어 2 함수(`connected_components`·`_edge_histograms`·`_boundary_mass`)의
+ 임계 경계값 전용 RGBA. 크로마 패스를 통과시키지 않고 **직접** 만든다 —
+ 크로마 출력에는 alpha 가 정확히 16/17 이나 델타가 정확히 96/97 인 픽셀이
+ 우연히 없어서 컷오프 변경이 게이트를 빠져나갔다(실측 확인).
+
+ - alpha 15/16/17: `connected_components` 의 `> 16` 컷오프
+ - alpha 127/128: `_boundary_mass` 의 `>= 128` 컷오프
+ - 이웃 채널 절대차 합 96/97: `_edge_histograms` 의 `> 96`
+ - 이웃 RGB 절대차 합 48/49: `_boundary_mass` 의 `> 48`
+ """
+ img = Image.new("RGBA", (width, height), (0, 0, 0, 0))
+ px = img.load()
+ for slot, alpha in enumerate((15, 16, 17, 127, 128, 255)):
+ x = 2 + slot * 6
+ for y in (2, 3, 4): # 세로 3px 덩어리 → 성분 경계가 생긴다
+ px[x, y] = (120, 60, 200, alpha)
+ px[x + 1, y] = (120, 60, 200, alpha)
+ base = (100, 100, 100)
+ for slot, delta in enumerate((95, 96, 97, 47, 48, 49)):
+ y = 10 + slot * 2
+ for x in range(0, width - 1, 4):
+ px[x, y] = (*base, 255)
+ px[x + 1, y] = (base[0] + delta, base[1], base[2], 255)
+ for x in range(width): # 알파 127/128 인 가로 띠 — 세로 방향 경계 판정
+ px[x, 22] = (10, 220, 30, 127)
+ px[x, 23] = (10, 220, 30, 128)
+ # 성분 픽셀에 **붙어 있는** alpha 16 — `data[neighbor] > 16` 을 `>= 16` 으로
+ # 바꾸면 이 픽셀이 성분에 흡수돼 area 가 달라진다. 떨어져 있으면 어느 쪽이든
+ # 시작 조건(`<= 16`)에서 걸러져 무해해진다.
+ px[20, 7] = (90, 140, 220, 255)
+ px[21, 7] = (90, 140, 220, 16)
+ # `_boundary_mass` AND 항의 **위쪽** 경계 (노드 3 attempt 2, R2).
+ # 위 alpha 127/128 가로 띠는 XOR 항만 밟는다 — 색이 같아서 AND 항의 색차
+ # 조건이 거짓이기 때문이다. `a[3] >= 128 and b[3] >= 128` 을 `> 128` 로 옮기는
+ # 변경을 잡으려면 **양쪽 알파가 >= 128 이고 한쪽이 정확히 128 이면서 색차 L1
+ # 이 48 을 넘는** 인접쌍이 필요하다 (그 쌍은 XOR 항이 거짓이라 AND 항만 판정한다).
+ # attempt 1 의 `>=128 -> >=127` 은 killed 였으므로 임계가 한쪽에서만 잠겨 있었다.
+ # 색차는 100 (200 vs 100 채널 0) 이라 `> 48` 쪽 임계와는 독립이다.
+ px[2, 6] = (200, 100, 100, 128) # 가로쌍 왼쪽 — 알파 정확히 128
+ px[3, 6] = (100, 100, 100, 255)
+ px[6, 5] = (200, 100, 100, 128) # 세로쌍 위 — 알파 정확히 128
+ px[6, 6] = (100, 100, 100, 255)
+ return img
+
+
+def _synthetic_spill_semantics_field(width: int = 160, height: int = 120) -> Image.Image:
+ """갇힌 스필 패스의 **의미**를 고정한다 (노드 3 추가 — mutant 4종을 잡는 자리).
+
+ - 비-키 픽셀이 **정확히 8,000** 개다 (피험체 100x80, 안쪽 재색칠은 개수를 안
+ 바꾼다). 캔버스는 19,200px 이라 `subject_count` 를 `width * height` 로 갈음하면
+ 한도가 `round(8000*0.005)=40` 에서 `round(19200*0.005)=96` 으로 뛴다. 그
+ 사이에 **60px 클러스터**를 놓았다 — 원본은 `60 > 40` 이라 too_big 로 안
+ 건드리고, 갈음한 구현은 despill 한다.
+ - **11px 클러스터** = 강한 틴트 1px(tint 95) + 약한 틴트 10px(tint 19).
+ `max` 95 > 40 이라 원본은 treated, 평균은 25.909 <= 40 이라 클러스터 축약을
+ `max` 대신 `mean`(np.mean) 으로 짜면 통째로 빠진다.
+ - 그 11px 는 **alpha 200** 이다. 스필은 색보정이라 알파를 보존한다 — despill
+ 결과에 255 를 박는 구현은 여기서 갈린다. (다른 픽스처의 스필 클러스터는 전부
+ alpha 255 라 이 계약이 안 잠겨 있었다.)
+ - **(2, 52, 0) 단독 픽셀**: tint 51 이라 `k = 51/255 = 0.2`, `coverage = 0.8`,
+ 채널 0 이 정확히 `2 / 0.8 == 2.5`. 파이썬 `round` 는 half-to-even 이라 **2**,
+ 손으로 짠 `np.floor(x + 0.5)` 는 **3** 이다. 반올림 규약이 갈리는 유일한 자리다.
+
+ 피험체 테두리는 subject 색이라 unmix 패스는 이 케이스에서 아무것도 하지 않는다 —
+ 스필 패스만 관측된다.
+ """
+ img = Image.new("RGBA", (width, height), (0, 0, 0, 0))
+ px = img.load()
+ for y in range(height):
+ for x in range(width):
+ red = 11 + ((x * 3) % 5)
+ green = 238 - ((x + y) % 7)
+ blue = 27 + ((y * 2) % 5)
+ alpha = 255
+ if 20 <= x < 120 and 15 <= y < 95: # 피험체 100x80 = 8,000px
+ red, green, blue = 180 + (x % 20), 40 + (y % 15), 150 - (x % 12)
+ if 30 <= x < 40 and 30 <= y < 36:
+ red, green, blue = 120, 200, 90 # 60px — 한도 40 초과, 96 미만
+ if x == 60 and y == 50:
+ red, green, blue, alpha = 120, 200, 90, 200 # 11px 클러스터의 씨앗
+ if 61 <= x < 66 and 50 <= y < 52:
+ red, green, blue, alpha = 150, 169, 150, 200 # tint 19 x 10px
+ if x == 90 and y == 70:
+ red, green, blue = 2, 52, 0 # coverage 0.8 → 채널0 이 정확히 2.5
+ px[x, y] = (red, green, blue, alpha)
+ return img
+
+
+def _synthetic_reach_geometry_field(width: int = 40, height: int = 28) -> Image.Image:
+ """거리변환(P2)의 **연결성 패리티와 경계 padding** 을 고정한다 (노드 3 추가).
+
+ 깊이는 최근접 keyed 픽셀까지의 체비셰프 거리다. 그 정의가 깨지는 두 방향이
+ 기존 9 케이스에서 안 잠겨 있었다.
+
+ - **키 구멍 1px** `(10, 15)` 과 거기서 오프셋 `(4, 1)` 인 out-of-band 블렌드
+ 픽셀 `(14, 16)`. 체비셰프 깊이는 `max(4, 1) = 4` 라 원본은 unmix 하지만, 같은
+ 행 이웃을 잃은 구현(`for dy in (-1, 1)`)은 y 를 매 스텝 ±1 옮겨야 해서 홀수
+ 스텝이 필요하고 깊이 5 -> 미도달이다. 기존 픽스처는 최대깊이 픽셀이 전부 짝수
+ 패리티(오프셋 `(4, 0)`) 자리라 이 변형이 통과했다.
+ - **상단 1행만 키 배경**, 나머지는 피험체. 바닥 행 `(25, 27)` 의 블렌드 픽셀은
+ 원본에서 깊이 27 이라 도달 불가지만, 시프트를 `np.roll` 로 짜면 바닥이 상단
+ 키 행과 이웃이 되어 깊이 1 -> unmix 된다. (가장자리를 clip 하는 구현은 등가다 —
+ clip 이 만드는 좌표는 `dx = 0` / `dy = 0` 으로 어차피 도달하는 칸이다.)
+
+ 두 블렌드 픽셀 모두 tint 35 다 — 40 이하라 스필 패스가 손대지 않으므로
+ **unmix 되었는가만** 관측된다.
+ """
+ img = Image.new("RGBA", (width, height), (200, 40, 180, 255)) # 피험체 바탕
+ px = img.load()
+ for x in range(width): # 키 배경은 상단 1행뿐
+ px[x, 0] = (11 + ((x * 3) % 5), 238 - (x % 7), 27, 255)
+ px[10, 15] = (13, 235, 29, 255) # 피험체 안쪽 키 구멍 (머리카락 틈)
+ px[14, 16] = (150, 120, 20, 255) # 오프셋 (4, 1) — 체비셰프 깊이 4
+ px[25, 27] = (150, 120, 20, 255) # 바닥 행 — wrap 구현에서만 깊이 1
+ return img
+
+
+def _synthetic_transparent_spill_field(width: int = 40, height: int = 30) -> Image.Image:
+ """스필 후보 루프의 `if not alpha: continue` 를 잠근다 (노드 3 추가).
+
+ 이 스킵은 **`fringe_delta > 0` 일 때만** 무의미하다: P1 이 지운 픽셀은 전부
+ `(0, 0, 0, 0)` 이고 그 tint 는 0 이라 `tint >= fringe_delta` 에서 걸러지기
+ 때문이다. 그런데 `--fringe-delta` 는 하한 없는 `type=float` CLI 플래그이고
+ `slice_sheet`·`inspect`·`cutout` 까지 그대로 흘러간다. `0` 을 주면 지워진
+ 픽셀이 전부 후보가 되고, **강한 틴트 클러스터에 붙어 있으면 클러스터가 배경
+ 전체와 이어져 한도를 넘겨** 진짜 스필이 치료를 면한다.
+
+ 그래서 투명 24px 를 강한 틴트 24px **바로 옆에** 붙여 두고 이 케이스만
+ `fringe_delta = 0.0` 으로 돌린다. 스킵을 지운 구현은 여기서 갈린다.
+ (노드 3 1라운드에서는 이 mutant 가 살아남았고, 등가라고 논증할 뻔했다 —
+ 적대적 코퍼스 차분이 `fringe_delta = 0` 에서 29건의 차이를 찾아냈다.)
+ """
+ img = Image.new("RGBA", (width, height), (11, 238, 27, 255))
+ px = img.load()
+ for y in range(8, 24):
+ for x in range(8, 32):
+ px[x, y] = (200, 40, 180, 255) # 피험체 (tint -150 → fringe_delta 0 에서도 subject)
+ for y in range(14, 18):
+ for x in range(14, 20):
+ px[x, y] = (120, 200, 90, 255) # 강한 틴트 24px (tint 95)
+ for y in range(14, 18):
+ for x in range(20, 26):
+ px[x, y] = (0, 0, 0, 0) # 거기 붙은 투명 24px
+ return img
+
+
+def _synthetic_classification_priority_field(width: int = 44, height: int = 32) -> Image.Image:
+ """P1 분류 if/elif 의 **우선순위**를 잠근다 (노드 3 attempt 2, R1).
+
+ `key_tint_score < fringe_delta -> _SUBJECT` 와
+ `color_distance <= fringe_threshold -> _BLEND_IN_BAND` 의 순서를 맞바꾼 mutant 는
+ **두 조건이 동시에 참인 픽셀**이 있어야만 관측된다. 기본 CLI 값에서는 그런 픽셀이
+ 존재할 수 없다 — 포화 2채널 키에서 교집합이 생기려면 코시-슈바르츠 상한
+ `sqrt(1.5) * T > 255 - delta` 를 넘어야 하는데 `T=180, delta=18` 이면
+ `220.4 vs 237` 로 **공집합**이다. 임계는 `T > 193.5`.
+ `--fringe-key-threshold` 는 상한 없는 `type=float` CLI 플래그이고
+ (`sprite_gen/cli.py:88,173,189`, `inspect.py:38`, 기본 180.0)
+ `slice_sheet`·`inspect`·`cutout` 까지 그대로 흘러간다 — 도달 가능한 설정이다.
+ 그래서 이 케이스만 `fringe_threshold` 를 **196.0** 으로 둔다.
+
+ if/elif 사슬을 벡터화하는 표준 수단이 `np.select`/중첩 `np.where` 이고, 그 변환에서
+ 유일하게 사람이 손으로 정하는 값이 **조건 우선순위**다. 잠글 자리가 바로 여기다.
+
+ 충돌 픽셀 `(80, 95, 80)`: 키 거리 195.959 <= 196, tint 15.0 < 18.
+ - 원본 순서: `_SUBJECT` — unmix 패스가 건드리지 않아 `(80, 95, 80, 255)` 유지
+ - 순서 교환: `_BLEND_IN_BAND` — depth <= 2 라 unmix 되어 `(85, 85, 85, 240)`
+
+ `_REF_IN_BAND_UNMIX_KEY_DEPTH` 가 2 라 깊이 3 이상이면 in-band 도 건너뛰어져
+ 차이가 사라진다. 그래서 피험체 블록 왼쪽 모서리에 붙여 깊이 1·2 만 쓴다
+ (`(12,11)`·`(12,12)` = 깊이 1, `(13,11)` = 깊이 2).
+
+ unmix 뒤 색은 `(85, 85, 85)` 라 tint 0 이고 원본도 tint 15 < 18 이라, 두 갈래 모두
+ 스필 후보가 아니다 — 차이가 뒤 패스에서 씻기지 않고 출력까지 남는다.
+ """
+ img = Image.new("RGBA", (width, height), (0, 0, 0, 0))
+ px = img.load()
+ for y in range(height):
+ for x in range(width):
+ # 흔들리는 키 배경 (거리 33.7~41.4 <= 96 → 전부 keyed)
+ px[x, y] = (11 + ((x * 3) % 5), 238 - ((x + y) % 7), 27 + ((y * 2) % 5), 255)
+ for y in range(10, 24):
+ for x in range(12, 32):
+ px[x, y] = (200, 40, 180, 255) # 피험체 (거리 344.4, tint -150 → subject)
+ for x, y in ((12, 11), (12, 12), (13, 11)):
+ px[x, y] = (80, 95, 80, 255) # 충돌 픽셀 — 거리 195.959, tint 15.0
+ return img
+
+
+def _synthetic_negative_fringe_delta_field(width: int = 32, height: int = 24) -> Image.Image:
+ """되쓰기의 **0..255 클램프**를 잠근다 (노드 7 attempt 2, R1).
+
+ 옛 스칼라 경로는 `pixels[x, y] = unmix_key_blend(...)` 로 PIL 에 넣었고 PIL 이
+ 범위 밖 채널을 클램프했다. 벡터화 경로는 uint8 배열에 직접 대입이라 numpy 가
+ **던진다** — `OverflowError: Python integer 257 out of bounds for uint8`.
+
+ `out_alpha > 255` 가 되는 조건은 정확히 하나다: `fringe_delta < 0` 이면 tint 가
+ 음수인 픽셀이 `_SUBJECT` 로 안 빠지고 블렌드로 분류되고, `k = tint/key_tint < 0`
+ → `coverage = 1 - k > 1` → `round(alpha * coverage) > alpha` 가 된다.
+ `fringe_delta >= 0` 이면 블렌드는 tint >= 0 뿐이라 `coverage <= 1` 이다 —
+ 그래서 기존 13 케이스(delta 18.0·0.0)는 이 자리를 **한 번도 안 밟는다.**
+
+ `--fringe-delta` 는 하한 없는 `type=float` CLI 플래그이고 진입점이 5자리다
+ (`sprite_gen/cli.py:89,174,190`, `inspect.py:39`, `slice_sheet.py:315`) —
+ `slice_sheet --fringe-delta=-5` 로 CLI 에서 그대로 도달한다. 노드 3 §C 가
+ `fringe_delta = 0` 을 등가 논증 대신 픽스처로 처리하고 노드 3 R1 이
+ `--fringe-key-threshold > 193.5` 를 블로킹으로 판정한 것과 같은 형태다.
+
+ 그래서 이 케이스만 `fringe_delta = -5.0` 으로 돌린다. **넘침의 크기는 delta 가
+ 가둔다** — 블렌드로 분류되려면 `tint >= fringe_delta` 여야 하므로 tint 는
+ `[-5, 0)` 뿐이고 `coverage <= 1 + 5/255`, 즉 알파 255 픽셀의 상한이 260 이다.
+ 심은 픽셀 6종은 그 창 안에서 클램프 경계와 대조군을 같이 덮는다
+ (키 `(0, 255, 0)`, `key_tint = 255`):
+
+ | 좌표 | 입력 | tint | 분류 | out_alpha | 되쓰기 | 잡는 변형 |
+ |----------|---------------------|------:|----------|----------:|-------:|-----------|
+ | (10, 9) | `(60,58,60,255)` | -2.0 | out-band | 257 | 255 | 클램프 삭제 → OverflowError |
+ | (10, 11) | `(60,59,60,255)` | -1.0 | out-band | 256 | 255 | `min(256, …)` 오프바이원 |
+ | (10, 13) | `(60,56,60,255)` | -4.0 | out-band | 259 | 255 | `% 256` wrap (→ 3) |
+ | (10, 15) | `(60,58,60,200)` | -2.0 | out-band | 202 | 202 | `out_alpha = 255` 무조건 대입 / `min(alpha, …)` |
+ | (10, 17) | `(120,200,90,255)` | 95.0 | in-band | 160 | 160 | 양수 tint 경로 동반 회귀 |
+ | (10, 19) | `(60,55,60,255)` | -5.0 | out-band | 260 | 255 | 음수 경계의 `< fringe_delta` → `<=` (피험체로 새면 무변경) |
+
+ 여섯 자리 모두 피험체 블록의 왼쪽 열이라 keyed 배경과 붙어 **깊이 1** 이고,
+ (10, 17) 을 뺀 다섯은 키 거리 213.6~217.3 > 180 이라 `_BLEND_OUT_OF_BAND` 다 —
+ in-band 깊이 제한(`_IN_BAND_UNMIX_KEY_DEPTH`)과 무관하게 unmix 된다. (10, 17) 은
+ 거리 159.8 로 in-band 이고 깊이 1 <= 2 라 역시 unmix 된다.
+
+ 블록 본체 `(200, 40, 180)` 은 tint -150 < -5 라 음수 delta 에서도 `_SUBJECT` 로
+ 남는다 — 이 케이스의 피험체 대조군이 그것이다.
+
+ unmix 뒤 색은 전부 tint 0 (회색) 이라 스필 후보로는 잡히되 `_SPILL_MIN_TINT`
+ 40 이하라 치료되지 않는다 — 차이가 뒤 패스에서 씻기지 않고 출력까지 남는다.
+ 행 간격을 2로 벌려 여섯 픽셀이 서로 8-이웃이 아니게 두었다: 각자 1px 클러스터라
+ 스필 패스의 판정이 픽셀마다 독립이고 기대표가 흔들리지 않는다.
+ """
+ img = Image.new("RGBA", (width, height), (0, 0, 0, 0))
+ px = img.load()
+ for y in range(height):
+ for x in range(width):
+ # 흔들리는 키 배경 (거리 33.7~41.4 <= 96 → 전부 keyed)
+ px[x, y] = (11 + ((x * 3) % 5), 238 - ((x + y) % 7), 27 + ((y * 2) % 5), 255)
+ for y in range(8, 21):
+ for x in range(10, 24):
+ px[x, y] = (200, 40, 180, 255) # 피험체 (거리 344.4, tint -150 → delta -5 에서도 subject)
+ px[10, 9] = (60, 58, 60, 255) # coverage 1.0078 → 257
+ px[10, 11] = (60, 59, 60, 255) # coverage 1.0039 → 256 (클램프 경계 정확히 +1)
+ px[10, 13] = (60, 56, 60, 255) # coverage 1.0157 → 259
+ px[10, 15] = (60, 58, 60, 200) # 같은 coverage, 알파가 낮아 202 — 클램프 미적용 대조군
+ px[10, 17] = (120, 200, 90, 255) # 양수 tint 95 → coverage 0.6275 → 160
+ px[10, 19] = (60, 55, 60, 255) # tint 가 정확히 fringe_delta — coverage 1.0196 → 260
+ return img
+
+
+# (case id, image builder, key, threshold, fringe_threshold, fringe_delta, reach, spill_fraction)
+CASES = [
+ ("moe-magenta", lambda: _open_moe("moe_green.png"), MAGENTA,
+ CLI_KEY_THRESHOLD, CLI_FRINGE_THRESHOLD, CLI_FRINGE_DELTA, CLI_UNMIX_REACH, CLI_SPILL_MAX_FRACTION),
+ ("moe-green", lambda: _open_moe("moe_red.png"), GREEN,
+ CLI_KEY_THRESHOLD, CLI_FRINGE_THRESHOLD, CLI_FRINGE_DELTA, CLI_UNMIX_REACH, CLI_SPILL_MAX_FRACTION),
+ ("synthetic-cli-defaults", _synthetic_branch_field, GREEN,
+ CLI_KEY_THRESHOLD, CLI_FRINGE_THRESHOLD, CLI_FRINGE_DELTA, CLI_UNMIX_REACH, CLI_SPILL_MAX_FRACTION),
+ ("synthetic-no-unmix", _synthetic_branch_field, GREEN,
+ CLI_KEY_THRESHOLD, CLI_FRINGE_THRESHOLD, CLI_FRINGE_DELTA, 0, CLI_SPILL_MAX_FRACTION),
+ ("synthetic-no-spill", _synthetic_branch_field, GREEN,
+ CLI_KEY_THRESHOLD, CLI_FRINGE_THRESHOLD, CLI_FRINGE_DELTA, CLI_UNMIX_REACH, 0.0),
+ ("synthetic-degenerate-tint", _synthetic_branch_field, (128, 128, 128),
+ CLI_KEY_THRESHOLD, CLI_FRINGE_THRESHOLD, CLI_FRINGE_DELTA, CLI_UNMIX_REACH, CLI_SPILL_MAX_FRACTION),
+ ("synthetic-zero-coverage", _synthetic_zero_coverage, (0, 200, 0),
+ 20.0, CLI_FRINGE_THRESHOLD, CLI_FRINGE_DELTA, CLI_UNMIX_REACH, CLI_SPILL_MAX_FRACTION),
+ ("synthetic-fraction-spill-limit", _synthetic_fraction_limit_field, GREEN,
+ CLI_KEY_THRESHOLD, CLI_FRINGE_THRESHOLD, CLI_FRINGE_DELTA, CLI_UNMIX_REACH, CLI_SPILL_MAX_FRACTION),
+ ("synthetic-threshold-boundaries", _synthetic_threshold_boundary_field, GREEN,
+ CLI_KEY_THRESHOLD, CLI_FRINGE_THRESHOLD, CLI_FRINGE_DELTA, CLI_UNMIX_REACH, CLI_SPILL_MAX_FRACTION),
+ ("synthetic-spill-semantics", _synthetic_spill_semantics_field, GREEN,
+ CLI_KEY_THRESHOLD, CLI_FRINGE_THRESHOLD, CLI_FRINGE_DELTA, CLI_UNMIX_REACH, CLI_SPILL_MAX_FRACTION),
+ ("synthetic-reach-geometry", _synthetic_reach_geometry_field, GREEN,
+ CLI_KEY_THRESHOLD, CLI_FRINGE_THRESHOLD, CLI_FRINGE_DELTA, CLI_UNMIX_REACH, CLI_SPILL_MAX_FRACTION),
+ # 유일하게 fringe_delta 를 0 으로 두는 케이스 — 픽스처 docstring 에 이유가 있다
+ ("synthetic-transparent-spill", _synthetic_transparent_spill_field, GREEN,
+ CLI_KEY_THRESHOLD, CLI_FRINGE_THRESHOLD, 0.0, CLI_UNMIX_REACH, CLI_SPILL_MAX_FRACTION),
+ # 유일하게 fringe_threshold 를 기본값 위로 올리는 케이스 (196.0 > 193.5 임계).
+ # 기본 180.0 에서는 subject/in-band 조건의 교집합이 공집합이라 분류 우선순위가
+ # 관측 불가다 — 픽스처 docstring 에 유도가 있다.
+ ("synthetic-classification-priority", _synthetic_classification_priority_field, GREEN,
+ CLI_KEY_THRESHOLD, 196.0, CLI_FRINGE_DELTA, CLI_UNMIX_REACH, CLI_SPILL_MAX_FRACTION),
+ # 유일하게 fringe_delta 를 **음수**로 두는 케이스. 되쓰기의 0..255 클램프는
+ # 여기서만 관측된다 — 나머지 13 케이스는 delta 18.0·0.0 이라 coverage <= 1 이다.
+ ("synthetic-negative-fringe-delta", _synthetic_negative_fringe_delta_field, GREEN,
+ CLI_KEY_THRESHOLD, CLI_FRINGE_THRESHOLD, -5.0, CLI_UNMIX_REACH, CLI_SPILL_MAX_FRACTION),
+]
+
+# 절대 잠금 — 프로덕션과 참조를 **같이** 고쳐 1번 잠금을 우회하는 경로를 막는다.
+# 값은 최적화 전 커밋(engine_revision 3adf0169561a)에서 뽑았다.
+EXPECTED_OUTPUT_SHA256 = {
+ "moe-magenta": "e987f14173a4ca102ad4e4b8ffbe13379ada43149f84c678fcd2d57b227fabbc",
+ "moe-green": "674709d6f773f0f0e84219a518d4a8c121a9e047d57f2c286da4bc3b4e6f73e0",
+ "synthetic-cli-defaults": "734f377991d3987ebbbd711b42b9ec99f7de86ca3cf9cf5be6d7f22b6bbf6821",
+ "synthetic-no-unmix": "1c667d0d0f01498e69afea8ce2ebb47dae890433b1cbeb0ecf8f2fa264bbc68d",
+ "synthetic-no-spill": "7426d33bfc6956db63e5818b5f0af38adedc1ac9b736091696957cbbb49c9520",
+ "synthetic-degenerate-tint": "249ceacd332f509d978e96b38080d7f9663ffa08eb2088494f385d490309f572",
+ "synthetic-zero-coverage": "32b2bdfc5d97d8ad7b97cc5f0da65bd5cd1be19ac6c4a4016c1f5bc69a48f762",
+ "synthetic-fraction-spill-limit": "262fd62b164365c23a6505da8ce025b8d38841c572dbf13c2781a94757da898c",
+ "synthetic-threshold-boundaries": "e1c84624a9a497595fe0f7db45a242e94d97e168935b24a0ffb347aee681d82a",
+ # 노드 3 추가분. 같은 최적화 전 엔진(`extract.py` 무변경, engine_revision
+ # 3adf0169561a)에서 뽑았다 — 위 7개와 같은 기준선이다.
+ "synthetic-spill-semantics": "ef45e6c84f334c8925c9e0df6be3a1beecfa6b59cec7611bbeb1b65af8fae2d1",
+ "synthetic-reach-geometry": "0d5030be40603283ea3e9743b2c1e069481b9ae38695bc99d50ec4c75415cf5f",
+ "synthetic-transparent-spill": "62309e999d53448eaab201e023cf24e734a1c780fc5d5287f0176eb755eafebf",
+ # 노드 3 attempt 2(R1) 추가분. 같은 기준선이다 — `extract.py` 는 노드 3 내내
+ # 무변경이고(engine_revision 3adf0169561a) 이 커밋에서도 손대지 않았다.
+ "synthetic-classification-priority": "65f0961c7e4a9a6cc98b2ec2f1bfd08d3341fff1df8b8576ce8fa1f71f41be03",
+ # 노드 7 attempt 2(R1) 추가분. 위 13개는 최적화 전 커밋에서 뽑았고 이 값도 같은
+ # 기준선이다 — **동결 사본이 아니라 `git show 05c549a:sprite_gen/frames/extract.py` 로
+ # 뽑은 그때 실제로 돌던 모듈**에 이 픽스처를 먹여 얻었다(하네스
+ # `_assets/extract-numpy-vectorization/probe_negative_delta_case.py`).
+ # 클램프를 잃은 4ae7d70 은 이 케이스에서 해시를 내지 못한다 — OverflowError 로
+ # 죽는다. 그래서 이 한 줄은 "값이 다르다" 가 아니라 "돌긴 하는가" 까지 잠근다.
+ "synthetic-negative-fringe-delta": "8711c53554807c59714d1d6485ac107e234e8530e895475afbc474a4bc363b9b",
+}
+
+# 분기 도달 계측 고정 — 픽스처가 조용히 분기를 잃으면 여기서 걸린다.
+EXPECTED_COVERAGE = {
+ "moe-magenta": {
+ "blend_in_band": 101,
+ "blend_out_of_band": 48,
+ "degenerate_key_tint": 0,
+ "depth_positive": 3158,
+ "depth_reached_max": 1,
+ "keyed_by_distance": 18312,
+ "spill_candidates": 11,
+ "spill_cluster_low_tint": 10,
+ "spill_cluster_treated": 1,
+ "spill_limit_from_fraction": 0,
+ "spill_treated_px": 1,
+ "subject": 6115,
+ "unmix_collapsed_to_transparent": 0,
+ "unmix_in_band": 100,
+ "unmix_in_band_skipped_deep": 1,
+ "unmix_out_of_band": 38,
+ },
+ "moe-green": {
+ "blend_in_band": 60,
+ "blend_out_of_band": 40,
+ "degenerate_key_tint": 0,
+ "depth_positive": 3051,
+ "depth_reached_max": 1,
+ "keyed_by_distance": 18614,
+ "spill_candidates": 1,
+ "spill_cluster_treated": 1,
+ "spill_limit_from_fraction": 0,
+ "spill_treated_px": 1,
+ "subject": 5862,
+ "unmix_collapsed_to_transparent": 0,
+ "unmix_in_band": 59,
+ "unmix_in_band_skipped_deep": 1,
+ "unmix_out_of_band": 40,
+ },
+ "synthetic-cli-defaults": {
+ "blend_in_band": 833,
+ "blend_out_of_band": 118,
+ "degenerate_key_tint": 0,
+ "depth_positive": 768,
+ "depth_reached_max": 1,
+ "keyed_alpha_zero": 192,
+ "keyed_by_distance": 4032,
+ "spill_candidates": 559,
+ "spill_cluster_low_tint": 2,
+ "spill_cluster_too_big": 2,
+ "spill_cluster_treated": 3,
+ "spill_limit_from_fraction": 0,
+ "spill_treated_px": 22,
+ "subject": 1737,
+ "unmix_collapsed_to_transparent": 0,
+ "unmix_in_band": 392,
+ "unmix_in_band_skipped_deep": 360,
+ "unmix_out_of_band": 16,
+ },
+ "synthetic-no-unmix": {
+ "blend_in_band": 833,
+ "blend_out_of_band": 118,
+ "degenerate_key_tint": 0,
+ "depth_positive": 0,
+ "depth_reached_max": 0,
+ "keyed_alpha_zero": 192,
+ "keyed_by_distance": 4032,
+ "spill_candidates": 951,
+ "spill_cluster_low_tint": 2,
+ "spill_cluster_too_big": 2,
+ "spill_cluster_treated": 3,
+ "spill_limit_from_fraction": 0,
+ "spill_treated_px": 22,
+ "subject": 1737,
+ },
+ "synthetic-no-spill": {
+ "blend_in_band": 833,
+ "blend_out_of_band": 118,
+ "degenerate_key_tint": 0,
+ "depth_positive": 768,
+ "depth_reached_max": 1,
+ "keyed_alpha_zero": 192,
+ "keyed_by_distance": 4032,
+ "subject": 1737,
+ "unmix_collapsed_to_transparent": 0,
+ "unmix_in_band": 392,
+ "unmix_in_band_skipped_deep": 360,
+ "unmix_out_of_band": 16,
+ },
+ "synthetic-degenerate-tint": {
+ "degenerate_key_tint": 1,
+ "depth_positive": 0,
+ "depth_reached_max": 0,
+ "keyed_alpha_zero": 192,
+ "keyed_by_distance": 996,
+ "subject": 5724,
+ },
+ "synthetic-zero-coverage": {
+ "blend_in_band": 53,
+ "degenerate_key_tint": 0,
+ "depth_positive": 308,
+ "depth_reached_max": 1,
+ "keyed_by_distance": 756,
+ "spill_candidates": 9,
+ "spill_cluster_treated": 1,
+ "spill_limit_from_fraction": 0,
+ "spill_treated_px": 9,
+ "spill_zero_coverage": 9,
+ "subject": 471,
+ "unmix_collapsed_to_transparent": 44,
+ "unmix_in_band": 44,
+ },
+ "synthetic-fraction-spill-limit": {
+ "blend_in_band": 745,
+ "degenerate_key_tint": 0,
+ "depth_positive": 1488,
+ "depth_reached_max": 1,
+ "keyed_by_distance": 7280,
+ "spill_candidates": 41,
+ "spill_cluster_treated": 1,
+ "spill_limit_from_fraction": 1,
+ "spill_treated_px": 41,
+ "subject": 7375,
+ "unmix_collapsed_to_transparent": 0,
+ "unmix_in_band": 704,
+ },
+ "synthetic-threshold-boundaries": {
+ "blend_in_band": 8,
+ "blend_out_of_band": 6,
+ "degenerate_key_tint": 0,
+ "depth_positive": 67,
+ "depth_reached_max": 1,
+ "keyed_alpha_zero": 1,
+ "keyed_by_distance": 1852,
+ "spill_candidates": 2,
+ "spill_cluster_treated": 1,
+ "spill_limit_from_fraction": 0,
+ "spill_treated_px": 2,
+ "subject": 53,
+ "unmix_collapsed_to_transparent": 0,
+ "unmix_in_band": 6,
+ "unmix_in_band_skipped_deep": 2,
+ "unmix_out_of_band": 6,
+ },
+ # 노드 3 추가분. `subject 7928 + 61 + 11 == 8000` 이 스필 한도 산식의 입력이고,
+ # `treated 2 / too_big 1 / treated_px 12` 가 max-vs-mean·한도 갈음 mutant 를
+ # 잡는 구성이다 — 이 숫자가 흔들리면 그 mutant 들이 다시 살아난다.
+ "synthetic-spill-semantics": {
+ "blend_in_band": 61,
+ "blend_out_of_band": 11,
+ "degenerate_key_tint": 0,
+ "depth_positive": 1376,
+ "depth_reached_max": 1,
+ "keyed_by_distance": 11200,
+ "spill_candidates": 72,
+ "spill_cluster_too_big": 1,
+ "spill_cluster_treated": 2,
+ "spill_limit_from_fraction": 1,
+ "spill_treated_px": 12,
+ "subject": 7928,
+ },
+ # `unmix_out_of_band == 1` 이 이 케이스의 전부다 — 깊이 4 짜리 블렌드 픽셀
+ # 하나가 unmix 되고 바닥 행 픽셀은 도달하지 않는다는 사실 자체가 단정이다.
+ "synthetic-reach-geometry": {
+ "blend_out_of_band": 2,
+ "degenerate_key_tint": 0,
+ "depth_positive": 240,
+ "depth_reached_max": 1,
+ "keyed_by_distance": 41,
+ "spill_candidates": 1,
+ "spill_cluster_low_tint": 1,
+ "spill_limit_from_fraction": 0,
+ "subject": 1077,
+ "unmix_collapsed_to_transparent": 0,
+ "unmix_out_of_band": 1,
+ },
+ # `keyed_alpha_zero 24` 가 `spill_candidates 24` 에 **안 섞여 있다**는 것이
+ # 이 케이스의 단정이다 — 스킵을 지우면 후보가 배경 전체로 번져 클러스터가
+ # 한도를 넘고 `spill_cluster_treated` 가 0 이 된다.
+ "synthetic-transparent-spill": {
+ "blend_in_band": 24,
+ "degenerate_key_tint": 0,
+ "depth_positive": 328,
+ "depth_reached_max": 1,
+ "keyed_alpha_zero": 24,
+ "keyed_by_distance": 816,
+ "spill_candidates": 24,
+ "spill_cluster_treated": 1,
+ "spill_limit_from_fraction": 0,
+ "spill_treated_px": 24,
+ "subject": 336,
+ "unmix_collapsed_to_transparent": 0,
+ "unmix_in_band": 8,
+ "unmix_in_band_skipped_deep": 8,
+ },
+ # 이 케이스가 고정하는 것은 **분기 도달이 아니라 미도달**이다: `blend_in_band` 와
+ # `unmix_*` 가 아예 없다. 충돌 픽셀 3개가 전부 `subject 280` 안에 들어 있고 unmix
+ # 패스가 아무것도 안 한다 — 그래서 우선순위를 뒤집은 프로덕션이 그 3개를 unmix 하면
+ # 출력 바이트가 갈린다. (이 표는 참조 구현으로 재는 픽스처측 가드라 프로덕션
+ # mutant 로는 안 빨개진다. 잠그는 것은 픽스처가 조용히 이 구도를 잃는 경우다 —
+ # 충돌 픽셀이 subject 를 벗어나면 `subject 280` 이 어긋나 여기서 걸린다.)
+ "synthetic-classification-priority": {
+ "degenerate_key_tint": 0,
+ "depth_positive": 208,
+ "depth_reached_max": 1,
+ "keyed_by_distance": 1128,
+ "spill_candidates": 0,
+ "spill_limit_from_fraction": 0,
+ "subject": 280,
+ },
+ # `unmix_alpha_over_255: 4` 가 이 케이스의 본체다 — 이 계수는 **여기에만** 있고
+ # (조건부 bump 라 나머지 12 케이스에는 키 자체가 없다) 되쓰기 클램프가 실제로
+ # 일하는 픽셀 수를 센다. 픽스처가 조용히 그 4자리를 잃으면
+ # `test_every_branch_is_reached_by_some_case` 가 먼저 빨개진다.
+ # `blend_out_of_band 5 / unmix_out_of_band 5` 는 심은 6종 중 (10,17) 을 뺀 다섯이고,
+ # `subject 176` 은 블록 본체(음수 delta 에서도 피험체로 남는 대조군)다.
+ "synthetic-negative-fringe-delta": {
+ "blend_in_band": 1,
+ "blend_out_of_band": 5,
+ "degenerate_key_tint": 0,
+ "depth_positive": 152,
+ "depth_reached_max": 1,
+ "keyed_by_distance": 586,
+ "spill_candidates": 6,
+ "spill_cluster_low_tint": 6,
+ "spill_limit_from_fraction": 0,
+ "subject": 176,
+ "unmix_alpha_over_255": 4,
+ "unmix_collapsed_to_transparent": 0,
+ "unmix_in_band": 1,
+ "unmix_out_of_band": 5,
+ },
+}
+
+
+def _case_params(case):
+ return dict(zip(
+ ("threshold", "fringe_threshold", "fringe_delta", "unmix_reach", "spill_max_fraction"),
+ case[3:],
+ ))
+
+
+def _run_production(case, image=None):
+ """`image` 를 주면 **그 이미지 객체 그대로** 넘긴다 — 입력 불변 단정은 자기가
+ 들고 있는 객체가 들어가야 성립한다 (노드 3: 매번 새로 빌드하면 공허해진다)."""
+ _, builder, key, threshold, fringe_threshold, fringe_delta, reach, spill = case
+ return extract.remove_chroma_background(
+ builder() if image is None else image,
+ key, threshold, fringe_threshold, fringe_delta,
+ unmix_reach=reach, spill_max_fraction=spill,
+ )
+
+
+def _run_reference(case, counters=None):
+ _, builder, key, threshold, fringe_threshold, fringe_delta, reach, spill = case
+ return _ref_remove_chroma_background(
+ builder(), key, threshold, fringe_threshold, fringe_delta,
+ unmix_reach=reach, spill_max_fraction=spill, counters=counters,
+ )
+
+
+def _sha256(image: Image.Image) -> str:
+ return hashlib.sha256(image.tobytes()).hexdigest()
+
+
+# --- 프리미티브: 프로덕션 vs 동결 사본 --------------------------------------
+
+# 결정론 스윕 — 임계 경계(63/64, 191/192)와 채널 극단을 모두 포함한다
+_SWEEP = (0, 1, 17, 63, 64, 127, 128, 191, 192, 254, 255)
+# 마지막 두 키는 `key_tint_score` 의 **채널 선택 임계 자체**를 밟는 자리다 (노드 3).
+# 색 쪽 스윕만으로는 `value >= 192` -> `> 192`, `value < 64` -> `<= 64` 가 안 잠긴다 —
+# 채널값이 정확히 192·64 인 키가 없으면 두 연산자가 같은 채널 집합을 고른다.
+# (192, 255, 0): keyed 가 [0, 1] vs [1] 로 갈린다
+# (0, 255, 64): unkeyed 가 [0] vs [0, 2] 로 갈린다
+_KEYS = [
+ GREEN, MAGENTA, (0, 255, 255), (255, 255, 0), (11, 238, 27), (0, 200, 0),
+ (255, 255, 255), (0, 0, 0), (128, 128, 128), (200, 255, 30),
+ (192, 255, 0), (0, 255, 64),
+]
+# 축퇴 키 — 키 채널이 아예 없거나(전부 어두움) 언키 채널이 아예 없다(전부 밝음).
+# 두 방향이 다 있어야 `_key_channel_split` 의 가드가 양쪽에서 잠긴다: 한쪽 항만
+# 남기면 나머지 방향에서 0 나눗셈이 샌다.
+_DEGENERATE_KEYS = [(128, 128, 128), (255, 255, 255), (0, 0, 0), (200, 200, 200), (63, 63, 63)]
+
+
+def test_color_distance_matches_frozen_scalar_reference():
+ """1,331 색 x 10 키 전수 — 근사 아니라 정확한 float 동일."""
+ checked = 0
+ for key in _KEYS:
+ for red in _SWEEP:
+ for green in _SWEEP:
+ for blue in _SWEEP:
+ color = (red, green, blue)
+ got = extract.color_distance(color, key)
+ ref = _ref_color_distance(color, key)
+ assert got == ref, f"key={key} color={color}: {got!r} != {ref!r}"
+ checked += 1
+ assert checked == len(_KEYS) * len(_SWEEP) ** 3
+
+
+def test_key_tint_score_matches_frozen_scalar_reference():
+ checked = 0
+ for key in _KEYS:
+ for red in _SWEEP:
+ for green in _SWEEP:
+ for blue in _SWEEP:
+ color = (red, green, blue)
+ got = extract.key_tint_score(color, key)
+ ref = _ref_key_tint_score(color, key)
+ assert got == ref, f"key={key} color={color}: {got!r} != {ref!r}"
+ checked += 1
+ assert checked == len(_KEYS) * len(_SWEEP) ** 3
+
+
+def test_key_tint_score_returns_zero_for_degenerate_keys():
+ """축퇴 키(키 채널 없음 / 언키 채널 없음)는 0.0 — 이 값이
+ `remove_chroma_background` 의 unmix·spill 패스 전체를 끄는 스위치다."""
+ for key in _DEGENERATE_KEYS:
+ assert extract.key_tint_score((10, 200, 30), key) == 0.0
+ assert _ref_key_tint_score((10, 200, 30), key) == 0.0
+
+
+def test_despill_and_unmix_match_frozen_scalar_reference():
+ """despill/unmix 는 벡터화 대상 안쪽의 산수라 별도로 고정한다."""
+ key = GREEN
+ key_tint = _ref_key_tint_score(key, key)
+ for red in _SWEEP:
+ for green in _SWEEP:
+ for blue in _SWEEP:
+ color = (red, green, blue)
+ tint = _ref_key_tint_score(color, key)
+ if tint <= 0:
+ continue
+ for alpha in (1, 17, 128, 254, 255):
+ assert extract.despill_color(color, key, key_tint, tint) == \
+ _ref_despill_color(color, key, key_tint, tint)
+ assert extract.unmix_key_blend(color, alpha, key, key_tint, tint) == \
+ _ref_unmix_key_blend(color, alpha, key, key_tint, tint)
+
+
+# --- 음수 tint 영역: 되쓰기 클램프가 기대는 두 전제 --------------------------
+# 위 스윕은 `tint <= 0` 을 건너뛴다. 그 영역이 `--fringe-delta < 0` 에서 블렌드로
+# 분류되는 자리이고, `coverage = 1 - tint/key_tint > 1` 이라 `round(alpha*coverage)`
+# 가 알파를 **키운다** — 옛 경로는 그걸 PIL 이 조여서 넣었고 배열 되쓰기는 던진다.
+# 프로덕션 되쓰기가 알파 **하나만**, **위로만** 조이는 근거가 아래 두 단정이다.
+# 둘 다 프로덕션 프리미티브를 재는 것이지 동결 사본을 재는 게 아니다.
+
+
+def _sweep_tints(key):
+ """스칼라 스윕 1,331 색을 tint 부호로 갈라 준다."""
+ key_tint = _ref_key_tint_score(key, key)
+ negative, positive = [], []
+ for red in _SWEEP:
+ for green in _SWEEP:
+ for blue in _SWEEP:
+ color = (red, green, blue)
+ tint = _ref_key_tint_score(color, key)
+ (negative if tint <= 0 else positive).append((color, tint))
+ return key_tint, negative, positive
+
+
+def test_despill_color_channels_stay_in_byte_range():
+ """되쓰기가 RGB 를 다시 클램프하지 않는 근거 — `despill_color` 가 이미 조인다.
+
+ 두 영역 다 돈다. `k >= 0` 에서는 외삽이라 범위를 벗어날 수 있고
+ (`min(255, max(0, …))` 가 거기서 일한다), `k < 0` 에서는 색과 키의 볼록결합이라
+ 구조적으로 못 벗어난다. 이 단정이 빨개지면 되쓰기의 "알파 하나만" 전제가 깨진
+ 것이므로 클램프 자리를 다시 정해야 한다.
+ """
+ for key in (GREEN, MAGENTA):
+ key_tint, negative, positive = _sweep_tints(key)
+ assert negative and positive, f"{key}: 한쪽 영역이 비었다 — 스윕이 공허하다"
+ for color, tint in negative + positive:
+ _, despilled = extract.despill_color(color, key, key_tint, tint)
+ assert all(0 <= channel <= 255 for channel in despilled), \
+ f"key={key} color={color} tint={tint}: {despilled}"
+
+
+def test_unmix_key_blend_alpha_overflows_upward_only_for_negative_tint():
+ """되쓰기가 위쪽 한 방향만 조이는 근거 + 그 자리가 공허하지 않다는 근거.
+
+ - 알파는 절대 음수가 안 된다: `out_alpha <= 0` 이면 완전 투명으로 접힌다.
+ 그래서 되쓰기에 `max(0, …)` 가 없다.
+ - 알파는 음수 tint 에서 **실제로 255 를 넘는다**. 넘는 사례가 0이면 되쓰기
+ 클램프도, 게이트의 음수 delta 케이스도 아무것도 잠그지 않는 장식이 된다.
+ - 그 영역에서도 프로덕션 프리미티브는 동결 사본과 정확히 같은 값을 낸다 —
+ 클램프는 프리미티브가 아니라 되쓰기의 일이다 (프리미티브를 고치면 이 단정이
+ 빨개진다).
+ """
+ overflowed = 0
+ for key in (GREEN, MAGENTA):
+ key_tint, negative, _ = _sweep_tints(key)
+ for color, tint in negative:
+ for alpha in (0, 1, 17, 128, 200, 254, 255):
+ got = extract.unmix_key_blend(color, alpha, key, key_tint, tint)
+ assert got == _ref_unmix_key_blend(color, alpha, key, key_tint, tint)
+ assert got[3] >= 0, f"key={key} color={color} alpha={alpha}: {got}"
+ overflowed += got[3] > 255
+ assert overflowed > 0, "음수 tint 스윕이 알파 255 초과를 한 번도 안 냈다 — 공허하다"
+
+
+# --- 배열 커널: 프로덕션 vs 같은 동결 사본 ------------------------------------
+# `remove_chroma_background` 는 이제 픽셀마다 `color_distance`·`key_tint_score` 를
+# 부르지 않고 `_key_distance_field`·`_key_tint_field` 에 이미지를 통째로 넘긴다.
+# 위의 스칼라 스윕이 지키던 그 산수가 **이 함수들로 옮겨간 것**이라, 스윕도 같이
+# 옮긴다 — 안 옮기면 rcb 가 타는 경로는 픽스처 몇 장으로만 덮이고, float32 강등처럼
+# 임계에 정확히 걸리는 픽셀이 없으면 관측되지 않는 슬립이 조용히 통과한다
+# (노드 7 하네스에서 실제로 SURVIVED 로 재현한 뒤 이 두 단정을 넣었다).
+# 참조는 위와 **같은 동결 스칼라 사본**이므로 프로덕션을 따라 움직이지 않는다.
+
+
+def _sweep_color_field():
+ """스칼라 스윕과 같은 1,331 색을 (N, 1, 3) 배열 한 장으로."""
+ colors = [(red, green, blue) for red in _SWEEP for green in _SWEEP for blue in _SWEEP]
+ return colors, np.array(colors, dtype=np.int32).reshape(len(colors), 1, 3)
+
+
+def test_key_distance_field_matches_frozen_scalar_reference():
+ """1,331 색 x 12 키 전수 — 배열 쪽도 근사가 아니라 정확한 float 동일."""
+ colors, field = _sweep_color_field()
+ checked = 0
+ for key in _KEYS:
+ got = extract._key_distance_field(field, key)
+ assert got.dtype == np.float64, f"key={key}: {got.dtype} — float64 계약 위반"
+ for index, color in enumerate(colors):
+ ref = _ref_color_distance(color, key)
+ assert got[index, 0] == ref, f"key={key} color={color}: {got[index, 0]!r} != {ref!r}"
+ checked += 1
+ assert checked == len(_KEYS) * len(_SWEEP) ** 3
+
+
+def test_key_tint_field_matches_frozen_scalar_reference():
+ """축퇴 키까지 포함한다 — 배열 경로의 축퇴 스위치도 같은 자리에서 갈려야 한다."""
+ colors, field = _sweep_color_field()
+ checked = 0
+ for key in _KEYS + _DEGENERATE_KEYS:
+ keyed_channels, unkeyed_channels = extract._key_channel_split(key)
+ got = extract._key_tint_field(field, keyed_channels, unkeyed_channels)
+ assert got.dtype == np.float64, f"key={key}: {got.dtype} — float64 계약 위반"
+ for index, color in enumerate(colors):
+ ref = _ref_key_tint_score(color, key)
+ assert got[index, 0] == ref, f"key={key} color={color}: {got[index, 0]!r} != {ref!r}"
+ checked += 1
+ assert checked == (len(_KEYS) + len(_DEGENERATE_KEYS)) * len(_SWEEP) ** 3
+
+
+# --- remove_chroma_background: 바이트 동일 ---------------------------------
+
+
[email protected]("case", CASES, ids=[case[0] for case in CASES])
+def test_remove_chroma_background_byte_identical_to_frozen_reference(case):
+ got = _run_production(case)
+ ref = _run_reference(case)
+ assert got.size == ref.size
+ assert got.mode == ref.mode == "RGBA"
+ assert got.tobytes() == ref.tobytes(), f"{case[0]}: {_sha256(got)} != {_sha256(ref)}"
+
+
[email protected]("case", CASES, ids=[case[0] for case in CASES])
+def test_remove_chroma_background_matches_pinned_output_hash(case):
+ """절대 잠금 — 프로덕션과 동결 참조를 같이 고쳐도 여기서 걸린다."""
+ expected = EXPECTED_OUTPUT_SHA256[case[0]]
+ assert expected != "PENDING", "고정 해시가 비어 있다 — 게이트가 아니다"
+ assert _sha256(_run_production(case)) == expected
+ assert _sha256(_run_reference(case)) == expected
+
+
[email protected]("case", CASES, ids=[case[0] for case in CASES])
+def test_case_branch_coverage_is_pinned(case):
+ """픽스처가 어떤 분기를 실제로 밟는지 고정 — 통과만 하는 단정을 막는다."""
+ counters = {}
+ _run_reference(case, counters=counters)
+ assert counters == EXPECTED_COVERAGE[case[0]], f"{case[0]}: {counters}"
+
+
+def test_every_branch_is_reached_by_some_case():
+ """벡터화 대상 분기가 하나도 미도달로 남지 않는다 — 미도달 분기는 mutant 로
+ 검증할 수 없으므로(체크리스트 3번) 여기서 잡는다."""
+ required = {
+ "keyed_by_distance", "keyed_alpha_zero", "subject", "blend_in_band", "blend_out_of_band",
+ "depth_positive", "depth_reached_max", "unmix_in_band", "unmix_in_band_skipped_deep",
+ "unmix_out_of_band", "unmix_collapsed_to_transparent", "spill_candidates",
+ "spill_cluster_treated", "spill_cluster_too_big", "spill_cluster_low_tint",
+ "spill_limit_from_fraction", "degenerate_key_tint", "spill_zero_coverage",
+ # 되쓰기 클램프가 일하는 유일한 분기. 어느 픽스처도 알파 255 를 넘기지
+ # 않으면 클램프 단정 전체가 공허해지므로 여기서 미도달을 잡는다.
+ "unmix_alpha_over_255",
+ }
+ reached = {name for coverage in EXPECTED_COVERAGE.values()
+ for name, count in coverage.items() if count}
+ assert required <= reached, f"미도달 분기: {sorted(required - reached)}"
+
+
+def test_remove_chroma_background_does_not_mutate_its_input():
+ """`convert("RGBA")` 가 사본을 만든다는 계약. numpy 로 옮길 때 `np.asarray`
+ 뷰에 제자리 기록하면 조용히 깨지고, `slice_sheet`·`cutout` 은 입력 이미지를
+ 호출 뒤에도 들고 있다.
+
+ 노드 3 수리: 첫 판은 `source` 를 만들어 놓고 프로덕션에는 `builder()` 로 **새로
+ 빌드한 다른 객체**를 넘겨서, `rgba = image` (사본 미생성) mutant 가 그대로
+ 통과했다. 통과만 하는 단정이었다. 이제 들고 있는 객체를 그대로 넘긴다."""
+ for case in CASES:
+ source = case[1]()
+ before = source.tobytes()
+ result = _run_production(case, image=source)
+ assert result is not source, f"{case[0]}: 입력 객체를 그대로 반환했다"
+ assert source.tobytes() == before, f"{case[0]}: 입력이 변형됐다"
+
+
+# --- 티어 2 대상 (플랜 Scope 행에 포함) ------------------------------------
+
+
+def _cleaned_synthetic():
+ return _run_production(CASES[2])
+
+
+def _tier2_images():
+ """크로마 출력(실전 입력) + 경계값 픽스처(연산자 판정) 양쪽."""
+ return (_cleaned_synthetic(), _open_moe("moe_red.png"), _alpha_boundary_field())
+
+
+def test_connected_components_matches_frozen_scalar_reference():
+ for image in _tier2_images():
+ got = extract.connected_components(image)
+ ref = _ref_connected_components(image)
+ assert len(got) == len(ref) and got, "성분이 0개면 픽스처가 무의미하다"
+ for left, right in zip(got, ref):
+ assert left["area"] == right["area"]
+ assert left["bbox"] == right["bbox"]
+ assert left["center_x"] == right["center_x"]
+ # 픽셀 목록은 순서까지 계약이다 — 하류가 이 순서로 이미지를 재구성한다
+ assert left["pixels"] == right["pixels"]
+
+
+def test_connected_components_alpha_cutoff_boundary_is_pinned():
+ """`> 16` 컷오프 자체를 고정 — alpha 16 은 배경, 17 은 성분이다.
+ 경계값 픽셀이 없으면 컷오프를 한 칸 옮기는 변경이 게이트를 통과한다."""
+ image = _alpha_boundary_field()
+ alpha = image.getchannel("A").tobytes()
+ assert alpha.count(16) and alpha.count(17), "픽스처에 경계 alpha 가 없다"
+ components = extract.connected_components(image)
+ assert components, "성분이 0개면 픽스처가 무의미하다"
+ assert sum(component["area"] for component in components) == sum(1 for value in alpha if value > 16)
+
+
+def test_edge_histograms_matches_frozen_scalar_reference():
+ for image in _tier2_images():
+ assert extract._edge_histograms(image) == _ref_edge_histograms(image)
+
+
+def test_boundary_mass_matches_frozen_scalar_reference():
+ for image in _tier2_images():
+ assert extract._boundary_mass(image) == _ref_boundary_mass(image)
+
+
+# --- 격리 불변식 -----------------------------------------------------------
+
+_FROZEN_BEGIN = "--- FROZEN SCALAR REFERENCE (BEGIN) ---"
+_FROZEN_END = "--- FROZEN SCALAR REFERENCE (END) ---"
+
+
+def _frozen_region() -> str:
+ source = Path(__file__).read_text(encoding="utf-8")
+ start = source.index(_FROZEN_BEGIN)
+ end = source.index(_FROZEN_END)
+ assert start < end
+ return source[start:end]
+
+
+def test_frozen_reference_is_isolated_from_production():
+ """이 게이트의 존재 이유. 동결 구역이 프로덕션 모듈을 참조하면 참조가
+ 프로덕션을 따라 움직여 새 코드를 새 코드와 비교하고 무조건 통과한다 —
+ 그 상태의 green 은 근거가 아니라 위증이다. 그래서 소스 단위로 강제한다."""
+ frozen = _frozen_region()
+ for token in (r"\bextract\b", r"\bsprite_gen\b", r"\bImage\b"):
+ assert not re.search(token, frozen), f"동결 구역이 {token} 를 참조한다"
+ # 참조가 실제로 존재하는지 (구역 마커만 남고 내용이 사라지는 사고 방지)
+ for name in ("_ref_color_distance", "_ref_key_tint_score", "_ref_remove_chroma_background",
+ "_ref_connected_components", "_ref_edge_histograms", "_ref_boundary_mass"):
+ assert f"def {name}(" in frozen
+
+
+def test_fixture_bytes_are_pinned():
+ """실촬 픽스처가 조용히 교체되면 고정 해시 전부가 의미를 잃는다."""
+ for name, expected in MOE_FIXTURE_SHA256.items():
+ assert expected != "PENDING", "픽스처 해시가 비어 있다"
+ digest = hashlib.sha256((FIXTURES / name).read_bytes()).hexdigest()
+ assert digest == expected, f"{name}: {digest}"
diff --git a/tests/gen/test_chroma_soft_alpha.py b/tests/gen/test_chroma_soft_alpha.py
new file mode 100644
index 0000000..b31f9be
--- /dev/null
+++ b/tests/gen/test_chroma_soft_alpha.py
@@ -0,0 +1,224 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Regression tests for soft-alpha edges and trapped interior chroma blends.
+
+Reproduction (moe raws, 2026-07-08): a mint-green-hair character keyed on
+magenta and a crimson-hair character keyed on green both extracted with
+
+1. **Binary alpha** — ``remove_chroma_background`` either erases a pixel to
+ ``(0, 0, 0, 0)`` or leaves it fully opaque; no partial alpha is ever
+ produced, so every antialiased silhouette edge collapses into a hard
+ staircase (mid-alpha pixel count was exactly 0 on both raws).
+2. **Trapped key-tint residue** — key/subject blend pixels caught between
+ hair strands survive cleanup. Measured on these fixtures: the survivors
+ sit 1-4 layers from keyed-out pixels, but (a) dark blends drift 181-265
+ color-distance from the key — outside the fringe band — so the band test
+ rejects them, and (b) blend pockets run up to 4 layers deep while the old
+ in-band peel only removed the nearest 2 layers.
+
+The fixtures are 1/8-size NEAREST copies of the repro raws (1024x1536 ->
+128x192), same recipe as ``tests/fixtures/accident/``:
+``Image.open(raw).convert("RGB").resize((w // 8, h // 8), Image.NEAREST)``.
+Source raws: moe-test ``raw-green.png`` (magenta key) / ``raw-red.png``
+(green key), generated at cell 1024x1536, idle single frame.
+
+The third test pins the v1.10.1 guardrail from the other side: on these
+fixtures, pixels deeper than any plausible fringe peel must come out
+byte-identical. The one sanctioned interior treatment is the trapped-spill
+despill (fourth test): a *small* cluster with a strongly key-tinted pixel,
+buried inside the subject, is generator spill and gets its color corrected
+in place (alpha kept — no pinholes); marginally warm subject colors (skin)
+and large key-tinted material regions are never touched.
+"""
+
+from __future__ import annotations
+
+import importlib.util
+import sys
+from collections import deque
+from pathlib import Path
+
+import pytest
+from PIL import Image
+
+SCRIPTS_DIR = Path(__file__).resolve().parents[2] / "scripts"
+if str(SCRIPTS_DIR) not in sys.path:
+ sys.path.insert(0, str(SCRIPTS_DIR))
+
+
+def _load(name: str):
+ spec = importlib.util.spec_from_file_location(name, SCRIPTS_DIR / f"{name}.py")
+ module = importlib.util.module_from_spec(spec)
+ assert spec and spec.loader
+ spec.loader.exec_module(module)
+ return module
+
+
+extract = _load("extract_sprite_row_frames")
+
+# extract_sprite_row_frames.py main() defaults
+KEY_THRESHOLD = 96.0
+FRINGE_THRESHOLD = 180.0
+FRINGE_DELTA = 18.0
+
+# Blend pockets in the repro raws run up to 4 layers deep, so a fix may
+# legitimately unmix beyond the old 2-layer in-band band for out-of-band
+# pixels. Pixels beyond this margin from every keyed pixel are unambiguously
+# subject interior and must never be altered, whatever the fix does at the
+# boundary.
+INTERIOR_MARGIN = 8
+
+FIXTURES = Path(__file__).resolve().parent.parent / "fixtures" / "moe"
+
+MAGENTA = (255, 0, 255)
+GREEN = (0, 255, 0)
+
+CASES = [
+ pytest.param("moe_green.png", MAGENTA, id="magenta-key"),
+ pytest.param("moe_red.png", GREEN, id="green-key"),
+]
+
+
+def _clean(image: Image.Image, chroma_key: tuple[int, int, int]) -> Image.Image:
+ return extract.remove_chroma_background(
+ image,
+ chroma_key,
+ threshold=KEY_THRESHOLD,
+ fringe_threshold=FRINGE_THRESHOLD,
+ fringe_delta=FRINGE_DELTA,
+ )
+
+
+def _open(name: str) -> Image.Image:
+ with Image.open(FIXTURES / name) as opened:
+ return opened.convert("RGBA")
+
+
+def _is_key_tinted(color: tuple[int, int, int], chroma_key: tuple[int, int, int]) -> bool:
+ """The plan's residue detector: every keyed channel clears every unkeyed
+ channel by more than 40 (for magenta: r-g>40 and b-g>40)."""
+ keyed = [index for index, value in enumerate(chroma_key) if value >= 192]
+ unkeyed = [index for index, value in enumerate(chroma_key) if value < 64]
+ return min(color[index] for index in keyed) - max(color[index] for index in unkeyed) > 40
+
+
+def _keyed_distance_map(image: Image.Image, chroma_key: tuple[int, int, int]) -> list[int | None]:
+ """8-connected BFS distance from every pixel to the nearest keyed pixel."""
+ width, height = image.size
+ pixels = image.load()
+ distance: list[int | None] = [None] * (width * height)
+ frontier: deque[int] = deque()
+ for y in range(height):
+ for x in range(width):
+ red, green, blue, alpha = pixels[x, y]
+ if alpha == 0 or extract.color_distance((red, green, blue), chroma_key) <= KEY_THRESHOLD:
+ distance[y * width + x] = 0
+ frontier.append(y * width + x)
+ while frontier:
+ index = frontier.popleft()
+ x = index % width
+ y = index // width
+ for dy in (-1, 0, 1):
+ for dx in (-1, 0, 1):
+ nx, ny = x + dx, y + dy
+ if 0 <= nx < width and 0 <= ny < height:
+ neighbor = ny * width + nx
+ if distance[neighbor] is None:
+ distance[neighbor] = distance[index] + 1
+ frontier.append(neighbor)
+ return distance
+
+
[email protected]("name, chroma_key", CASES)
+def test_boundary_blend_pixels_get_partial_alpha(name: str, chroma_key) -> None:
+ # ① Antialiased edges must survive as partial alpha. A hard binary cut
+ # leaves zero mid-alpha pixels and the silhouette staircases.
+ out = _clean(_open(name), chroma_key)
+ histogram = out.getchannel("A").histogram()
+ mid_alpha = sum(histogram[1:255])
+ assert mid_alpha > 0, f"{name}: no partial alpha anywhere — edges are a binary cut"
+
+
[email protected]("name, chroma_key", CASES)
+def test_no_key_tint_residue_survives_cleanup(name: str, chroma_key) -> None:
+ # ② Key/subject blends trapped between hair strands must not survive as
+ # visible key-colored specks, whether they touch the outer background or
+ # sit inside an enclosed hole.
+ source = _open(name)
+ source_pixels = source.load()
+ distance = _keyed_distance_map(source, chroma_key)
+ width, height = source.size
+ trapped = [
+ (x, y)
+ for y in range(height)
+ for x in range(width)
+ if 0 < (distance[y * width + x] or 0) <= 4
+ and _is_key_tinted(source_pixels[x, y][:3], chroma_key)
+ ]
+ assert trapped, f"{name}: fixture lost its key-blend pixels; fixture is wrong"
+
+ out = _clean(source, chroma_key).load()
+ residue = [
+ ((x, y), out[x, y][:3])
+ for y in range(height)
+ for x in range(width)
+ if out[x, y][3] > 0 and _is_key_tinted(out[x, y][:3], chroma_key)
+ ]
+ assert not residue, f"{name}: {len(residue)} key-tint pixels survived, e.g. {residue[:5]}"
+
+
[email protected]("name, chroma_key", CASES)
+def test_deep_interior_subject_pixels_survive_untouched(name: str, chroma_key) -> None:
+ # ③ v1.10.1 guardrail: on these fixtures every pixel beyond a plausible
+ # peel of the keyed regions (outer background *and* interior holes) must
+ # come out byte-identical — the fixtures carry no strong-tint spill
+ # cluster deeper than INTERIOR_MARGIN, so nothing deeper may change. In
+ # particular this pins that marginally key-leaning subject colors (skin
+ # under a magenta key scores tint 19-21) are never "despilled".
+ source = _open(name)
+ source_pixels = source.load()
+ distance = _keyed_distance_map(source, chroma_key)
+ width, height = source.size
+ interior = [
+ (x, y)
+ for y in range(height)
+ for x in range(width)
+ if (distance[y * width + x] or 0) > INTERIOR_MARGIN
+ ]
+ assert interior, f"{name}: fixture has no deep-interior pixels; fixture is wrong"
+
+ out = _clean(source, chroma_key).load()
+ changed = [
+ (x, y)
+ for x, y in interior
+ if out[x, y] != source_pixels[x, y]
+ ]
+ assert not changed, f"{name}: {len(changed)} deep-interior pixels altered, e.g. {changed[:5]}"
+
+
+def test_trapped_spill_strand_is_despilled_in_place() -> None:
+ # ④ Generator spill: a small, strongly key-tinted streak buried deep in
+ # the subject (a green strand inside crimson hair at full resolution sits
+ # 20+ px from any keyed pixel) is unreachable by any boundary peel. It
+ # must be color-corrected in place — tint removed, alpha kept, so the
+ # sprite gets no pinhole — while the untinted subject around it stays
+ # byte-identical.
+ subject = (60, 170, 70)
+ spill = (190, 60, 170) # dist ~123 from magenta (past the hard cut), tint 120
+ assert extract.color_distance(spill, MAGENTA) > KEY_THRESHOLD
+ assert extract.key_tint_score(spill, MAGENTA) > 40
+
+ image = Image.new("RGBA", (64, 64), (*MAGENTA, 255))
+ pixels = image.load()
+ for y in range(4, 60):
+ for x in range(4, 60):
+ pixels[x, y] = (*subject, 255)
+ streak = [(x, y) for y in range(28, 36) for x in range(30, 33)] # 3x8, depth > 8
+ for x, y in streak:
+ pixels[x, y] = (*spill, 255)
+
+ out = _clean(image, MAGENTA).load()
+ for x, y in streak:
+ red, green, blue, alpha = out[x, y]
+ assert alpha == 255, f"spill despill must keep alpha, got {alpha} at {(x, y)}"
+ assert not _is_key_tinted((red, green, blue), MAGENTA), f"tint survived at {(x, y)}"
+ assert out[20, 32] == (*subject, 255) # deep untinted subject untouched
diff --git a/tests/gen/test_chroma_ycbcr.py b/tests/gen/test_chroma_ycbcr.py
new file mode 100644
index 0000000..ae344bc
--- /dev/null
+++ b/tests/gen/test_chroma_ycbcr.py
@@ -0,0 +1,215 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Tests for the opt-in YCbCr chrominance matting path (chroma.mode: "ycbcr").
+
+Port of perfectpixel-studio internal/sprite/chroma.go (MIT — see NOTICE).
+What the RGB-distance path cannot do and this path must:
+
+1. **Shaded/gradient key background** — a green key darkened by shading keeps
+ its chroma direction but moves >96 RGB distance from the declared key, so
+ the RGB threshold leaves it opaque. On the CbCr plane it stays in the key's
+ chroma family and the border flood fill removes it.
+2. **Key detection by histogram mode, not mean** — a border containing two
+ chroma clusters must yield the dominant cluster's average, never the
+ global mean (which lands between clusters and mattes neither).
+3. **Key-direction despill** — a green-spilled subject pixel loses only its
+ key-direction chroma; colors orthogonal to the key keep their saturation.
+4. **Connectivity preserves the interior** — a key-family pixel enclosed by
+ subject never connects to the border and survives the flood fill.
+5. **Self-diagnostic rematte is observable** — when border sampling
+ mis-detects the key (subject crowds the corners), the declared-key rematte
+ engages and reports itself through the warnings channel (no silent
+ fallback).
+"""
+
+from __future__ import annotations
+
+import importlib.util
+import json
+import shutil
+import sys
+from pathlib import Path
+
+from PIL import Image
+
+SCRIPTS_DIR = Path(__file__).resolve().parents[2] / "scripts"
+if str(SCRIPTS_DIR) not in sys.path:
+ sys.path.insert(0, str(SCRIPTS_DIR))
+
+
+def _load(name: str):
+ spec = importlib.util.spec_from_file_location(name, SCRIPTS_DIR / f"{name}.py")
+ module = importlib.util.module_from_spec(spec)
+ assert spec and spec.loader
+ spec.loader.exec_module(module)
+ return module
+
+
+extract = _load("extract_sprite_row_frames")
+
+GREEN = (0, 255, 0)
+# Shaded green: same chroma direction as the key, dimmed luma. RGB distance to
+# pure green is 115 (past the 96 erase radius) yet its CbCr offset stays inside
+# the lenient flood tolerance.
+SHADED_GREEN = (0, 140, 0)
+RED = (200, 40, 40)
+
+
+def _opaque_count(image: Image.Image, threshold: int = 10) -> int:
+ return sum(image.getchannel("A").histogram()[threshold + 1 :])
+
+
+def _green_family_opaque(image: Image.Image) -> int:
+ """Opaque pixels still in the key's chroma family (residual background)."""
+ pixels = image.load()
+ width, height = image.size
+ _, key_cb, key_cr = extract.rgb_to_ycc(*GREEN)
+ count = 0
+ for y in range(height):
+ for x in range(width):
+ red, green, blue, alpha = pixels[x, y]
+ if alpha <= 10:
+ continue
+ _, cb, cr = extract.rgb_to_ycc(red, green, blue)
+ if ((cb - key_cb) ** 2 + (cr - key_cr) ** 2) ** 0.5 < 55.0:
+ count += 1
+ return count
+
+
+def _shaded_key_strip() -> Image.Image:
+ """Green-key strip with a wide shaded-green band and a red subject.
+
+ The shaded band is kept >6px away from any pure-key pixel by making it a
+ thick border-adjacent region, so the RGB path's depth-limited unmix cannot
+ reach it either.
+ """
+ strip = Image.new("RGB", (96, 64), GREEN)
+ # Shaded background band across the bottom third — border-connected.
+ for y in range(44, 64):
+ for x in range(96):
+ strip.putpixel((x, y), SHADED_GREEN)
+ # Red subject block, clear of the band.
+ for y in range(8, 36):
+ for x in range(30, 62):
+ strip.putpixel((x, y), RED)
+ return strip
+
+
+def test_rgb_path_leaves_shaded_key_but_ycbcr_clears_it():
+ strip = _shaded_key_strip()
+ rgb_result = extract.remove_chroma_background(strip, GREEN, 96.0, 180.0, 18.0)
+ ycc_result = extract.remove_chroma_background_ycbcr(strip, GREEN)
+
+ # The shaded band's lower rows sit beyond the RGB path's depth-limited
+ # unmix reach; count survivors there directly.
+ band = (0, 50, 96, 64)
+ rgb_residue = _opaque_count(rgb_result.crop(band))
+ ycc_residue = _opaque_count(ycc_result.crop(band))
+ assert rgb_residue > 500, "expected the RGB path to leave the shaded band opaque"
+ assert ycc_residue == 0, f"ycbcr path left {ycc_residue} background pixels"
+ assert _green_family_opaque(ycc_result) == 0
+
+ # The subject must survive intact in both.
+ subject = ycc_result.crop((30, 8, 62, 36))
+ assert _opaque_count(subject) == subject.width * subject.height
+
+
+def test_detect_background_key_uses_histogram_mode_not_mean():
+ # Two chroma clusters on the border: dominant real background vs a
+ # minority stripe. The mean of the samples is a muddy midpoint that
+ # mattes neither cluster; both resolution branches (declared-key family
+ # bias, plain histogram mode) must land on the dominant cluster.
+ image = Image.new("RGB", (60, 60), (11, 238, 27))
+ for y in range(60):
+ for x in range(0, 12): # left edge minority stripe
+ image.putpixel((x, y), (200, 40, 200))
+ rgba = image.convert("RGBA")
+ # Declared key green → the green family on the border wins.
+ detected = extract.detect_background_key_ycc(rgba, GREEN)
+ assert extract.color_distance(detected, (11, 238, 27)) < 30.0
+ # A declared key with no family on the border (blue) forces the pure
+ # histogram-mode branch; the dominant green cluster must still win.
+ detected_mode = extract.detect_background_key_ycc(rgba, (0, 77, 255))
+ assert extract.color_distance(detected_mode, (11, 238, 27)) < 30.0
+
+
+def test_despill_subtracts_key_direction_only():
+ # Green-spilled interior pixels ((60, 220, 60): CbCr distance ~51 from the
+ # key — inside the despill band) shielded from the border flood fill by a
+ # solid red ring, so the despilled soft-alpha result survives.
+ spilled = (60, 220, 60)
+ strip = Image.new("RGB", (48, 48), GREEN)
+ for y in range(10, 38):
+ for x in range(10, 38):
+ strip.putpixel((x, y), RED)
+ for y in range(16, 32):
+ for x in range(16, 32):
+ strip.putpixel((x, y), spilled)
+ result = extract.remove_chroma_background_ycbcr(strip, GREEN)
+ red, green, blue, alpha = result.getpixel((24, 24))
+ assert 0 < alpha < 255, "spill blend must resolve to partial coverage"
+ # Green excess over the other channels must shrink after despill.
+ before_excess = spilled[1] - (spilled[0] + spilled[2]) / 2
+ after_excess = green - (red + blue) / 2
+ assert after_excess < before_excess * 0.7
+ # A color orthogonal to the key direction is preserved byte-exact.
+ assert result.getpixel((12, 12)) == (*RED, 255)
+
+
+def test_flood_fill_preserves_enclosed_key_family_pixel():
+ strip = Image.new("RGB", (48, 48), GREEN)
+ # Solid red subject with one shaded-green pixel sealed inside.
+ for y in range(10, 38):
+ for x in range(10, 38):
+ strip.putpixel((x, y), RED)
+ strip.putpixel((24, 24), SHADED_GREEN)
+ result = extract.remove_chroma_background_ycbcr(strip, GREEN)
+ assert result.getpixel((24, 24))[3] > 0, "enclosed key-family pixel must survive"
+ # Border-connected shaded green (same color) is removed.
+ strip.putpixel((2, 2), SHADED_GREEN)
+ result2 = extract.remove_chroma_background_ycbcr(strip, GREEN)
+ assert result2.getpixel((2, 2))[3] == 0
+
+
+def test_self_diagnostic_rematte_is_reported():
+ # Subject crowds every corner: border sampling detects the red frame as
+ # the key, mattes away the subject, and the green background survives —
+ # the residue symptom must trigger the declared-key rematte.
+ strip = Image.new("RGB", (64, 64), RED)
+ for y in range(16, 48):
+ for x in range(16, 48):
+ strip.putpixel((x, y), GREEN)
+ warnings: list[str] = []
+ result = extract.remove_chroma_background_ycbcr(strip, GREEN, warnings)
+ assert warnings, "fallback rematte must be observable"
+ assert result.getpixel((32, 32))[3] == 0, "green region must be keyed out"
+ assert result.getpixel((4, 4))[3] == 255, "red subject must survive"
+
+
+def test_extract_cli_ycbcr_mode_end_to_end(fixture_run_dir: Path):
+ from conftest import run_script
+
+ result = run_script(
+ "extract_sprite_row_frames.py",
+ "--run-dir",
+ str(fixture_run_dir),
+ "--chroma-mode",
+ "ycbcr",
+ )
+ assert result.returncode == 0, result.stderr
+ request = json.loads((fixture_run_dir / "sprite-request.json").read_text())
+ assert request["chroma"]["mode"] == "ycbcr"
+ for state, frames in (("idle", 4), ("walk", 3)):
+ for index in range(frames):
+ frame = fixture_run_dir / "frames" / state / f"frame-{index}.png"
+ assert frame.is_file()
+ with Image.open(frame) as opened:
+ assert _opaque_count(opened.convert("RGBA")) > 0
+
+
+def test_default_mode_stays_rgb(fixture_run_dir: Path):
+ from conftest import run_script
+
+ result = run_script("extract_sprite_row_frames.py", "--run-dir", str(fixture_run_dir))
+ assert result.returncode == 0, result.stderr
+ request = json.loads((fixture_run_dir / "sprite-request.json").read_text())
+ assert request["chroma"]["mode"] == "rgb"
diff --git a/tests/gen/test_codex_rollout_resolution.py b/tests/gen/test_codex_rollout_resolution.py
new file mode 100644
index 0000000..4e48e1f
--- /dev/null
+++ b/tests/gen/test_codex_rollout_resolution.py
@@ -0,0 +1,197 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Codex state-root and rollout selection contracts."""
+
+from __future__ import annotations
+
+import base64
+import json
+from concurrent.futures import ThreadPoolExecutor
+from pathlib import Path
+
+import pytest
+from PIL import Image
+
+from sprite_gen.gen import codex_provider
+from sprite_gen.gen.base import GenRequest, verify_png
+
+
+def _png_base64() -> str:
+ import io
+
+ buffer = io.BytesIO()
+ Image.new("RGBA", (4, 4), (255, 0, 255, 255)).save(buffer, format="PNG")
+ return base64.b64encode(buffer.getvalue()).decode("ascii")
+
+
+def _write_rollout(codex_home: Path, session_id: str, *, branch: str = "03") -> Path:
+ rollout = (
+ codex_home
+ / "sessions"
+ / "2026"
+ / "08"
+ / branch
+ / f"rollout-2026-08-{branch}T02-40-51-{session_id}.jsonl"
+ )
+ rollout.parent.mkdir(parents=True, exist_ok=True)
+ rollout.write_text(
+ json.dumps(
+ {
+ "payload": {
+ "type": "image_generation_end",
+ "status": "completed",
+ "result": _png_base64(),
+ }
+ }
+ )
+ + "\n",
+ encoding="utf-8",
+ )
+ return rollout
+
+
+def test_codex_home_env_is_the_only_state_root(tmp_path: Path, monkeypatch) -> None:
+ configured = tmp_path / "account-codex-home"
+ configured.mkdir()
+ monkeypatch.setenv("CODEX_HOME", str(configured))
+
+ assert codex_provider._resolve_codex_home() == configured.resolve()
+
+
+def test_codex_home_unset_uses_codex_default_root(tmp_path: Path, monkeypatch) -> None:
+ monkeypatch.delenv("CODEX_HOME", raising=False)
+ monkeypatch.setattr(codex_provider.Path, "home", classmethod(lambda cls: tmp_path / "user"))
+
+ assert codex_provider._resolve_codex_home() == tmp_path / "user" / ".codex"
+
+
+def test_codex_home_set_empty_fails_instead_of_falling_back(monkeypatch) -> None:
+ monkeypatch.setenv("CODEX_HOME", " ")
+
+ with pytest.raises(SystemExit, match="CODEX_HOME is set but empty"):
+ codex_provider._resolve_codex_home()
+
+
+def test_resolve_rollout_missing_and_duplicate_fail_loud(tmp_path: Path) -> None:
+ sessions = tmp_path / "sessions"
+ session_id = "018f0000-0000-7000-8000-000000000002"
+
+ with pytest.raises(SystemExit, match="no rollout jsonl"):
+ codex_provider._resolve_rollout(session_id, sessions)
+
+ first = _write_rollout(tmp_path, session_id, branch="03")
+ second = _write_rollout(tmp_path, session_id, branch="04")
+ with pytest.raises(SystemExit, match="multiple rollout jsonl files") as error:
+ codex_provider._resolve_rollout(session_id, sessions)
+ assert str(first) in str(error.value)
+ assert str(second) in str(error.value)
+
+
+def test_resolve_rollout_rejects_preexisting_stale_session(tmp_path: Path) -> None:
+ session_id = "018f0000-0000-7000-8000-000000000002"
+ stale = _write_rollout(tmp_path, session_id)
+ sessions = tmp_path / "sessions"
+
+ with pytest.raises(SystemExit, match="pre-existing stale rollout"):
+ codex_provider._resolve_rollout(session_id, sessions, preexisting={stale.resolve()})
+
+
+def test_parallel_sessions_resolve_by_exact_session_id(tmp_path: Path) -> None:
+ session_ids = [
+ "018f0000-0000-7000-8000-000000000002",
+ "018f0000-0000-7000-8000-000000000003",
+ "018f0000-0000-7000-8000-000000000004",
+ "018f0000-0000-7000-8000-000000000005",
+ ]
+ expected = {
+ session_id: _write_rollout(tmp_path, session_id, branch=f"{index + 3:02d}")
+ for index, session_id in enumerate(session_ids)
+ }
+ unrelated_stale = _write_rollout(
+ tmp_path, "018f0000-0000-7000-8000-000000000006", branch="02"
+ )
+ sessions = tmp_path / "sessions"
+
+ with ThreadPoolExecutor(max_workers=4) as executor:
+ resolved = dict(
+ zip(
+ session_ids,
+ executor.map(lambda session_id: codex_provider._resolve_rollout(session_id, sessions), session_ids),
+ strict=True,
+ )
+ )
+
+ assert resolved == expected
+ assert unrelated_stale not in resolved.values()
+
+
+def test_generate_reads_rollout_from_nondefault_codex_home(tmp_path: Path, monkeypatch) -> None:
+ codex_home = tmp_path / "engine-account" / "codex"
+ codex_home.mkdir(parents=True)
+ monkeypatch.setenv("CODEX_HOME", str(codex_home))
+ session_id = "018f0000-0000-7000-8000-000000000002"
+ seen: dict[str, object] = {}
+
+ class _Completed:
+ returncode = 0
+ stdout = json.dumps({"type": "thread.started", "thread_id": session_id}) + "\n"
+ stderr = ""
+
+ def _fake_run(cmd, **kwargs):
+ seen["cmd"] = cmd
+ seen["env"] = kwargs["env"]
+ _write_rollout(codex_home, session_id)
+ return _Completed()
+
+ monkeypatch.setattr(codex_provider.subprocess, "run", _fake_run)
+ workdir = tmp_path / "work"
+ workdir.mkdir()
+ raw = workdir / "raw.png"
+
+ result = codex_provider.CodexProvider(keep_session=True).generate(
+ GenRequest(prompt="a mushroom", raw=raw), workdir
+ )
+
+ assert result.session_id == session_id
+ assert verify_png(raw) > 0
+ cmd = seen["cmd"]
+ assert isinstance(cmd, list)
+ add_dir = cmd[cmd.index("--add-dir") + 1]
+ assert add_dir == str(codex_home / "generated_images")
+ assert (codex_home / "generated_images").is_dir()
+ assert seen["env"]["CODEX_HOME"] == str(codex_home.resolve())
+
+
+def test_generate_reads_rollout_from_default_codex_home(tmp_path: Path, monkeypatch) -> None:
+ monkeypatch.delenv("CODEX_HOME", raising=False)
+ monkeypatch.setattr(codex_provider.Path, "home", classmethod(lambda cls: tmp_path / "user"))
+ codex_home = tmp_path / "user" / ".codex"
+ codex_home.mkdir(parents=True)
+ session_id = "018f0000-0000-7000-8000-000000000003"
+ seen: dict[str, object] = {}
+
+ class _Completed:
+ returncode = 0
+ stdout = json.dumps({"type": "thread.started", "thread_id": session_id}) + "\n"
+ stderr = ""
+
+ def _fake_run(cmd, **kwargs):
+ seen["cmd"] = cmd
+ seen["env"] = kwargs["env"]
+ _write_rollout(codex_home, session_id)
+ return _Completed()
+
+ monkeypatch.setattr(codex_provider.subprocess, "run", _fake_run)
+ workdir = tmp_path / "work"
+ workdir.mkdir()
+ raw = workdir / "raw.png"
+
+ result = codex_provider.CodexProvider(keep_session=True).generate(
+ GenRequest(prompt="a mushroom", raw=raw), workdir
+ )
+
+ assert result.session_id == session_id
+ assert verify_png(raw) > 0
+ cmd = seen["cmd"]
+ assert isinstance(cmd, list)
+ assert cmd[cmd.index("--add-dir") + 1] == str(codex_home / "generated_images")
+ assert "CODEX_HOME" not in seen["env"]
diff --git a/tests/gen/test_gen.py b/tests/gen/test_gen.py
new file mode 100644
index 0000000..7b7245d
--- /dev/null
+++ b/tests/gen/test_gen.py
@@ -0,0 +1,531 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Offline tests for the sprite_gen.gen provider layer.
+
+Network/OAuth provider calls (codex exec, grok) are exercised as live e2e in the
+C-gen deliverable; here we lock the deterministic seams: PNG verification, the
+codex inline-base64 extraction contract, prompt shape, chroma post-process, and
+the orchestrator wiring with a fake provider.
+"""
+
+from __future__ import annotations
+
+import base64
+import json
+from pathlib import Path
+
+import pytest
+from PIL import Image
+
+from sprite_gen import gen
+from sprite_gen.gen import base as gen_base
+from sprite_gen.gen import chroma as chroma_mod
+from sprite_gen.gen import codex_provider
+from sprite_gen.gen.base import GenRequest
+
+
+def _png_bytes(color=(255, 0, 255, 255), size=(4, 4)) -> bytes:
+ import io
+
+ buf = io.BytesIO()
+ Image.new("RGBA", size, color).save(buf, format="PNG")
+ return buf.getvalue()
+
+
+def test_verify_png_accepts_real_png_and_rejects_junk(tmp_path: Path) -> None:
+ good = tmp_path / "good.png"
+ good.write_bytes(_png_bytes())
+ assert gen_base.verify_png(good) == len(good.read_bytes())
+
+ bad = tmp_path / "bad.png"
+ bad.write_bytes(b"not a png")
+ with pytest.raises(SystemExit):
+ gen_base.verify_png(bad)
+
+ with pytest.raises(SystemExit):
+ gen_base.verify_png(tmp_path / "missing.png")
+
+
+def test_provider_subprocess_env_scrubs_orchestrator_session_env(monkeypatch) -> None:
+ monkeypatch.setenv("ORCHESTRATOR_RUNTIME_ENDPOINT_ID", "synthetic-endpoint")
+ monkeypatch.setenv("ORCHESTRATOR_MEMBER_ID", "synthetic-worker")
+ monkeypatch.setenv("ORCHESTRATOR_PROJECT_ID", "synthetic-project")
+ monkeypatch.setenv("ORCHESTRATOR_PLAN_EXIT_GATE", "1")
+ monkeypatch.setenv("ORCHESTRATOR_STUDIO_PORT", "4312")
+ monkeypatch.setenv("PATH", "/usr/bin")
+
+ env = gen_base.provider_subprocess_env()
+
+ assert not [
+ key
+ for key in env
+ if key.endswith(gen_base._ORCHESTRATOR_SESSION_ENV_SUFFIXES)
+ ], "orchestrator session variables must be scrubbed from provider environments"
+ assert env.get("PATH") == "/usr/bin" # 일반 env 는 유지
+
+
+def test_provider_binary_resolves_windows_style_path_shims(monkeypatch) -> None:
+ monkeypatch.setattr(gen_base.shutil, "which", lambda name: f"C:/tools/{name}.CMD")
+ assert gen_base.provider_binary("codex") == "C:/tools/codex.CMD"
+ monkeypatch.setattr(gen_base.shutil, "which", lambda _name: None)
+ assert gen_base.provider_binary("codex") == "codex"
+
+
+def test_provider_run_uses_scrubbed_env(tmp_path: Path, monkeypatch) -> None:
+ # Both providers must route their subprocess.run through the scrubbed env.
+ import sprite_gen.gen.grok_provider as grok_provider
+
+ seen: dict[str, dict | None] = {}
+
+ class _Completed:
+ returncode = 0
+ stdout = '{"type":"thread.started","thread_id":"aaaa-bbbb"}\n'
+ stderr = ""
+
+ def _fake_codex_run(cmd, **kwargs):
+ seen["codex"] = kwargs.get("env")
+ seen["codex_cmd"] = cmd
+ seen["codex_encoding"] = kwargs.get("encoding")
+ return _Completed()
+
+ # Short-circuit codex's post-run rollout parsing — we only assert the env.
+ monkeypatch.setattr(codex_provider.subprocess, "run", _fake_codex_run)
+ monkeypatch.setattr(
+ codex_provider,
+ "_resolve_rollout",
+ lambda sid, sessions_root, *, preexisting: tmp_path / "x.jsonl",
+ )
+ b64 = base64.b64encode(_png_bytes()).decode()
+ monkeypatch.setattr(codex_provider, "_collect_inline_results", lambda rollout: [b64])
+ monkeypatch.setenv("ORCHESTRATOR_RUNTIME_ENDPOINT_ID", "synthetic-endpoint")
+ codex_provider.CodexProvider(keep_session=True).generate(
+ GenRequest(prompt="a mushroom", raw=tmp_path / "raw.png"), tmp_path
+ )
+ assert seen["codex"] is not None
+ assert "ORCHESTRATOR_RUNTIME_ENDPOINT_ID" not in seen["codex"]
+ assert seen["codex_encoding"] == "utf-8"
+
+ grok_raw = tmp_path / "grok_raw.png"
+
+ def _fake_grok_run(cmd, **kwargs):
+ seen["grok"] = kwargs.get("env")
+ seen["grok_cmd"] = cmd
+ seen["grok_encoding"] = kwargs.get("encoding")
+ # grok's truth is the PNG on disk — write one so verify_png passes.
+ Image.new("RGBA", (8, 8), (255, 0, 255, 255)).save(grok_raw)
+ class _C:
+ returncode = 0
+ stdout = str(grok_raw)
+ stderr = ""
+ return _C()
+
+ monkeypatch.setattr(grok_provider.subprocess, "run", _fake_grok_run)
+ grok_provider.GrokProvider().generate(
+ GenRequest(prompt="a mushroom", raw=grok_raw), tmp_path
+ )
+ assert seen["grok"] is not None
+ assert "ORCHESTRATOR_RUNTIME_ENDPOINT_ID" not in seen["grok"]
+ assert seen["grok_encoding"] == "utf-8"
+
+
+def test_provider_commands_use_the_single_resolved_binary(tmp_path: Path, monkeypatch) -> None:
+ import sprite_gen.gen.grok_provider as grok_provider
+
+ seen: dict[str, list[str]] = {}
+ monkeypatch.setattr(codex_provider, "provider_binary", lambda _name: "C:/bin/codex.CMD")
+ monkeypatch.setattr(grok_provider, "provider_binary", lambda _name: "C:/bin/grok.CMD")
+
+ class _CodexCompleted:
+ returncode = 0
+ stdout = '{"type":"thread.started","thread_id":"aaaa-bbbb"}\n'
+ stderr = ""
+
+ def fake_codex(cmd, **_kwargs):
+ seen["codex"] = cmd
+ return _CodexCompleted()
+
+ monkeypatch.setattr(codex_provider.subprocess, "run", fake_codex)
+ monkeypatch.setattr(codex_provider, "_resolve_rollout", lambda *_args, **_kwargs: tmp_path / "rollout.jsonl")
+ monkeypatch.setattr(codex_provider, "_collect_inline_results", lambda _path: [base64.b64encode(_png_bytes()).decode()])
+ codex_provider.CodexProvider(keep_session=True).generate(
+ GenRequest(prompt="도구", raw=tmp_path / "codex.png"), tmp_path
+ )
+
+ grok_out = tmp_path / "grok.png"
+
+ class _GrokCompleted:
+ returncode = 0
+ stdout = "ok"
+ stderr = ""
+
+ def fake_grok(cmd, **_kwargs):
+ seen["grok"] = cmd
+ Image.new("RGBA", (2, 2), (1, 2, 3, 255)).save(grok_out)
+ return _GrokCompleted()
+
+ monkeypatch.setattr(grok_provider.subprocess, "run", fake_grok)
+ grok_provider.GrokProvider().generate(GenRequest(prompt="도구", raw=grok_out), tmp_path)
+ assert seen["codex"][0] == "C:/bin/codex.CMD"
+ assert seen["grok"][0] == "C:/bin/grok.CMD"
+
+
+def test_json_report_writes_utf8_bytes_without_reconfiguring_stdout(monkeypatch) -> None:
+ import io
+ import sys
+
+ raw = io.BytesIO()
+ cp949_stream = io.TextIOWrapper(raw, encoding="cp949")
+ monkeypatch.setattr(sys, "stdout", cp949_stream)
+ gen._print_json({"prompt": "도구 — 완료"})
+ cp949_stream.detach()
+ assert json.loads(raw.getvalue().decode("utf-8")) == {"prompt": "도구 — 완료"}
+
+
+def test_codex_inline_extraction_reads_both_record_types(tmp_path: Path) -> None:
+ b64 = base64.b64encode(_png_bytes()).decode()
+ rollout = tmp_path / "rollout-test.jsonl"
+ lines = [
+ {"payload": {"type": "response_item", "text": "noise"}},
+ {"payload": {"type": "image_generation_call", "result": b64}},
+ {"payload": {"type": "image_generation_end", "result": b64, "status": "completed"}},
+ ]
+ rollout.write_text("\n".join(json.dumps(line) for line in lines) + "\n", encoding="utf-8")
+
+ results = codex_provider._collect_inline_results(rollout)
+ assert len(results) == 2
+
+ dest = tmp_path / "decoded.png"
+ codex_provider._decode_png(results[-1], dest)
+ assert gen_base.verify_png(dest) > 0
+
+
+def test_codex_inline_extraction_rejects_failed_status(tmp_path: Path) -> None:
+ b64 = base64.b64encode(_png_bytes()).decode()
+ rollout = tmp_path / "rollout-fail.jsonl"
+ rollout.write_text(
+ json.dumps({"payload": {"type": "image_generation_end", "result": b64, "status": "failed"}}) + "\n",
+ encoding="utf-8",
+ )
+ with pytest.raises(SystemExit):
+ codex_provider._collect_inline_results(rollout)
+
+
+def test_codex_parse_session_id_json_and_legacy() -> None:
+ json_stdout = (
+ '{"type":"thread.started","thread_id":"018f0000-0000-7000-8000-000000000001"}\n'
+ '{"type":"turn.started"}\n'
+ )
+ assert codex_provider._parse_session_id(json_stdout) == "018f0000-0000-7000-8000-000000000001"
+
+ legacy_stdout = "some header\nsession id: abc123de-0000-1111-2222-333344445555\ndone\n"
+ assert codex_provider._parse_session_id(legacy_stdout) == "abc123de-0000-1111-2222-333344445555"
+
+ assert codex_provider._parse_session_id("no id here") is None
+
+
+def test_codex_prompt_carries_official_imagegen_skill_trigger() -> None:
+ # Image generation lives in codex's bundled `imagegen` system skill, and the
+ # official way to invoke a skill explicitly is the `$<skill>` prompt mention
+ # (skills/.system/imagegen/agents/openai.yaml ships `default_prompt: "Use
+ # $imagegen to make or edit an image for this project."`). This locks the
+ # transport prompt to that contract; if the implicit prose phrasing comes
+ # back, this goes red.
+ #
+ # Scope note: the trigger is a contract alignment, not a tool-exposure fix.
+ # Built-in image generation is an account capability of the active Codex state
+ # root — see codex_provider._no_image_records_message. Do not let this test's
+ # name imply that the trigger is what makes image_gen available.
+ user_prompt = "a mushroom sprite row on a #00FF00 background"
+ prompt = codex_provider._build_prompt(user_prompt)
+
+ assert codex_provider._SKILL_TRIGGER == "$imagegen"
+ assert "$imagegen" in prompt, "the official skill trigger must be in the transport prompt"
+ # It must lead the instruction, not trail the user's prompt as an aside.
+ assert prompt.startswith("$imagegen "), prompt
+ # The caller's sprite-request prompt is the SSoT — passed through verbatim.
+ assert user_prompt in prompt
+ # The rest of the transport contract survives the trigger.
+ assert "정확히 1번" in prompt
+ assert "금지" in prompt
+
+
+def test_codex_empty_rollout_fails_loud_on_tool_non_exposure(tmp_path: Path, monkeypatch) -> None:
+ # An empty rollout is the tool-non-exposure signature. It must fail loudly, name
+ # the account capability behind the active Codex state root as the thing that is
+ # missing, and point at the one real remedy — never fall back to another
+ # provider on its own, never trust a model-reported path, and never send the
+ # reader off to hunt for a config toggle.
+ monkeypatch.setenv("CODEX_HOME", str(tmp_path))
+ rollout = tmp_path / "rollout-empty.jsonl"
+
+ class _Completed:
+ returncode = 0
+ stdout = '{"type":"thread.started","thread_id":"aaaa-bbbb"}\n'
+ stderr = ""
+
+ monkeypatch.setattr(codex_provider.subprocess, "run", lambda cmd, **kwargs: _Completed())
+ monkeypatch.setattr(
+ codex_provider,
+ "_resolve_rollout",
+ lambda sid, sessions_root, *, preexisting: rollout,
+ )
+ monkeypatch.setattr(codex_provider, "_collect_inline_results", lambda path: [])
+
+ with pytest.raises(SystemExit) as excinfo:
+ codex_provider.CodexProvider(keep_session=True).generate(
+ GenRequest(prompt="a mushroom", raw=tmp_path / "raw.png"), tmp_path
+ )
+
+ message = str(excinfo.value)
+ assert "image_gen tool never ran" in message
+ assert "$imagegen" in message
+ assert str(rollout) in message
+ # The message must name the missing capability and the state root that lacks
+ # it, and must close off the config-toggle detour.
+ assert "capability" in message
+ assert str(tmp_path) in message, "the failing Codex state root must be named"
+ assert "does not grant it" in message
+ assert not (tmp_path / "raw.png").exists(), "a failed run must not leave a raw PNG"
+
+
+def test_codex_prompt_reaches_the_child_process(tmp_path: Path, monkeypatch) -> None:
+ # The trigger is only real if it survives into codex exec's stdin — assert the
+ # transport prompt is what the child actually receives, not just what we build.
+ monkeypatch.setenv("CODEX_HOME", str(tmp_path))
+ seen: dict[str, str] = {}
+
+ class _Completed:
+ returncode = 0
+ stdout = '{"type":"thread.started","thread_id":"aaaa-bbbb"}\n'
+ stderr = ""
+
+ def _fake_run(cmd, **kwargs):
+ seen["input"] = kwargs.get("input", "")
+ return _Completed()
+
+ monkeypatch.setattr(codex_provider.subprocess, "run", _fake_run)
+ monkeypatch.setattr(
+ codex_provider,
+ "_resolve_rollout",
+ lambda sid, sessions_root, *, preexisting: tmp_path / "x.jsonl",
+ )
+ b64 = base64.b64encode(_png_bytes()).decode()
+ monkeypatch.setattr(codex_provider, "_collect_inline_results", lambda path: [b64])
+
+ codex_provider.CodexProvider(keep_session=True).generate(
+ GenRequest(prompt="a mushroom", raw=tmp_path / "raw.png"), tmp_path
+ )
+
+ assert seen["input"].startswith("$imagegen ")
+ assert "a mushroom" in seen["input"]
+
+
+def test_grok_prompt_switches_on_refs(tmp_path: Path) -> None:
+ from sprite_gen.gen import grok_provider
+
+ raw = tmp_path / "raw.png"
+ no_ref = grok_provider._build_prompt(GenRequest(prompt="a red apple", raw=raw, aspect_ratio="1:1"))
+ assert "image_gen" in no_ref and "1:1" in no_ref and str(raw) in no_ref
+
+ ref = tmp_path / "ref.png"
+ ref.write_bytes(_png_bytes())
+ with_ref = grok_provider._build_prompt(GenRequest(prompt="same char waving", raw=raw, refs=[ref]))
+ assert "image_edit" in with_ref and str(ref.resolve()) in with_ref
+
+
+def test_chroma_key_transparent_clears_magenta(tmp_path: Path) -> None:
+ src = tmp_path / "src.png"
+ img = Image.new("RGBA", (6, 6), (255, 0, 255, 255))
+ img.putpixel((2, 2), (10, 20, 30, 255)) # a real subject pixel
+ img.save(src)
+
+ out = tmp_path / "out.png"
+ stats = chroma_mod.key_transparent(src, out, key="magenta", white_check=tmp_path / "check.png")
+ assert stats["mode"] == "RGBA"
+ assert stats["stale_transparent_rgb_pixels"] == 0
+ assert stats["keyed_pixels"] == 35 # 36 - 1 subject pixel
+
+ keyed = Image.open(out).convert("RGBA")
+ assert keyed.getpixel((0, 0))[3] == 0
+ assert keyed.getpixel((2, 2))[3] == 255
+
+
+class _FakeProvider:
+ name = "fake"
+
+ def __init__(self) -> None:
+ self.calls = 0
+
+ def generate(self, request: GenRequest, workdir: Path):
+ self.calls += 1
+ Image.new("RGBA", (8, 8), (255, 0, 255, 255)).save(request.raw)
+ return gen_base.ProviderRun(provider=self.name, elapsed_seconds=1.23, model=request.model)
+
+
+def test_generate_image_orchestrates_report_and_raw_keep(tmp_path: Path, monkeypatch) -> None:
+ fake = _FakeProvider()
+ monkeypatch.setattr(gen, "_make_provider", lambda name, *, keep_session: fake)
+
+ out = tmp_path / "asset.png"
+ report = tmp_path / "report.json"
+ rc = gen.run(
+ provider="fake",
+ prompt="a mushroom",
+ out=out,
+ ref=[],
+ model=None,
+ aspect_ratio=None,
+ transparent=True,
+ chroma_key="magenta",
+ white_check=None,
+ keep_session=False,
+ report=report,
+ prompt_file=None,
+ workdir=None,
+ )
+ assert rc == 0
+ assert fake.calls == 1
+ assert out.is_file()
+ assert (tmp_path / "asset.png.raw.png").is_file() # pre-chroma raw preserved
+ payload = json.loads(report.read_text(encoding="utf-8"))
+ assert payload["provider"] == "fake"
+ assert payload["transparent"] is True
+ assert payload["chroma"]["stale_transparent_rgb_pixels"] == 0
+ assert payload["elapsed_seconds"] == 1.23
+
+
+def test_generate_image_empty_prompt_fails_loud(tmp_path: Path) -> None:
+ with pytest.raises(SystemExit):
+ gen.generate_image("codex", " ", tmp_path / "x.png")
+
+
+def test_unknown_provider_fails_loud(tmp_path: Path) -> None:
+ with pytest.raises(SystemExit):
+ gen._make_provider("gemini", keep_session=False)
+
+
+# ── Default-provider policy (maintainer 2026-07-17): default = codex, observable grok
+# fallback when codex is unavailable, SPRITE_GEN_DEFAULT_PROVIDER override. ──────
+
+def test_resolve_default_provider_hard_default_is_codex(monkeypatch) -> None:
+ monkeypatch.delenv(gen.DEFAULT_PROVIDER_ENV, raising=False)
+ monkeypatch.setattr(gen, "_codex_available", lambda: (True, ""))
+ assert gen.resolve_default_provider() == ("codex", None)
+
+
+def test_resolve_default_provider_env_override(monkeypatch) -> None:
+ monkeypatch.setenv(gen.DEFAULT_PROVIDER_ENV, "grok")
+ # codex probe must not even run when the env pins a non-codex default.
+ monkeypatch.setattr(gen, "_codex_available", lambda: pytest.fail("probe should not run"))
+ assert gen.resolve_default_provider() == ("grok", None)
+
+
+def test_resolve_default_provider_invalid_env_fails_loud(monkeypatch) -> None:
+ monkeypatch.setenv(gen.DEFAULT_PROVIDER_ENV, "gemini")
+ with pytest.raises(SystemExit):
+ gen.resolve_default_provider()
+
+
+def test_resolve_default_provider_codex_unavailable_falls_back_observably(monkeypatch) -> None:
+ monkeypatch.delenv(gen.DEFAULT_PROVIDER_ENV, raising=False)
+ monkeypatch.setattr(gen, "_codex_available", lambda: (False, "codex not logged in (test)"))
+ provider, fallback = gen.resolve_default_provider()
+ assert provider == "grok"
+ assert fallback == {
+ "from": "codex",
+ "to": "grok",
+ "reason": "codex not logged in (test)",
+ "default_source": "hard-default",
+ }
+
+
+def test_resolve_default_provider_env_codex_still_falls_back(monkeypatch) -> None:
+ # An env that pins codex still gets the availability fallback (default_source=env).
+ monkeypatch.setenv(gen.DEFAULT_PROVIDER_ENV, "codex")
+ monkeypatch.setattr(gen, "_codex_available", lambda: (False, "codex CLI not found on PATH"))
+ provider, fallback = gen.resolve_default_provider()
+ assert provider == "grok"
+ assert fallback["default_source"] == gen.DEFAULT_PROVIDER_ENV
+
+
+def _install_recording_provider(monkeypatch):
+ """Monkeypatch _make_provider to record the requested name and emit a PNG."""
+ requested: list[str] = []
+
+ def fake_make(name, *, keep_session):
+ requested.append(name)
+
+ class _P:
+ def generate(self, request: GenRequest, workdir: Path):
+ Image.new("RGBA", (8, 8), (255, 0, 255, 255)).save(request.raw)
+ return gen_base.ProviderRun(provider=name, elapsed_seconds=0.1, model=request.model)
+
+ return _P()
+
+ monkeypatch.setattr(gen, "_make_provider", fake_make)
+ return requested
+
+
+def test_run_explicit_provider_is_honored_without_fallback(tmp_path: Path, monkeypatch) -> None:
+ requested = _install_recording_provider(monkeypatch)
+ # Even with codex "down", an EXPLICIT --provider is never overridden.
+ monkeypatch.setattr(gen, "_codex_available", lambda: (False, "should be irrelevant"))
+ report = tmp_path / "r.json"
+ rc = gen.run(provider="grok", prompt="x", out=tmp_path / "o.png", report=report)
+ assert rc == 0
+ assert requested == ["grok"]
+ payload = json.loads(report.read_text(encoding="utf-8"))
+ assert payload["provider"] == "grok"
+ assert payload["provider_resolved_from"] == "explicit"
+ assert "provider_fallback" not in payload
+
+
+def test_run_default_uses_codex_when_available(tmp_path: Path, monkeypatch) -> None:
+ monkeypatch.delenv(gen.DEFAULT_PROVIDER_ENV, raising=False)
+ requested = _install_recording_provider(monkeypatch)
+ monkeypatch.setattr(gen, "_codex_available", lambda: (True, ""))
+ report = tmp_path / "r.json"
+ rc = gen.run(prompt="x", out=tmp_path / "o.png", report=report)
+ assert rc == 0
+ assert requested == ["codex"]
+ payload = json.loads(report.read_text(encoding="utf-8"))
+ assert payload["provider"] == "codex"
+ assert payload["provider_resolved_from"] == "hard-default"
+ assert "provider_fallback" not in payload
+
+
+def test_run_default_falls_back_to_grok_and_reports_it(tmp_path: Path, monkeypatch, capsys) -> None:
+ monkeypatch.delenv(gen.DEFAULT_PROVIDER_ENV, raising=False)
+ requested = _install_recording_provider(monkeypatch)
+ monkeypatch.setattr(gen, "_codex_available", lambda: (False, "codex not logged in (test)"))
+ report = tmp_path / "r.json"
+ rc = gen.run(prompt="x", out=tmp_path / "o.png", report=report)
+ assert rc == 0
+ assert requested == ["grok"] # actually generated with grok
+ payload = json.loads(report.read_text(encoding="utf-8"))
+ assert payload["provider"] == "grok"
+ assert payload["provider_resolved_from"] == "fallback-from-codex"
+ assert payload["provider_fallback"]["from"] == "codex"
+ assert payload["provider_fallback"]["to"] == "grok"
+ assert "codex not logged in" in payload["provider_fallback"]["reason"]
+ # And the fallback is loud on stderr (No Silent Fallback).
+ assert "falling back to 'grok'" in capsys.readouterr().err
+
+
+def test_codex_stream_errors_surface_the_real_cause() -> None:
+ # codex reports a fatal error (e.g. an unsupported model) on stdout as a
+ # `turn.failed` event, with the API error nested as JSON inside `message`.
+ # Item-level warnings (model metadata, skills budget) must not drown it out.
+ stream = "\n".join([
+ '{"type":"thread.started","thread_id":"abc"}',
+ '{"type":"item.completed","item":{"type":"error","message":"Model metadata for `x` not found."}}',
+ '{"type":"turn.failed","error":{"message":'
+ '"{\\"type\\":\\"error\\",\\"status\\":400,\\"error\\":'
+ '{\\"type\\":\\"invalid_request_error\\",'
+ '\\"message\\":\\"The model is not supported.\\"}}"}}',
+ ])
+ assert codex_provider._extract_stream_errors(stream) == ["The model is not supported."]
+
+
+def test_codex_stream_errors_empty_when_no_failure() -> None:
+ stream = '{"type":"thread.started","thread_id":"abc"}\n{"type":"turn.completed"}'
+ assert codex_provider._extract_stream_errors(stream) == []
diff --git a/tests/packaging/test_curation_asset_packaging.py b/tests/packaging/test_curation_asset_packaging.py
new file mode 100644
index 0000000..e2035ba
--- /dev/null
+++ b/tests/packaging/test_curation_asset_packaging.py
@@ -0,0 +1,212 @@
+# SPDX-License-Identifier: Apache-2.0
+"""The curation SPA ships inside the package, from one location.
+
+`sprite-gen curation` finds its assets relative to `sprite_gen/serve/serve_curation.py`, so an
+asset that `pyproject.toml` does not declare as package data is simply absent from an
+installed wheel — the server still boots and still serves `index.html`, and every
+`<script src>` in it 404s. Nothing fails at build time, so what lands in the build is
+checked here against what is actually on disk instead.
+
+Checked against the build, not against the declaration string: reading the patterns and
+asking "does this asset look like one of them" is how the first version of this guard passed
+while the wheel was already dropping files (`fnmatch`'s `*` crosses `/`, setuptools' does
+not). Both tests below therefore go through an expansion that packaging actually performs —
+`glob(recursive=True)` for the always-on one, a real wheel build for the other.
+
+The same reasoning covers the subprocess routes (`/api/compose`, `/api/interpolate`,
+`/api/reroll`, `/api/export`, `/api/export-gif`): naming `scripts/<tool>.py` there would
+work in a checkout and 500 in an install, because the `scripts/` wrappers are not
+installed. Those routes go through `-m sprite_gen.<module>`, and the last test holds them
+to it.
+"""
+
+from __future__ import annotations
+
+import ast
+import glob
+import importlib.util
+import os
+import re
+import shutil
+import subprocess
+import sys
+import zipfile
+from pathlib import Path
+
+import pytest
+
+from sprite_gen.serve.serve_curation import CURATOR_DIR
+
+ROOT = Path(__file__).resolve().parent.parent.parent
+PACKAGE_DIR = ROOT / "sprite_gen"
+PYPROJECT = (ROOT / "pyproject.toml").read_text(encoding="utf-8")
+
+# `scripts/<anything>.py` named as a path, not as prose.
+SCRIPT_PATH = re.compile(r"(?:^|/)scripts/[^/]+\.py$")
+
+
+def _declared_package_data() -> list[str]:
+ """The `sprite_gen = [...]` patterns under `[tool.setuptools.package-data]`.
+
+ Read with a regex for the same reason `test_version_ssot.py` does: `tomllib` is 3.11+
+ and this suite runs on the 3.10 floor `requires-python` promises.
+ """
+ section = re.search(
+ r"(?ms)^\[tool\.setuptools\.package-data\]\s*$(.*?)(?=^\[|\Z)", PYPROJECT)
+ assert section, "pyproject.toml is missing [tool.setuptools.package-data]"
+ entry = re.search(r"(?ms)^sprite_gen\s*=\s*\[(.*?)\]", section.group(1))
+ assert entry, "[tool.setuptools.package-data] declares nothing for sprite_gen"
+ return re.findall(r'"([^"]+)"', entry.group(1))
+
+
+def _curator_assets() -> list[Path]:
+ return sorted(p for p in CURATOR_DIR.rglob("*") if p.is_file())
+
+
+def _collected_package_data() -> set[str]:
+ """The files the declared patterns actually collect, expanded the way the build does.
+
+ setuptools' `build_py.find_data_files` runs each pattern through `glob(..., recursive=True)`
+ rooted at the package source dir and keeps the regular files. That expansion is the whole
+ contract: in it a lone `*` stops at a directory boundary (`**` is what descends), which is
+ exactly where a hand-listed pattern silently loses a nested asset.
+ """
+ collected: set[str] = set()
+ for pattern in _declared_package_data():
+ for hit in glob.glob(os.path.join(glob.escape(str(PACKAGE_DIR)), pattern), recursive=True):
+ if os.path.isfile(hit):
+ collected.add(Path(hit).relative_to(PACKAGE_DIR).as_posix())
+ return collected
+
+
+_BUILD_WHEEL = (
+ "import sys\n"
+ "from setuptools import build_meta\n"
+ "sys.stdout.write(build_meta.build_wheel(sys.argv[1]))\n"
+)
+
+
[email protected](scope="module")
+def wheel_names(tmp_path_factory: pytest.TempPathFactory) -> set[str]:
+ """Every path inside a wheel built from this tree — the packaging ground truth.
+
+ Built from a copy so the build's own scratch (`build/`, `*.egg-info`) never lands in the
+ checkout, and with the backend called directly (no build isolation) so the test needs no
+ network.
+ """
+ if importlib.util.find_spec("setuptools") is None:
+ pytest.skip("setuptools — the build backend pyproject.toml declares — is not importable "
+ "in this interpreter, so no wheel can be built here to inspect")
+ project = tmp_path_factory.mktemp("project")
+ for name in ("pyproject.toml", "README.md", "LICENSE"):
+ shutil.copy2(ROOT / name, project / name)
+ shutil.copytree(PACKAGE_DIR, project / PACKAGE_DIR.name,
+ ignore=shutil.ignore_patterns("__pycache__"))
+ out = tmp_path_factory.mktemp("wheel")
+ built_by = subprocess.run([sys.executable, "-c", _BUILD_WHEEL, str(out)],
+ cwd=project, capture_output=True, text=True)
+ assert built_by.returncode == 0, (
+ f"the declared build backend could not build this project:\n{built_by.stderr}")
+ built = list(out.glob("*.whl"))
+ assert len(built) == 1, f"expected exactly one wheel, got {built}"
+ with zipfile.ZipFile(built[0]) as zf:
+ return set(zf.namelist())
+
+
+def _string_constants(tree: ast.AST) -> list[str]:
+ """Every string literal except docstrings.
+
+ Docstrings are prose about the repo (`python3 scripts/interpolate_frames.py …` is a
+ documented call form) — the contract is about paths the code actually builds.
+ """
+ docstrings = set()
+ for node in ast.walk(tree):
+ if isinstance(node, (ast.Module, ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef)):
+ body = getattr(node, "body", [])
+ if body and isinstance(body[0], ast.Expr) and isinstance(body[0].value, ast.Constant) \
+ and isinstance(body[0].value.value, str):
+ docstrings.add(id(body[0].value))
+ return [n.value for n in ast.walk(tree)
+ if isinstance(n, ast.Constant) and isinstance(n.value, str) and id(n) not in docstrings]
+
+
+def test_curator_dir_lives_inside_the_installed_package() -> None:
+ # The SPA lives under a domain subpackage (serve/curator), so it is nested
+ # inside the package rather than a direct child — what matters is that it
+ # travels with the package (is importable-package-relative), not its depth.
+ assert CURATOR_DIR.is_relative_to(PACKAGE_DIR), (
+ f"the SPA has to travel with the package; CURATOR_DIR points outside it: {CURATOR_DIR}")
+ assert (CURATOR_DIR / "index.html").is_file()
+
+
+def test_the_spa_has_exactly_one_home() -> None:
+ """No `scripts/curator/` left behind to shadow it (No Silent Fallback)."""
+ assert not (ROOT / "scripts" / "curator").exists(), (
+ "two curator trees exist — whichever one the server does not read will rot silently")
+
+
+def test_the_package_data_patterns_collect_every_curator_asset() -> None:
+ """Not "does the asset look declared" but "does the declaration pick it up"."""
+ on_disk = {p.relative_to(PACKAGE_DIR).as_posix() for p in _curator_assets()}
+ missing = sorted(on_disk - _collected_package_data())
+
+ assert not missing, (
+ f"{len(missing)} SPA asset(s) survive no package-data pattern "
+ f"{_declared_package_data()} — {missing[:5]} — so they are absent from the wheel and "
+ f"404 for anyone who installed sprite-gen instead of cloning it")
+
+
+def test_the_built_wheel_carries_every_curator_asset(wheel_names: set[str]) -> None:
+ """The declaration is a claim; the wheel is the fact. Compare the fact to the disk."""
+ on_disk = {f"sprite_gen/serve/curator/{p.relative_to(CURATOR_DIR).as_posix()}"
+ for p in _curator_assets()}
+ in_wheel = {n for n in wheel_names if n.startswith("sprite_gen/serve/curator/")}
+
+ assert not sorted(on_disk - in_wheel), (
+ f"the built wheel is missing {sorted(on_disk - in_wheel)} — the SPA loads them from "
+ f"an installed sprite_gen, so an install serves a shell whose scripts 404")
+ assert not sorted(in_wheel - on_disk), (
+ f"the wheel carries curator files that are not in the tree: {sorted(in_wheel - on_disk)}")
+
+
+def test_the_built_wheel_carries_every_package_module(wheel_names: set[str]) -> None:
+ """Same fact-vs-claim check one level up: a subpackage may not go missing either.
+
+ A hand-listed `packages = ["sprite_gen"]` once dropped all of `sprite_gen/gen/`, and
+ `sprite-gen --help` (cli.py imports `gen` at module scope) died on every non-editable
+ install while the whole suite stayed green — editable installs map the source tree, so
+ they cannot see this class of defect at all.
+ """
+ on_disk = {p.relative_to(ROOT).as_posix() for p in PACKAGE_DIR.rglob("*.py")
+ if "__pycache__" not in p.parts}
+ missing = sorted(on_disk - wheel_names)
+
+ assert not missing, (
+ f"{len(missing)} module(s) are in the tree but not in the wheel: {missing[:5]} — "
+ f"an install imports what shipped, not what the checkout has")
+
+
+def test_the_spa_asks_only_for_assets_that_exist() -> None:
+ """Every `src=`/`href=` in index.html is a real file under the SPA root.
+
+ The load order in index.html is the SSoT for the split `src/*.js` modules, so a
+ renamed or dropped file shows up as a blank page, not as an error.
+ """
+ html = (CURATOR_DIR / "index.html").read_text(encoding="utf-8")
+ refs = re.findall(r'(?:src|href)="(/[^"]+)"', html)
+ assert refs, "index.html loads no assets — the SPA cannot be blank by accident"
+ missing = [r for r in refs if not (CURATOR_DIR / r.lstrip("/")).is_file()]
+
+ assert not missing, f"index.html references assets that are not in the SPA tree: {missing}"
+
+
[email protected]("module", sorted(p.relative_to(ROOT).as_posix()
+ for p in PACKAGE_DIR.rglob("*.py")))
+def test_the_package_never_reaches_into_the_scripts_wrappers(module: str) -> None:
+ tree = ast.parse((ROOT / module).read_text(encoding="utf-8"))
+ offenders = [s for s in _string_constants(tree) if s == "scripts" or SCRIPT_PATH.search(s)]
+
+ assert not offenders, (
+ f"{module} builds a path into scripts/ ({offenders}) — those wrappers are not "
+ f"installed, so this works in a checkout and fails in an install. Shell out with "
+ f"`-m sprite_gen.<module>` instead.")
diff --git a/tests/packaging/test_curation_cli_entrypoint.py b/tests/packaging/test_curation_cli_entrypoint.py
new file mode 100644
index 0000000..17a1167
--- /dev/null
+++ b/tests/packaging/test_curation_cli_entrypoint.py
@@ -0,0 +1,73 @@
+# SPDX-License-Identifier: Apache-2.0
+"""`sprite-gen curation` is the same program as the two older launch forms.
+
+The console script removes the "which interpreter?" question for the webview, but only if
+the subcommand is the *same* declaration and the *same* implementation as
+`python -m sprite_gen.serve.serve_curation` and the `scripts/serve_curation.py` wrapper. A copied
+argument list would pass a smoke test on the day it is written and drift on the next flag.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from conftest import help_options as _help_options
+from sprite_gen import cli
+from sprite_gen.serve import serve_curation
+
+ROOT = Path(__file__).resolve().parents[2]
+
+def test_curation_subcommand_reuses_the_webview_declaration() -> None:
+ """Identity, not equality: the CLI table points at the webview's own functions."""
+ _description, add_args, run_fn = cli.COMMANDS["curation"]
+
+ assert add_args is serve_curation.add_arguments
+ assert run_fn is serve_curation.run
+
+
+def test_every_launch_form_exposes_the_same_flags() -> None:
+ subcommand = _help_options("-m", "sprite_gen.cli", "curation")
+ module = _help_options("-m", "sprite_gen.serve.serve_curation")
+ wrapper = _help_options(str(ROOT / "scripts" / "serve_curation.py"))
+
+ assert subcommand == {"--run-dir", "--host", "--port", "--no-open", "--lang", "--help"}
+ assert subcommand == module == wrapper
+
+
+def test_subcommand_hands_the_parsed_arguments_to_the_server(fixture_run_dir, monkeypatch, capsys) -> None:
+ """The whole chain, unmocked except for the socket: parse -> kwargs -> serve.
+
+ `cli.main` calls `run_fn(**vars(args))`, so a renamed parameter or a dest mismatch
+ (`--no-open` -> `no_open`) is a TypeError here rather than at a user's first launch.
+ """
+ seen: dict = {}
+
+ class FakeServer:
+ def __init__(self, address, handler):
+ seen["address"] = address
+ self.server_address = address
+
+ def serve_forever(self):
+ raise KeyboardInterrupt
+
+ def server_close(self):
+ seen["closed"] = True
+
+ opened: list[str] = []
+ # The handler's config is class state; register it with monkeypatch so this test's
+ # `--lang ko` is restored and cannot leak into another test's run snapshot.
+ monkeypatch.setattr(serve_curation.CurationHandler, "lang", serve_curation.CurationHandler.lang)
+ monkeypatch.setattr(serve_curation.CurationHandler, "run_dir", serve_curation.CurationHandler.run_dir)
+ monkeypatch.setattr(serve_curation, "ThreadingHTTPServer", FakeServer)
+ monkeypatch.setattr(serve_curation.webbrowser, "open", opened.append)
+
+ code = cli.main(["curation", "--run-dir", str(fixture_run_dir),
+ "--host", "127.0.0.1", "--port", "8797", "--no-open", "--lang", "ko"])
+
+ assert code == 0
+ assert seen["address"] == ("127.0.0.1", 8797)
+ assert seen.get("closed") is True
+ assert opened == [], "--no-open still opened a browser"
+ assert serve_curation.CurationHandler.lang == "ko"
+ assert serve_curation.CurationHandler.run_dir == fixture_run_dir.resolve()
+ assert "http://127.0.0.1:8797/" in capsys.readouterr().out
diff --git a/tests/packaging/test_entrypoint_interpreter.py b/tests/packaging/test_entrypoint_interpreter.py
new file mode 100644
index 0000000..76d2b20
--- /dev/null
+++ b/tests/packaging/test_entrypoint_interpreter.py
@@ -0,0 +1,79 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Deployment-interpreter contract for the agent-facing entrypoints.
+
+The skill's dependencies (Pillow, NumPy) are declared in `pyproject.toml` and
+materialized into the repo-root `.venv` — the same venv the README quickstart
+and CI create. A global `python3` is whatever `$PATH` points at that day; on
+macOS that is a PEP 668 externally-managed homebrew CPython whose packages were
+installed by hand, so declaration and reality drift there (observed: Pillow
+present, NumPy absent — one dependency installed made the surface *look*
+provisioned).
+
+Agent-facing docs (`SKILL.md`, `docs/*.md`) are read by agents in shells that
+never activated the venv, so *every* invocation there must name the interpreter
+explicitly — the absolute skill-path form and the repo-relative
+`python3 scripts/<script>.py` form alike. The relative form is not safer: it was
+the shape that actually drifted (`docs/frame-interpolation.md` carried
+`python3 scripts/interpolate_frames.py` as its only command, with zero mentions
+of `venv`/`activate` anywhere in the file, and that script imports
+`sprite_gen.frames.extract` at module load).
+
+Only the README quickstart register stays out of scope, and it is out of scope
+by not being scanned at all: its relative examples follow an explicit
+`source .venv/bin/activate` line that resolves to this same interpreter.
+"""
+
+from __future__ import annotations
+
+import re
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[2]
+
+# An invocation is "agent-register" when it names a script or this package at
+# all: a path anchored outside the current directory (`$SPRITE_GEN_ROOT/...`,
+# the `$SG` shorthand docs/curation.md defines, the elliptical `.../<script>.py`
+# form), a repo-relative `scripts/<script>.py`, or `-m sprite_gen...`. These
+# files are the agent register in full, so every form needs the explicit
+# interpreter. Only the README quickstart may assume an activated shell, and it
+# is excluded by file, not by form (see `_agent_facing_docs`).
+_BARE_INTERPRETER = r"(?<![\w./-])python3?\s+"
+_AGENT_REGISTER_BARE = re.compile(
+ _BARE_INTERPRETER
+ + r"(?:"
+ + r"[\"']?(?:\$\{?(?:SPRITE_GEN_ROOT|SG)\b|\.\.\./)" # skill-absolute path
+ + r"|-m\s+sprite_gen" # or the package CLI
+ + r"|(?:\./)?(?:[\w.-]+/)*[\w-]+\.py\b" # or a repo-relative script
+ + r")"
+)
+
+
+def _agent_facing_docs() -> list[Path]:
+ return [ROOT / "SKILL.md", *sorted((ROOT / "docs").glob("*.md"))]
+
+
+def test_agent_facing_docs_never_invoke_a_global_python() -> None:
+ offenders: list[str] = []
+ for path in _agent_facing_docs():
+ for lineno, line in enumerate(path.read_text(encoding="utf-8").splitlines(), 1):
+ if _AGENT_REGISTER_BARE.search(line):
+ rel = path.relative_to(ROOT)
+ offenders.append(f"{rel}:{lineno}: {line.strip()}")
+ assert not offenders, (
+ "agent-facing commands must name the venv interpreter "
+ "($SPRITE_GEN_ROOT/.venv/bin/python), not a global python3:\n"
+ + "\n".join(offenders)
+ )
+
+
+def test_skill_md_owns_the_interpreter_rule() -> None:
+ """The rule has to live in SKILL.md, or the commands above are unexplained."""
+ text = (ROOT / "SKILL.md").read_text(encoding="utf-8")
+ assert ".venv/bin/python" in text, (
+ "SKILL.md must name the venv interpreter as the skill's runtime")
+ assert "실행 인터프리터" in text, (
+ "SKILL.md lost its runtime-interpreter gate section")
+ # No silent fallback (principle 6): there is exactly one interpreter, and a
+ # missing venv is created or fails loudly — never quietly swapped for python3.
+ assert "폴백 금지" in text, (
+ "SKILL.md must keep the no-fallback clause for the interpreter rule")
diff --git a/tests/packaging/test_layer_cli_entrypoint.py b/tests/packaging/test_layer_cli_entrypoint.py
new file mode 100644
index 0000000..17b7bbb
--- /dev/null
+++ b/tests/packaging/test_layer_cli_entrypoint.py
@@ -0,0 +1,56 @@
+# 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
new file mode 100644
index 0000000..f0139da
--- /dev/null
+++ b/tests/packaging/test_numpy_dependency_gate.py
@@ -0,0 +1,201 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Missing-NumPy contract for the agent-facing entrypoints.
+
+`tests/test_entrypoint_interpreter.py` locks the other half of the deployment
+question — that documented commands name the venv interpreter. This file locks
+what happens when someone runs one anyway on an interpreter that cannot import
+NumPy: it fails, before it does any work, naming the interpreter it ran under
+and the command that fixes it. A pure-Python fallback is not permitted
+(principle 6, SECURITY.md "Current Dependency Surface"), so "kept running,
+slower" is a failure of this contract rather than an outcome it tolerates.
+
+The absence is simulated with a `sitecustomize.py` on `PYTHONPATH` that installs
+a meta-path finder raising `ModuleNotFoundError` for `numpy`, so the real
+documented command line runs on the real interpreter and only the one import
+disappears. Every failing case is paired with the same command unblocked, so a
+green run cannot come from an entrypoint that was already broken.
+
+Two assertions carry this past the point where the vectorized code actually
+lands. The runtime ones hold whatever `sprite_gen/frames/extract.py` does, because the
+gate fires at package import, before any submodule runs. The static one keeps it
+that way: a module that imports NumPy directly would fail with a bare
+`No module named 'numpy'`, which names neither the interpreter nor the fix.
+"""
+
+from __future__ import annotations
+
+import ast
+import os
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+
+ROOT = Path(__file__).resolve().parents[2]
+GATE = Path("sprite_gen/_deps.py")
+
+# Shipped code only. The test suite and the plan harnesses may import NumPy
+# directly — they are not what an agent runs.
+_SHIPPED_TREES = (ROOT / "sprite_gen", ROOT / "scripts")
+
+# Documented pipeline entrypoints that must be in the scanned population below;
+# an AST scan that quietly returned nothing would parametrize into zero cases.
+_CORE_ENTRYPOINTS = {
+ "extract_sprite_row_frames.py",
+ "prepare_sprite_run.py",
+ "compose_sprite_atlas.py",
+ "serve_curation.py",
+}
+
+_BLOCKER = """\
+import sys
+
+
+class _NoNumpy:
+ def find_spec(self, fullname, path=None, target=None):
+ if fullname == "numpy" or fullname.startswith("numpy."):
+ raise ModuleNotFoundError(f"No module named {fullname!r}", name=fullname)
+ return None
+
+
+sys.meta_path.insert(0, _NoNumpy())
+"""
+
+
+def _module_level(tree: ast.Module):
+ """Statements that run on import — function and class bodies do not."""
+ stack = list(tree.body)
+ while stack:
+ node = stack.pop()
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
+ continue
+ yield node
+ stack.extend(ast.iter_child_nodes(node))
+
+
+def _imports_at_load(path: Path, package: str) -> bool:
+ for node in _module_level(ast.parse(path.read_text(encoding="utf-8"))):
+ if isinstance(node, ast.Import):
+ if any(a.name == package or a.name.startswith(f"{package}.") for a in node.names):
+ return True
+ elif isinstance(node, ast.ImportFrom):
+ module = node.module or ""
+ if node.level == 0 and (module == package or module.startswith(f"{package}.")):
+ return True
+ return False
+
+
+def _imports_numpy_anywhere(path: Path) -> bool:
+ """Direct NumPy imports, including the dynamic spellings, at any nesting depth."""
+ for node in ast.walk(ast.parse(path.read_text(encoding="utf-8"))):
+ if isinstance(node, ast.Import):
+ if any(a.name == "numpy" or a.name.startswith("numpy.") for a in node.names):
+ return True
+ elif isinstance(node, ast.ImportFrom):
+ module = node.module or ""
+ if node.level == 0 and (module == "numpy" or module.startswith("numpy.")):
+ return True
+ elif isinstance(node, ast.Call):
+ func = node.func
+ name = func.attr if isinstance(func, ast.Attribute) else getattr(func, "id", None)
+ if name in {"import_module", "__import__"} and node.args:
+ arg = node.args[0]
+ if isinstance(arg, ast.Constant) and isinstance(arg.value, str):
+ if arg.value.split(".")[0] == "numpy":
+ return True
+ return False
+
+
+def _entry_scripts() -> list[Path]:
+ """The `scripts/*.py` that load the package — i.e. the ones that reach the gate.
+
+ Derived rather than listed: a script that stops importing `sprite_gen` also
+ stops needing NumPy, and one that starts importing it joins this population
+ without anyone remembering to add it here.
+ """
+ return sorted(p for p in (ROOT / "scripts").glob("*.py") if _imports_at_load(p, "sprite_gen"))
+
+
+# The registers SKILL.md documents, plus a bare package import for downstream importers.
+COMMANDS = {"package import": ["-c", "import sprite_gen"], "cli module": ["-m", "sprite_gen.cli", "--help"]}
+COMMANDS.update({path.name: [str(path), "--help"] for path in _entry_scripts()})
+
+
+def _run(args: list[str], *, numpy_blocked: bool, tmp_path: Path) -> subprocess.CompletedProcess:
+ env = dict(os.environ)
+ if numpy_blocked:
+ (tmp_path / "sitecustomize.py").write_text(_BLOCKER, encoding="utf-8")
+ env["PYTHONPATH"] = os.pathsep.join(
+ [str(tmp_path), env.get("PYTHONPATH", "")]).rstrip(os.pathsep)
+ return subprocess.run(
+ [sys.executable, *args], cwd=ROOT, env=env, capture_output=True, text=True, timeout=180)
+
+
+def test_the_scanned_entrypoints_are_the_real_ones() -> None:
+ """Anti-vacuity: the parametrization below is derived, so it must be checked."""
+ found = {path.name for path in _entry_scripts()}
+
+ assert _CORE_ENTRYPOINTS <= found, (
+ f"documented entrypoints missing from the scan: {sorted(_CORE_ENTRYPOINTS - found)}")
+
+
[email protected]("register", sorted(COMMANDS))
+def test_entrypoint_without_numpy_fails_loudly_with_the_install_path(
+ register: str, tmp_path: Path
+) -> None:
+ proc = _run(COMMANDS[register], numpy_blocked=True, tmp_path=tmp_path)
+
+ assert proc.returncode != 0, (
+ f"{register} kept running without NumPy — there is no pure-Python fallback for it to "
+ f"keep running on:\n{proc.stdout}")
+ assert "usage:" not in proc.stdout, (
+ f"{register} produced entrypoint output before failing; the gate must fire at import, "
+ f"not partway through a run:\n{proc.stdout}")
+ stderr = proc.stderr
+ assert "NumPy" in stderr, f"{register} failure never names NumPy:\n{stderr}"
+ assert sys.executable in stderr, (
+ f"{register} failure does not name the interpreter it ran under, which is the thing the "
+ f"reader has to change:\n{stderr}")
+ assert f"{ROOT}/.venv/bin/python -m pip install -e {ROOT}" in stderr, (
+ f"{register} failure does not spell out the install command for the skill venv:\n{stderr}")
+
+
[email protected]("register", sorted(COMMANDS))
+def test_the_same_entrypoint_succeeds_when_numpy_is_importable(
+ register: str, tmp_path: Path
+) -> None:
+ """Control: the failures above come from the blocked import, not a broken command."""
+ proc = _run(COMMANDS[register], numpy_blocked=False, tmp_path=tmp_path)
+
+ assert proc.returncode == 0, f"{register} fails even with NumPy present:\n{proc.stderr}"
+
+
+def test_numpy_is_imported_in_exactly_one_shipped_module() -> None:
+ """The gate cannot be bypassed. A direct `import numpy` elsewhere still fails loudly, but
+ with a bare `No module named 'numpy'` that names neither interpreter nor install command."""
+ importers = sorted(
+ path.relative_to(ROOT)
+ for tree in _SHIPPED_TREES
+ for path in tree.rglob("*.py")
+ if _imports_numpy_anywhere(path))
+
+ assert importers == [GATE], (
+ f"shipped code must reach NumPy through {GATE} (`from sprite_gen._deps import np`), not "
+ f"by importing it directly; found: {[str(p) for p in importers]}")
+
+
+def test_the_gate_hands_back_the_real_numpy() -> None:
+ """No sentinel, no shim — `np` is NumPy itself, or the import raised."""
+ from sprite_gen import _deps
+
+ assert _deps.np is _deps.numpy
+ assert getattr(_deps.np, "__name__", None) == "numpy"
+
+
+def test_skill_md_documents_the_missing_numpy_behavior() -> None:
+ """An agent that hits the traceback reads SKILL.md next; the rule lives there."""
+ text = (ROOT / "SKILL.md").read_text(encoding="utf-8")
+
+ assert "NumPy 가 없는 인터프리터" in text, (
+ "SKILL.md lost the clause telling agents what a NumPy-less interpreter does")
diff --git a/tests/packaging/test_package_surface.py b/tests/packaging/test_package_surface.py
new file mode 100644
index 0000000..d7fdb55
--- /dev/null
+++ b/tests/packaging/test_package_surface.py
@@ -0,0 +1,144 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Import-surface contract checks for downstream package consumers."""
+
+from __future__ import annotations
+
+import ast
+import importlib
+import re
+import subprocess
+import sys
+from importlib import metadata
+from pathlib import Path
+
+import pytest
+
+from sprite_gen._modules import qualified
+
+ROOT = Path(__file__).resolve().parents[2]
+PACKAGE_DIR = ROOT / "sprite_gen"
+
+PACKAGE_RUN_MODULES = [
+ "anchor",
+ "compose_atlas",
+ "compose_cycle",
+ "compose_gif",
+ "compose_layers",
+ "correction_loop",
+ "export_aseprite",
+ "export_pngs",
+ "extract",
+ "gen",
+ "generate_image",
+ "inspect",
+ "prepare",
+ "preview",
+ "score",
+ "serve_curation",
+ "slice_sheet",
+ "unpack_atlas",
+]
+
+CLI_HELPERS = [
+ "_parse_frame_order",
+ "_parse_frames",
+ "_parse_grid",
+]
+
+
+def _read_skill_version() -> str:
+ text = (ROOT / "SKILL.md").read_text(encoding="utf-8")
+ match = re.search(r"(?m)^version:\s*([^\s#]+)\s*$", text)
+ assert match, "SKILL.md frontmatter is missing version:"
+ return match.group(1)
+
+
[email protected]("module_name", PACKAGE_RUN_MODULES)
+def test_mcp_import_surface_modules_expose_callable_run(module_name: str) -> None:
+ module_path = "sprite_gen.gen" if module_name == "gen" else qualified(module_name)
+ module = importlib.import_module(module_path)
+
+ assert callable(getattr(module, "run", None)), f"{module_path}.run must be callable"
+
+
[email protected]("helper_name", CLI_HELPERS)
+def test_cli_parser_helpers_exist(helper_name: str) -> None:
+ cli = importlib.import_module("sprite_gen.cli")
+
+ assert callable(getattr(cli, helper_name, None)), f"sprite_gen.cli.{helper_name} must be callable"
+
+
+def _sibling_module_names() -> set[str]:
+ modules = {path.stem for path in PACKAGE_DIR.glob("*.py")}
+ modules |= {path.name for path in PACKAGE_DIR.iterdir() if (path / "__init__.py").is_file()}
+ return modules - {"__init__"}
+
+
+def _bare_sibling_imports(path: Path, siblings: set[str]) -> list[tuple[int, str]]:
+ """Imports of a sibling module by bare name, at any nesting depth.
+
+ Names that also exist in the stdlib (`inspect`) are left alone: inside the package an
+ absolute `import inspect` reaches the stdlib, which is what the caller means.
+ """
+ hits = []
+ for node in ast.walk(ast.parse(path.read_text(encoding="utf-8"))):
+ if isinstance(node, ast.Import):
+ names = [alias.name for alias in node.names]
+ elif isinstance(node, ast.ImportFrom) and node.level == 0:
+ names = [node.module or ""]
+ else:
+ continue
+ for name in names:
+ root = name.split(".")[0]
+ if root in siblings and root not in sys.stdlib_module_names:
+ hits.append((node.lineno, name))
+ return hits
+
+
+def test_package_modules_import_siblings_by_package_path() -> None:
+ """`from sprite_gen.curate.curation import …`, never `from curation import …`.
+
+ A bare sibling import only resolves when `scripts/` happens to be on `sys.path`, so it
+ survives `python scripts/<tool>.py` and dies under `python -m sprite_gen.<tool>` or any
+ downstream importer. The lazy ones die at request time, not import time — the curation
+ webview served its SPA and 500'd on `/api/run` with `No module named 'extract'`.
+ """
+ siblings = _sibling_module_names()
+ offenders = {
+ str(path.relative_to(ROOT)): _bare_sibling_imports(path, siblings)
+ for path in sorted(PACKAGE_DIR.rglob("*.py"))
+ if _bare_sibling_imports(path, siblings)
+ }
+
+ assert not offenders, f"bare sibling imports inside the package: {offenders}"
+
+
+def test_scripts_wrappers_reexport_their_package_module() -> None:
+ """The `scripts/*.py` call path documented in the READMEs keeps working after a module
+ moves into the package: the wrapper re-exports the implementation, entrypoints included."""
+ probe = (
+ "import runpy, sys;"
+ f"m = runpy.run_path({str(ROOT / 'scripts' / 'serve_curation.py')!r});"
+ "sys.exit(0 if callable(m.get('main')) and callable(m.get('build_run_state')) else 1)"
+ )
+ proc = subprocess.run([sys.executable, "-c", probe], cwd=ROOT, capture_output=True, text=True)
+
+ assert proc.returncode == 0, f"scripts/serve_curation.py stopped re-exporting the impl:\n{proc.stderr}"
+
+ helped = subprocess.run(
+ [sys.executable, str(ROOT / "scripts" / "serve_curation.py"), "--help"],
+ cwd=ROOT, capture_output=True, text=True)
+
+ assert helped.returncode == 0, helped.stderr
+ assert "--run-dir" in helped.stdout, (
+ f"the wrapper no longer runs the entrypoint — `python scripts/serve_curation.py` is a "
+ f"documented launch command:\n{helped.stdout}")
+
+
+def test_installed_distribution_version_matches_skill_frontmatter() -> None:
+ try:
+ installed_version = metadata.version("sprite-gen")
+ except metadata.PackageNotFoundError:
+ pytest.skip("sprite-gen distribution metadata is only available after editable/package install")
+
+ assert installed_version == _read_skill_version()
diff --git a/tests/packaging/test_pipeline_smoke.py b/tests/packaging/test_pipeline_smoke.py
new file mode 100644
index 0000000..7fcef1d
--- /dev/null
+++ b/tests/packaging/test_pipeline_smoke.py
@@ -0,0 +1,503 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Quickstart smoke: prepare -> extract -> compose on the golden fixture."""
+
+import json
+from pathlib import Path
+
+import pytest
+from PIL import Image
+
+from conftest import run_script
+
+
+def test_prepare_writes_run_contract(tmp_path: Path) -> None:
+ out_dir = tmp_path / "run"
+ result = run_script(
+ "prepare_sprite_run.py",
+ "--out-dir", str(out_dir),
+ "--character-id", "smokebot",
+ )
+ assert result.returncode == 0, result.stdout + result.stderr
+
+ request = json.loads((out_dir / "sprite-request.json").read_text(encoding="utf-8"))
+ assert request["kind"] == "sprite-gen-request"
+ assert request["character"]["id"] == "smokebot"
+ for state in request["states"]:
+ assert (out_dir / "prompts" / f"{state}.txt").is_file()
+ assert (out_dir / "references" / "layout-guides" / f"{state}.png").is_file()
+
+
+def test_prepare_records_fit_cli_flags_in_request(tmp_path: Path) -> None:
+ out_dir = tmp_path / "run"
+ result = run_script(
+ "prepare_sprite_run.py",
+ "--out-dir", str(out_dir),
+ "--character-id", "smokebot",
+ "--request-json", '{"fit": {"resample": "lanczos", "palette_size": 24}}',
+ "--fit-resample", "kcentroid",
+ "--fit-align-x", "foot-centroid",
+ "--fit-pixel-unfake",
+ "--fit-logical-height", "64",
+ "--fit-outline", "0.5",
+ )
+ assert result.returncode == 0, result.stdout + result.stderr
+
+ request = json.loads((out_dir / "sprite-request.json").read_text(encoding="utf-8"))
+ assert request["fit"] == {
+ "resample": "kcentroid", # CLI overrides the --request-json value
+ "align_x": "foot-centroid",
+ "pixel_unfake": True,
+ "logical_height": 64,
+ "outline": 0.5,
+ "palette_size": 24, # untouched --request-json key survives the merge
+ }
+
+
+def test_extract_then_compose_bakes_atlas(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
+
+ request = json.loads((fixture_run_dir / "sprite-request.json").read_text(encoding="utf-8"))
+ cell = request["cell"]
+ states = list(request["states"])
+ max_frames = max(int(entry["frames"]) for entry in request["states"].values())
+
+ with Image.open(fixture_run_dir / "sprite-sheet-alpha.png") as atlas:
+ assert atlas.size == (max_frames * cell["width"], len(states) * cell["height"])
+
+ manifest = json.loads((fixture_run_dir / "manifest.json").read_text(encoding="utf-8"))
+ assert manifest["curation_applied"] is False
+ layout_rows = manifest["frame_layout"]["rows"]
+ assert set(layout_rows) == set(states)
+ for row_index, state in enumerate(states):
+ cells = layout_rows[state]
+ assert len(cells) == int(request["states"][state]["frames"])
+ for column, rect in enumerate(cells):
+ assert rect == {
+ "x": column * cell["width"],
+ "y": row_index * cell["height"],
+ "w": cell["width"],
+ "h": cell["height"],
+ }
+
+
+def test_subset_reextract_preserves_other_states(fixture_run_dir: Path) -> None:
+ """A subset `--states` re-extract (auto-correction / single-row regeneration) preserves the
+ frames AND manifest rows of the states it does not rebuild, so a later compose still finds
+ every state (SSoT/Idempotency: a single-row re-extract must not delete other states)."""
+ import hashlib
+
+ run = fixture_run_dir
+ assert run_script("extract_sprite_row_frames.py", "--run-dir", str(run)).returncode == 0
+ states = sorted(json.loads((run / "sprite-request.json").read_text())["states"])
+ assert len(states) >= 2
+ target, others = states[0], states[1:]
+
+ before = {}
+ for state in others:
+ for frame in sorted((run / "frames" / state).glob("frame-*.png")):
+ if not frame.name.endswith(".plain.png"):
+ before[str(frame.relative_to(run))] = hashlib.sha256(frame.read_bytes()).hexdigest()
+ assert before
+
+ r = run_script("extract_sprite_row_frames.py", "--run-dir", str(run), "--states", target)
+ assert r.returncode == 0, r.stdout + r.stderr
+
+ for rel, digest in before.items(): # non-target frame bytes preserved
+ assert (run / rel).is_file(), f"{rel} deleted by subset re-extract"
+ assert hashlib.sha256((run / rel).read_bytes()).hexdigest() == digest
+ manifest = json.loads((run / "frames" / "frames-manifest.json").read_text())
+ assert sorted(row["state"] for row in manifest["rows"]) == states # manifest keeps all rows
+ compose = run_script("compose_sprite_atlas.py", "--run-dir", str(run))
+ assert compose.returncode == 0, compose.stdout + compose.stderr # was exit 1 before the fix
+
+
+def test_failed_subset_reextract_preserves_prior_generation(fixture_run_dir: Path) -> None:
+ """A failed subset re-extract must leave the prior COMPLETE frames generation byte-intact
+ and discard staging (Atomicity: publish only on success). Otherwise a single-row
+ regeneration that fails would destroy the previously-good frames for that row."""
+ import hashlib
+
+ run = fixture_run_dir
+ assert run_script("extract_sprite_row_frames.py", "--run-dir", str(run)).returncode == 0
+ target = sorted(json.loads((run / "sprite-request.json").read_text())["states"])[0]
+
+ before = {str(p.relative_to(run)): hashlib.sha256(p.read_bytes()).hexdigest()
+ for p in (run / "frames").rglob("frame-*.png")}
+ prior_manifest = (run / "frames" / "frames-manifest.json").read_bytes()
+
+ (run / "raw" / f"{target}.png").unlink() # break the target's raw strip
+ r = run_script("extract_sprite_row_frames.py", "--run-dir", str(run), "--states", target)
+ assert r.returncode == 1 # failed loudly
+
+ for rel, digest in before.items(): # prior generation byte-intact
+ assert (run / rel).is_file(), f"{rel} destroyed by a failed subset re-extract"
+ assert hashlib.sha256((run / rel).read_bytes()).hexdigest() == digest
+ assert (run / "frames" / "frames-manifest.json").read_bytes() == prior_manifest
+ assert not (run / ".frames.sg-staging").exists() # staging discarded, no leak
+ assert run_script("compose_sprite_atlas.py", "--run-dir", str(run)).returncode == 0
+
+
+def test_failed_reextract_signal_reaches_correction_loop_consumer(fixture_run_dir: Path) -> None:
+ """The automatic correction loop drives error-driven regeneration off inspect's per-state
+ errors. A failed RE-extract keeps the prior good frames byte-intact, so inspect's own
+ frame-count check sees nothing wrong — the ONLY channel for 'this state's re-extract failed,
+ and why' is extract-failure.json (frames/ stays complete-only). This proves the strict-
+ atomicity fix keeps that signal wired, so auto-correction never goes blind."""
+ from sprite_gen.qa.inspect import _manifest_state_notes
+
+ run = fixture_run_dir
+ assert run_script("extract_sprite_row_frames.py", "--run-dir", str(run)).returncode == 0
+ target = sorted(json.loads((run / "sprite-request.json").read_text())["states"])[0]
+
+ (run / "raw" / f"{target}.png").unlink() # break only this state's raw strip
+ assert run_script("extract_sprite_row_frames.py", "--run-dir", str(run), "--states", target).returncode == 1
+
+ assert (run / "frames" / target).is_dir() # prior good frames intact (re-extract)
+ assert (run / "extract-failure.json").is_file() # signal recorded OUTSIDE frames/
+ _row, errors, _warnings = _manifest_state_notes(run, target)
+ assert errors and all(e.startswith(f"{target}:") for e in errors), errors # consumer reads it
+
+
+def test_successful_extract_clears_prior_failure_evidence(fixture_run_dir: Path) -> None:
+ """A success resolves any prior failure: extract-failure.json must be removed so inspect and
+ the correction loop never re-flag a now-good state with a stale signal (Consistency)."""
+ from sprite_gen.qa.inspect import _manifest_state_notes
+
+ run = fixture_run_dir
+ assert run_script("extract_sprite_row_frames.py", "--run-dir", str(run)).returncode == 0
+ target = sorted(json.loads((run / "sprite-request.json").read_text())["states"])[0]
+
+ raw = run / "raw" / f"{target}.png"
+ saved = raw.read_bytes()
+ raw.unlink()
+ assert run_script("extract_sprite_row_frames.py", "--run-dir", str(run), "--states", target).returncode == 1
+ assert (run / "extract-failure.json").is_file() # failure recorded
+
+ raw.write_bytes(saved) # fix the input, re-extract succeeds
+ assert run_script("extract_sprite_row_frames.py", "--run-dir", str(run), "--states", target).returncode == 0
+ assert not (run / "extract-failure.json").exists() # success cleared the stale signal
+ _row, errors, _warnings = _manifest_state_notes(run, target)
+ assert not errors # consumer sees a clean state again
+
+
+def test_subset_success_preserves_other_state_failure(fixture_run_dir: Path) -> None:
+ """A subset --states extract is the formal single-row / auto-correction path: it only
+ determines the outcome of the states it targets. A SUCCESS on one state must never erase
+ another state's still-unresolved failure — else the correction loop goes blind to it
+ (Consistency / No Silent Fallback). walk-success must keep idle's failure signal."""
+ from sprite_gen.qa.inspect import _manifest_state_notes
+
+ run = fixture_run_dir
+ assert run_script("extract_sprite_row_frames.py", "--run-dir", str(run)).returncode == 0
+ (run / "raw" / "idle.png").unlink() # break only idle
+ assert run_script("extract_sprite_row_frames.py", "--run-dir", str(run), "--states", "idle").returncode == 1
+ assert run_script("extract_sprite_row_frames.py", "--run-dir", str(run), "--states", "walk").returncode == 0
+
+ assert (run / "extract-failure.json").is_file() # walk-success did NOT delete it
+ _row, idle_errors, _w = _manifest_state_notes(run, "idle")
+ assert idle_errors and all(e.startswith("idle:") for e in idle_errors), idle_errors # idle still failed
+ _row, walk_errors, _w = _manifest_state_notes(run, "walk")
+ assert not walk_errors # walk is resolved — no stale signal
+
+
+def test_consecutive_state_failures_accumulate_in_evidence(fixture_run_dir: Path) -> None:
+ """A new failure must not overwrite a different state's prior unresolved failure — the
+ evidence merges per state. Break idle, then walk; both failures must stay visible."""
+ from sprite_gen.qa.inspect import _manifest_state_notes
+
+ run = fixture_run_dir
+ assert run_script("extract_sprite_row_frames.py", "--run-dir", str(run)).returncode == 0
+ (run / "raw" / "idle.png").unlink()
+ assert run_script("extract_sprite_row_frames.py", "--run-dir", str(run), "--states", "idle").returncode == 1
+ (run / "raw" / "walk.png").unlink()
+ assert run_script("extract_sprite_row_frames.py", "--run-dir", str(run), "--states", "walk").returncode == 1
+
+ _row, idle_errors, _w = _manifest_state_notes(run, "idle")
+ _row, walk_errors, _w = _manifest_state_notes(run, "walk")
+ assert idle_errors, "idle failure was overwritten by the later walk failure"
+ assert walk_errors, "walk failure missing"
+
+
+def test_commit_generation_rolls_back_both_surfaces_on_evidence_failure(tmp_path, monkeypatch):
+ """The frames swap and the failure-evidence update are ONE publish transaction: if the
+ evidence write fails, BOTH canonical surfaces must roll back to their pre-commit state — the
+ run must never end with a new frames generation beside a stale failure record (Atomicity)."""
+ from sprite_gen.frames import extract
+
+ run = tmp_path / "run"
+ for st, tag in (("idle", b"IDLE_OLD"), ("walk", b"WALK_OLD")): # prior complete generation
+ (run / "frames" / st).mkdir(parents=True)
+ (run / "frames" / st / "frame-0.png").write_bytes(tag)
+ prior_evidence = {"ok": False, "errors": ["idle: broke"], "warnings": [], "rows": []}
+ (run / "extract-failure.json").write_text(json.dumps(prior_evidence), encoding="utf-8")
+ staging = run / ".frames.sg-staging" # new generation (walk rebuilt)
+ for st, tag in (("idle", b"IDLE_OLD"), ("walk", b"WALK_NEW")):
+ (staging / st).mkdir(parents=True)
+ (staging / st / "frame-0.png").write_bytes(tag)
+
+ real_write = extract.atomic_write_text
+ def flaky(target, text):
+ if Path(target).name == "extract-failure.json":
+ raise OSError("injected evidence write failure")
+ return real_write(target, text)
+ monkeypatch.setattr(extract, "atomic_write_text", flaky)
+
+ with pytest.raises(OSError):
+ # walk success with idle still failed -> merged errors [idle] -> evidence WRITE -> boom
+ extract._commit_generation(run, staging, {"ok": True, "errors": [], "warnings": [], "rows": []},
+ {"walk"}, {"idle", "walk"})
+
+ assert (run / "frames" / "walk" / "frame-0.png").read_bytes() == b"WALK_OLD" # not the new gen
+ assert (run / "frames" / "idle" / "frame-0.png").read_bytes() == b"IDLE_OLD"
+ assert json.loads((run / "extract-failure.json").read_text()) == prior_evidence # evidence intact
+ assert not (run / ".frames.sg-backup").exists() # no backup leak
+ assert not (run / ".extract-failure.sg-backup").exists()
+
+
+# Broken canonical records that must all fail loud, NOT be read as empty/absent. Beyond
+# unparseable JSON: a syntactically-valid `{}`, a missing required field, a wrong `ok`, an
+# empty failure `errors`, or a row without a `state` are all schema corruption (No Silent
+# Fallback — an existing-but-broken record never reads as "all clear").
+_BROKEN_MANIFESTS = [
+ "{ malformed", # unparseable
+ "{}", # empty dict (missing all)
+ '{"ok": false, "rows": [], "errors": [], "warnings": []}', # wrong ok (must be true)
+ '{"ok": true, "errors": [], "warnings": []}', # missing rows
+ '{"ok": true, "rows": [{"files": []}], "errors": [], "warnings": []}', # row without state
+]
+_BROKEN_EVIDENCE = [
+ "{ malformed", # unparseable
+ "{}", # empty dict (missing all)
+ '{"ok": true, "errors": ["idle: x"], "warnings": [], "rows": []}', # wrong ok (must be false)
+ '{"ok": false, "errors": [], "warnings": [], "rows": []}', # empty errors
+ '{"ok": false, "warnings": [], "rows": []}', # missing errors
+ '{"ok": false, "errors": [null], "warnings": [], "rows": []}', # null error entry (would be silently dropped)
+ '{"ok": false, "errors": ["no state prefix"], "warnings": [], "rows": []}', # not state-scoped
+]
+
+
[email protected]("payload", _BROKEN_EVIDENCE)
+def test_commit_fails_loud_on_broken_failure_evidence(fixture_run_dir: Path, payload: str) -> None:
+ """WRITER path: a subset --states success reads the prior extract-failure.json to merge. A
+ broken record (unparseable OR valid-but-wrong-schema, incl. `{}`) must fail loud, never be
+ read as 'no failures' and silently dropped on the successful publish (No Silent Fallback)."""
+ run = fixture_run_dir
+ assert run_script("extract_sprite_row_frames.py", "--run-dir", str(run)).returncode == 0
+ (run / "extract-failure.json").write_text(payload, encoding="utf-8")
+
+ r = run_script("extract_sprite_row_frames.py", "--run-dir", str(run), "--states", "walk")
+ assert r.returncode != 0, f"commit silently accepted broken evidence: {payload!r}"
+ assert "failure evidence" in (r.stdout + r.stderr).lower()
+ assert (run / "extract-failure.json").read_text(encoding="utf-8") == payload # not deleted/rewritten
+
+
[email protected]("payload", _BROKEN_EVIDENCE)
+def test_inspect_fails_loud_on_broken_failure_evidence(fixture_run_dir: Path, payload: str) -> None:
+ """READER path: the correction loop reads per-state failures through inspect_run. A broken
+ extract-failure.json must fail loud on the read too — never be read as 'no failures' — or an
+ unresolved-failure run is judged all-clear (No Silent Fallback)."""
+ run = fixture_run_dir
+ assert run_script("extract_sprite_row_frames.py", "--run-dir", str(run)).returncode == 0
+ (run / "extract-failure.json").write_text(payload, encoding="utf-8")
+
+ r = run_script("inspect_sprite_run.py", "--run-dir", str(run), "--no-write")
+ assert r.returncode != 0, f"inspect silently accepted broken evidence: {payload!r}"
+ assert "failure evidence" in (r.stdout + r.stderr).lower()
+ assert (run / "extract-failure.json").exists() # not silently removed
+
+
[email protected]("payload", _BROKEN_MANIFESTS)
+def test_subset_reextract_fails_loud_on_broken_prior_manifest(fixture_run_dir: Path, payload: str) -> None:
+ """WRITER path: a subset --states re-extract seeds untouched states from the prior complete
+ generation. A broken prior manifest (unparseable OR `{}`/missing-rows/wrong-ok/row-without-
+ state) must fail loud BEFORE staging — never be read as 'no prior rows' and then publish an
+ incomplete manifest that disagrees with the carried frame tree (No Silent Fallback /
+ Consistency / Atomicity). The prior generation stays byte-intact and no staging leaks."""
+ import hashlib
+
+ run = fixture_run_dir
+ assert run_script("extract_sprite_row_frames.py", "--run-dir", str(run)).returncode == 0
+ (run / "frames" / "frames-manifest.json").write_text(payload, encoding="utf-8")
+ before = {str(p.relative_to(run)): hashlib.sha256(p.read_bytes()).hexdigest()
+ for p in (run / "frames").rglob("*") if p.is_file()}
+
+ r = run_script("extract_sprite_row_frames.py", "--run-dir", str(run), "--states", "walk")
+ assert r.returncode != 0, f"subset re-extract silently accepted broken manifest: {payload!r}"
+ assert "frames manifest" in (r.stdout + r.stderr).lower()
+ after = {str(p.relative_to(run)): hashlib.sha256(p.read_bytes()).hexdigest()
+ for p in (run / "frames").rglob("*") if p.is_file()}
+ assert after == before, "prior generation was mutated by a failed subset re-extract"
+ assert not (run / ".frames.sg-staging").exists() # failed before staging created
+
+
+def test_inspect_fails_loud_on_broken_frames_manifest(fixture_run_dir: Path) -> None:
+ """READER path: inspect reads the frames manifest too; an `{}`-broken manifest must fail loud,
+ not read as an empty generation (No Silent Fallback)."""
+ run = fixture_run_dir
+ assert run_script("extract_sprite_row_frames.py", "--run-dir", str(run)).returncode == 0
+ (run / "frames" / "frames-manifest.json").write_text("{}", encoding="utf-8")
+
+ r = run_script("inspect_sprite_run.py", "--run-dir", str(run), "--no-write")
+ assert r.returncode != 0, "inspect silently accepted a broken frames manifest"
+ assert "frames manifest" in (r.stdout + r.stderr).lower()
+
+
[email protected]("script,extra", [
+ ("compose_sprite_atlas.py", []),
+ ("export_curated_pngs.py", []),
+ ("preview_animation.py", []),
+ ("compose_sprite_gif.py", []),
+ ("compose_selected_cycle.py", ["--state", "walk", "--name", "cyc"]),
+])
+def test_finished_generation_consumers_fail_loud_on_broken_manifest(fixture_run_dir: Path, script, extra) -> None:
+ """Every consumer of a completed generation validates the manifest before producing output.
+ A `{}`-broken manifest must fail loud — never yield stale/empty output from unvalidated
+ physical frames (No Silent Fallback / Consistency)."""
+ run = fixture_run_dir
+ assert run_script("extract_sprite_row_frames.py", "--run-dir", str(run)).returncode == 0
+ (run / "frames" / "frames-manifest.json").write_text("{}", encoding="utf-8")
+
+ r = run_script(script, "--run-dir", str(run), *extra)
+ assert r.returncode != 0, f"{script} silently accepted a broken manifest"
+ assert "frames manifest" in (r.stdout + r.stderr).lower()
+
+
[email protected]("mutate,expect", [
+ (lambda m: m.update(rows=[]), "missing row"), # empty rows, but frames exist
+ (lambda m: m["rows"].pop(), "missing row"), # drop a state's row
+ (lambda m: m["rows"].append({**m["rows"][0]}), "duplicate"), # duplicate state row
+])
+def test_consumer_fails_loud_on_inconsistent_manifest(fixture_run_dir: Path, mutate, expect) -> None:
+ """Beyond JSON schema: a manifest that disagrees with the request/frame tree (empty/missing/
+ duplicate rows) must fail loud, never let a consumer build output from a partial generation
+ (Consistency / No Silent Fallback)."""
+ run = fixture_run_dir
+ assert run_script("extract_sprite_row_frames.py", "--run-dir", str(run)).returncode == 0
+ p = run / "frames" / "frames-manifest.json"
+ m = json.loads(p.read_text()); mutate(m); p.write_text(json.dumps(m), encoding="utf-8")
+
+ r = run_script("compose_sprite_atlas.py", "--run-dir", str(run))
+ assert r.returncode != 0, f"consumer accepted inconsistent manifest ({expect})"
+ assert expect in (r.stdout + r.stderr).lower()
+
+
[email protected]("tool,extra", [("compose_sprite_atlas.py", []), ("compose_sprite_gif.py", [])])
+def test_consumer_fails_loud_on_deleted_frame(fixture_run_dir: Path, tool, extra) -> None:
+ """A physical frame the manifest references is deleted → the consumer fails loud, never
+ silently produces a shorter output (No Silent Fallback)."""
+ run = fixture_run_dir
+ assert run_script("extract_sprite_row_frames.py", "--run-dir", str(run)).returncode == 0
+ victim = sorted((run / "frames" / "idle").glob("frame-*.png"))[0] # a canonical frame (fixture is non-pp)
+ victim.unlink()
+
+ r = run_script(tool, "--run-dir", str(run), *extra)
+ assert r.returncode != 0, f"{tool} accepted a missing frame"
+ assert "missing frame" in (r.stdout + r.stderr).lower()
+
+
+def test_orphan_frames_without_manifest_fail_loud(fixture_run_dir: Path) -> None:
+ """Physical frames with NO manifest are an orphan/stale generation, not a fresh scaffold —
+ consumers and inspect must fail loud, not read the stale frames as a valid generation."""
+ run = fixture_run_dir
+ assert run_script("extract_sprite_row_frames.py", "--run-dir", str(run)).returncode == 0
+ (run / "frames" / "frames-manifest.json").unlink()
+
+ for tool, extra in (("compose_sprite_atlas.py", []), ("inspect_sprite_run.py", ["--no-write"])):
+ r = run_script(tool, "--run-dir", str(run), *extra)
+ assert r.returncode != 0, f"{tool} accepted orphan frames"
+ assert "orphan" in (r.stdout + r.stderr).lower()
+
+
+def test_empty_files_generation_fails_loud(fixture_run_dir: Path) -> None:
+ """A manifest that claims every state but with empty `files` over deleted frames (zero physical
+ frames) must fail loud on every consumer — never be exposed/consumed as a present-but-empty
+ generation (No Silent Fallback / Consistency). This is validator's exact counterexample.
+
+ 실시간 계약 이후 갱신 (2026-07-15): raw 가 남아 있으면 compose 는 손상을
+ fail 하는 대신 heal(재유도)로 복구한다 — 그것도 '조용한 소비'가 아니라
+ 관측 가능한 복구다. fail-loud 보장은 복구 재료(raw)마저 없는 경우로 남는다."""
+ import shutil
+
+ run = fixture_run_dir
+ assert run_script("extract_sprite_row_frames.py", "--run-dir", str(run)).returncode == 0
+
+ def corrupt():
+ for d in (run / "frames").iterdir():
+ if d.is_dir():
+ shutil.rmtree(d) # 0 physical frames
+ p = run / "frames" / "frames-manifest.json"
+ m = json.loads(p.read_text())
+ m["rows"] = [{"state": r["state"], "files": [], "ok": True} for r in m["rows"]]
+ p.write_text(json.dumps(m), encoding="utf-8")
+
+ # raw 가 있으면: compose 가 자가치유하고 성공한다 (stderr 에 관측 가능)
+ corrupt()
+ healed = run_script("compose_sprite_atlas.py", "--run-dir", str(run))
+ assert healed.returncode == 0, healed.stdout + healed.stderr
+ assert "[heal]" in healed.stderr
+
+ # raw 가 없으면: 어떤 소비자도 손상 세대를 받아들이지 않는다 (fail loud)
+ corrupt()
+ shutil.rmtree(run / "raw")
+ for tool, extra in (("compose_sprite_atlas.py", []), ("preview_animation.py", []),
+ ("inspect_sprite_run.py", ["--no-write"])):
+ r = run_script(tool, "--run-dir", str(run), *extra)
+ assert r.returncode != 0, f"{tool} accepted an empty-files generation"
+ assert "no frame files" in (r.stdout + r.stderr).lower()
+
+
+def test_unknown_state_row_fails_loud(fixture_run_dir: Path) -> None:
+ """request states and manifest rows must match BOTH directions: a 'ghost' state row + physical
+ frames not in the request must fail loud, not be rendered by compose/preview while serve (which
+ is request-driven) hides it — a per-consumer divergence (Consistency / SSoT). validator's repro."""
+ import shutil
+
+ run = fixture_run_dir
+ assert run_script("extract_sprite_row_frames.py", "--run-dir", str(run)).returncode == 0
+ # add a ghost state: physical frame + a matching manifest row, but no request entry
+ ghost_dir = run / "frames" / "ghost"
+ ghost_dir.mkdir()
+ shutil.copy(sorted((run / "frames" / "idle").glob("frame-*.png"))[0], ghost_dir / "frame-0.png")
+ p = run / "frames" / "frames-manifest.json"
+ m = json.loads(p.read_text())
+ m["rows"].append({"state": "ghost", "frames": 1, "files": ["frames/ghost/frame-0.png"], "ok": True})
+ p.write_text(json.dumps(m), encoding="utf-8")
+
+ for tool, extra in (("compose_sprite_atlas.py", []), ("preview_animation.py", []),
+ ("inspect_sprite_run.py", ["--no-write"])):
+ r = run_script(tool, "--run-dir", str(run), *extra)
+ assert r.returncode != 0, f"{tool} accepted an unknown 'ghost' state"
+ assert "not in the request" in (r.stdout + r.stderr).lower()
+
+
+def test_frame_count_mismatch_fails_loud(fixture_run_dir: Path) -> None:
+ """A manifest row whose canonical files disagree with the physical frame set (here: one file
+ dropped while the frame stays on disk) is an inconsistent generation — fail loud."""
+ run = fixture_run_dir
+ assert run_script("extract_sprite_row_frames.py", "--run-dir", str(run)).returncode == 0
+ p = run / "frames" / "frames-manifest.json"
+ m = json.loads(p.read_text())
+ m["rows"][0]["files"] = m["rows"][0]["files"][:-1] # drop one; physical still has it
+ p.write_text(json.dumps(m), encoding="utf-8")
+
+ r = run_script("compose_sprite_atlas.py", "--run-dir", str(run))
+ assert r.returncode != 0, "consumer accepted a files/physical-frame mismatch"
+ assert "!= physical" in (r.stdout + r.stderr).lower()
+
+
+def test_require_frames_manifest_distinguishes_absent_from_broken(tmp_path: Path) -> None:
+ """The shared finished-generation gate: {} for a genuinely absent manifest, but fail loud for
+ a present-but-broken one (absent-vs-broken, No Silent Fallback)."""
+ from sprite_gen.frames.extract import require_frames_manifest
+
+ run = tmp_path / "run"
+ (run / "frames").mkdir(parents=True)
+ with pytest.raises(SystemExit): # absent -> no finished generation
+ require_frames_manifest(run)
+ (run / "frames" / "frames-manifest.json").write_text("{}", encoding="utf-8")
+ with pytest.raises(SystemExit): # present-but-broken -> fail loud
+ require_frames_manifest(run)
diff --git a/tests/packaging/test_project_metadata.py b/tests/packaging/test_project_metadata.py
new file mode 100644
index 0000000..64bfe36
--- /dev/null
+++ b/tests/packaging/test_project_metadata.py
@@ -0,0 +1,42 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Regression checks for support-version documentation drift."""
+
+import re
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[2]
+
+
+def _declared_min_python() -> str:
+ pyproject = (ROOT / "pyproject.toml").read_text(encoding="utf-8")
+ match = re.search(r'^requires-python\s*=\s*">=(\d+\.\d+)"', pyproject, flags=re.MULTILINE)
+ assert match, "pyproject.toml must declare requires-python as a >= major.minor floor"
+ return match.group(1)
+
+
+def _version_tuple(version: str) -> tuple[int, int]:
+ major, minor = version.split(".")
+ return int(major), int(minor)
+
+
+def test_ci_matrix_covers_declared_minimum_python() -> None:
+ minimum = _declared_min_python()
+ workflow = (ROOT / ".github" / "workflows" / "ci.yml").read_text(encoding="utf-8")
+
+ matrix = re.search(r"python-version:\s*\[(?P<versions>[^\]]+)\]", workflow)
+ assert matrix, "CI must declare the setup-python matrix on one line"
+ versions = re.findall(r'"(\d+\.\d+)"', matrix.group("versions"))
+ assert versions, "CI Python matrix must include at least one version"
+
+ minimum_tuple = _version_tuple(minimum)
+ assert minimum in versions
+ assert min(_version_tuple(version) for version in versions) == minimum_tuple
+ assert all(_version_tuple(version) >= minimum_tuple for version in versions)
+
+
+def test_readme_names_declared_python_support_and_venv_requirement() -> None:
+ minimum = _declared_min_python()
+ readme = (ROOT / "README.md").read_text(encoding="utf-8")
+
+ assert f"CPython {minimum}+" in readme
+ assert "`venv`/`ensurepip`" in readme
diff --git a/tests/packaging/test_recolor_cli_entrypoint.py b/tests/packaging/test_recolor_cli_entrypoint.py
new file mode 100644
index 0000000..a40b2c3
--- /dev/null
+++ b/tests/packaging/test_recolor_cli_entrypoint.py
@@ -0,0 +1,52 @@
+# SPDX-License-Identifier: Apache-2.0
+"""`sprite-gen recolor` / `recolor-palette` are the same program as the wrappers.
+
+The console script is only safe if the CLI table points at the module's own
+argument declaration and run function — a copied flag list would pass a smoke
+test on the day it is written and drift on the next option.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from conftest import help_options as _help_options
+from sprite_gen import cli
+from sprite_gen.effects import recolor
+
+ROOT = Path(__file__).resolve().parents[2]
+
+def test_recolor_subcommand_reuses_module_declaration() -> None:
+ _description, add_args, run_fn = cli.COMMANDS["recolor"]
+ assert add_args is recolor.add_recolor_arguments
+ assert run_fn is recolor.run
+
+
+def test_recolor_palette_subcommand_reuses_module_declaration() -> None:
+ _description, add_args, run_fn = cli.COMMANDS["recolor-palette"]
+ assert add_args is recolor.add_palette_arguments
+ assert run_fn is recolor.run_palette
+
+
+def test_recolor_launch_forms_expose_the_same_flags() -> None:
+ subcommand = _help_options("-m", "sprite_gen.cli", "recolor")
+ wrapper = _help_options(str(ROOT / "scripts" / "recolor.py"))
+
+ expected = {
+ "--base",
+ "--run-dir",
+ "--atlas",
+ "--spec",
+ "--out-dir",
+ "--manifest",
+ "--alpha-threshold",
+ "--report",
+ "--help",
+ }
+ assert subcommand == expected
+ assert subcommand == wrapper
+
+
+def test_recolor_palette_cli_exposes_authoring_flags() -> None:
+ flags = _help_options("-m", "sprite_gen.cli", "recolor-palette")
+ assert flags == {"--base", "--out", "--alpha-threshold", "--max-colors", "--help"}
diff --git a/tests/packaging/test_version_ssot.py b/tests/packaging/test_version_ssot.py
new file mode 100644
index 0000000..7019d54
--- /dev/null
+++ b/tests/packaging/test_version_ssot.py
@@ -0,0 +1,27 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Release metadata version parity checks."""
+
+from __future__ import annotations
+
+import re
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[2]
+
+
+def _read_pyproject_version() -> str:
+ text = (ROOT / "pyproject.toml").read_text(encoding="utf-8")
+ match = re.search(r'(?m)^version\s*=\s*"([^"]+)"\s*$', text)
+ assert match, "pyproject.toml is missing [project] version"
+ return match.group(1)
+
+
+def _read_skill_version() -> str:
+ text = (ROOT / "SKILL.md").read_text(encoding="utf-8")
+ match = re.search(r"(?m)^version:\s*([^\s#]+)\s*$", text)
+ assert match, "SKILL.md frontmatter is missing version:"
+ return match.group(1)
+
+
+def test_pyproject_version_matches_skill_frontmatter_version() -> None:
+ assert _read_pyproject_version() == _read_skill_version()
diff --git a/tests/qa/test_inspect_score_loop.py b/tests/qa/test_inspect_score_loop.py
new file mode 100644
index 0000000..f7e136a
--- /dev/null
+++ b/tests/qa/test_inspect_score_loop.py
@@ -0,0 +1,114 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Automated inspect/score/correction-loop coverage."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+from conftest import run_script
+
+
+def test_inspect_scores_extracted_fixture(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
+
+ inspected = run_script("inspect_sprite_run.py", "--run-dir", str(fixture_run_dir))
+ assert inspected.returncode == 0, inspected.stdout + inspected.stderr
+ inspect_report = json.loads((fixture_run_dir / "sprite-inspect.report.json").read_text(encoding="utf-8"))
+ assert inspect_report["kind"] == "sprite-gen-inspect-report"
+ assert inspect_report["rows"][0]["metrics"]["histogram_intersection"]["min"] <= 1.0
+ assert inspect_report["rows"][0]["metrics"]["dhash_similarity"]["min"] <= 1.0
+ assert "motion_presence" in inspect_report["rows"][0]["metrics"]
+
+ scored = run_script(
+ "score_sprite_run.py",
+ "--inspect-report", str(fixture_run_dir / "sprite-inspect.report.json"),
+ )
+ assert scored.returncode == 0, scored.stdout + scored.stderr
+ score_report = json.loads((fixture_run_dir / "sprite-score.report.json").read_text(encoding="utf-8"))
+ assert score_report["ok"] is True
+ assert score_report["overall_score"] >= 90
+
+
+def test_raw_frame_count_defect_produces_correction_hint(fixture_run_dir: Path) -> None:
+ request_path = fixture_run_dir / "sprite-request.json"
+ request = json.loads(request_path.read_text(encoding="utf-8"))
+ request["states"] = {"walk": {**request["states"]["walk"], "frames": 5}}
+ request_path.write_text(json.dumps(request, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
+
+ inspected = run_script("inspect_sprite_run.py", "--run-dir", str(fixture_run_dir), "--states", "walk")
+ assert inspected.returncode == 1
+ scored = run_script(
+ "score_sprite_run.py",
+ "--inspect-report", str(fixture_run_dir / "sprite-inspect.report.json"),
+ )
+ assert scored.returncode == 1
+ score_report = json.loads((fixture_run_dir / "sprite-score.report.json").read_text(encoding="utf-8"))
+ assert score_report["ok"] is False
+ assert any("exactly 5 full-body poses" in hint for hint in score_report["hints"])
+
+
+def test_correction_loop_dry_run_preserves_best_candidate(fixture_run_dir: Path, tmp_path: Path) -> None:
+ request_path = fixture_run_dir / "sprite-request.json"
+ request = json.loads(request_path.read_text(encoding="utf-8"))
+ request["states"] = {"walk": {**request["states"]["walk"], "frames": 5}}
+ request_path.write_text(json.dumps(request, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
+
+ out_dir = tmp_path / "loop"
+ result = run_script(
+ "run_correction_loop.py",
+ "--run-dir", str(fixture_run_dir),
+ "--states", "walk",
+ "--out-dir", str(out_dir),
+ "--dry-run",
+ )
+ assert result.returncode == 1
+ loop_report = json.loads((out_dir / "correction-loop.report.json").read_text(encoding="utf-8"))
+ assert loop_report["dry_run"] is True
+ assert Path(loop_report["preserved_best"]).is_dir()
+ assert "exactly 5 full-body poses" in (out_dir / "attempt-1" / "correction-hints.txt").read_text(encoding="utf-8")
+
+
+def test_correction_loop_min_attempts_forces_provider_then_converges(fixture_run_dir: Path, tmp_path: Path) -> None:
+ extract = run_script("extract_sprite_row_frames.py", "--run-dir", str(fixture_run_dir))
+ assert extract.returncode == 0, extract.stdout + extract.stderr
+ provider = tmp_path / "copy_provider.py"
+ provider.write_text(
+ "import shutil,sys\nshutil.copytree(sys.argv[1], sys.argv[2])\n",
+ encoding="utf-8",
+ )
+ out_dir = tmp_path / "loop"
+ result = run_script(
+ "run_correction_loop.py",
+ "--run-dir", str(fixture_run_dir),
+ "--states", "walk",
+ "--out-dir", str(out_dir),
+ "--max-passes", "3",
+ "--min-attempts", "2",
+ "--provider-command", f"python3 {provider} {fixture_run_dir} {{next_run_dir}}",
+ )
+ assert result.returncode == 0, result.stdout + result.stderr
+ loop_report = json.loads((out_dir / "correction-loop.report.json").read_text(encoding="utf-8"))
+ assert loop_report["min_attempts"] == 2
+ assert len(loop_report["attempts"]) == 2
+ assert loop_report["attempts"][1]["ok"] is True
+ assert not (out_dir / "candidate-3").exists()
+
+
+def test_correction_loop_does_not_generate_after_last_attempt(fixture_run_dir: Path, tmp_path: Path) -> None:
+ request_path = fixture_run_dir / "sprite-request.json"
+ request = json.loads(request_path.read_text(encoding="utf-8"))
+ request["states"] = {"walk": {**request["states"]["walk"], "frames": 5}}
+ request_path.write_text(json.dumps(request, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
+ out_dir = tmp_path / "loop"
+ result = run_script(
+ "run_correction_loop.py",
+ "--run-dir", str(fixture_run_dir),
+ "--states", "walk",
+ "--out-dir", str(out_dir),
+ "--max-passes", "1",
+ "--provider-command", "python3 -c 'raise SystemExit(9)'",
+ )
+ assert result.returncode == 1
+ assert not (out_dir / "attempt-1" / "provider.log").exists()
diff --git a/tests/serve/test_curation_view_contract.py b/tests/serve/test_curation_view_contract.py
new file mode 100644
index 0000000..168bb4e
--- /dev/null
+++ b/tests/serve/test_curation_view_contract.py
@@ -0,0 +1,674 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Curation-view display contract (run-contract.md §3/§4): imported `_base`/`_refs`
+sources surface as the base row + generation-material chips, the self-report `contract`
+field is populated, and filenames with URL-special characters are percent-encoded so
+they actually serve (regression: an unencoded `#` in a ref filename became a URL
+fragment → 404)."""
+
+from __future__ import annotations
+
+import json
+import shutil
+import subprocess
+import sys
+import threading
+import urllib.request
+from functools import partial
+from http.server import ThreadingHTTPServer
+from pathlib import Path
+
+import pytest
+from PIL import Image
+
+ROOT = Path(__file__).resolve().parents[2]
+
+from sprite_gen.serve.serve_curation import CurationHandler, _url, build_run_state # noqa: E402
+from sprite_gen.frames.unpack_atlas import import_png_groups # noqa: E402
+
+
+def _png(path: Path, color=(80, 80, 80, 255), size=(48, 48)) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ Image.new("RGBA", size, color).save(path)
+
+
+def _build_import(tmp_path: Path, ref_names, with_base=True) -> Path:
+ pngs = tmp_path / "pngs"
+ if with_base:
+ _png(pngs / "_base" / "hero.png", size=(96, 96))
+ _png(pngs / "items" / "1-a.png")
+ _png(pngs / "items" / "2-b.png")
+ for name in ref_names:
+ _png(pngs / "items" / "_refs" / name)
+ out = tmp_path / "run"
+ import_png_groups(
+ out,
+ [{
+ "name": "items",
+ "paths": sorted((pngs / "items").glob("*.png")),
+ "labels": [],
+ "refs": sorted((pngs / "items" / "_refs").glob("*.png")),
+ }],
+ base_src=(pngs / "_base" / "hero.png") if with_base else None,
+ )
+ return out
+
+
+def _serve_status(run: Path, url: str) -> int:
+ CurationHandler.run_dir = run
+ CurationHandler.lang = "en"
+ srv = ThreadingHTTPServer(("127.0.0.1", 0), partial(CurationHandler))
+ threading.Thread(target=srv.serve_forever, daemon=True).start()
+ try:
+ return urllib.request.urlopen(f"http://127.0.0.1:{srv.server_address[1]}{url}").status
+ finally:
+ srv.shutdown()
+
+
+def test_imported_sources_expose_base_row_and_chips(tmp_path):
+ run = _build_import(tmp_path, ["anchor-idle.png", "guide-walk.png"])
+ st = build_run_state(run)
+ assert st["baseUrl"] == "/run/base-source.png"
+ roles = {(r["role"], r["name"]) for r in st["states"][0]["refs"]}
+ assert ("anchor", "anchor-idle.png") in roles
+ assert ("guide", "guide-walk.png") in roles
+ assert st["contract"] == {"base": True, "refs": True, "refsStates": 1, "grid": True, "sourceless": False}
+
+
+def test_sourceless_import_is_reported(tmp_path):
+ run = _build_import(tmp_path, [], with_base=False)
+ st = build_run_state(run)
+ assert st["baseUrl"] is None
+ assert st["states"][0]["refs"] == []
+ assert st["contract"]["sourceless"] is True
+
+
+def _checker_png(path: Path, pitch: int = 4, size: int = 48) -> None:
+ """A checkerboard PNG with a `pitch`-px block size so detect_pixel_pitch finds a grid."""
+ path.parent.mkdir(parents=True, exist_ok=True)
+ im = Image.new("RGBA", (size, size), (0, 0, 0, 255))
+ px = im.load()
+ for y in range(size):
+ for x in range(size):
+ if ((x // pitch) + (y // pitch)) % 2 == 0:
+ px[x, y] = (240, 240, 240, 255)
+ im.save(path)
+
+
+def test_special_char_state_name_keeps_pixel_grid(tmp_path):
+ """A special-char group/state name must not break auto pixel-grid measurement. The
+ frame url is percent-encoded for HTTP, but pixelScale is measured from the real
+ decoded file path (regression: measuring off the encoded url silently null-ed the
+ grid + reported contract.grid=false for special-char imports)."""
+ pngs = tmp_path / "pngs"
+ _checker_png(pngs / "walk" / "1-a.png")
+ _checker_png(pngs / "walk #한글 %" / "1-a.png") # same image, special-char group name
+ out = tmp_path / "run"
+ assert _run_import(pngs, out, "--force").returncode == 0
+ st = build_run_state(out)
+ plain = next(s for s in st["states"] if s["name"] == "walk")
+ special = next(s for s in st["states"] if s["name"] == "walk #한글 %")
+ assert plain["pixelScale"] is not None
+ assert special["pixelScale"] == plain["pixelScale"] # measured, not silently null
+ assert st["contract"]["grid"] is True
+ url = special["frames"][0]["url"] # frame url still percent-encoded + serves
+ assert "#" not in url and " " not in url
+ assert _serve_status(out, url) == 200
+
+
[email protected]("name", ["guide-a#b.png", "anchor-c d.png", "basis-100%done.png", "guide-café.png"])
+def test_special_char_ref_filename_is_url_encoded_and_serves(tmp_path, name):
+ run = _build_import(tmp_path, [name])
+ url = build_run_state(run)["states"][0]["refs"][0]["url"]
+ # nothing that breaks a URL (# → fragment) or an HTML attribute may survive raw
+ assert not any(c in url for c in '# "\'<>')
+ assert _serve_status(run, url) == 200
+
+
+def test_url_helper_encodes_only_unsafe_segments():
+ assert _url("run", "raw", "down_idle.png") == "/run/raw/down_idle.png" # unreserved unchanged
+ assert _url("run", "a b#c.png") == "/run/a%20b%23c.png"
+ assert _url("frames", "down_walk", "frame-0.png") == "/frames/down_walk/frame-0.png"
+
+
+def _run_import(pngs: Path, out: Path, *extra: str) -> subprocess.CompletedProcess[str]:
+ return subprocess.run(
+ [sys.executable, str(ROOT / "scripts" / "unpack_atlas_run.py"),
+ "--pngs-dir", str(pngs), "--out-dir", str(out), *extra],
+ capture_output=True, text=True,
+ )
+
+
+def test_force_reimport_is_a_clean_rebuild(tmp_path):
+ """--force re-import must not leave stale source truth (Idempotency/SSoT)."""
+ pngs = tmp_path / "pngs"
+ _png(pngs / "_base" / "b.png", size=(96, 96))
+ _png(pngs / "items" / "1-a.png")
+ _png(pngs / "items" / "_refs" / "anchor-x.png")
+ out = tmp_path / "run"
+ r1 = _run_import(pngs, out, "--force")
+ assert r1.returncode == 0, r1.stderr
+ assert (out / "base-source.png").is_file()
+ assert (out / "references" / "imported" / "items" / "anchor-x.png").is_file()
+ # remove both sources from the input, re-import into the SAME out-dir
+ shutil.rmtree(pngs / "_base")
+ shutil.rmtree(pngs / "items" / "_refs")
+ r2 = _run_import(pngs, out, "--force")
+ assert r2.returncode == 0, r2.stderr
+ assert not (out / "base-source.png").exists() # stale base gone
+ assert not (out / "references" / "imported").exists() # stale refs gone
+ prov = json.loads((out / "unpack-source.json").read_text())
+ assert prov["base_source"] is None and prov["imported_refs"] == {}
+ st = build_run_state(out)
+ assert st["baseUrl"] is None and st["contract"]["sourceless"] is True
+
+
+def test_unknown_ref_role_fails_loud(tmp_path):
+ """A _refs file with an unknown role prefix is rejected, not relabeled to guide."""
+ pngs = tmp_path / "pngs"
+ _png(pngs / "items" / "1-a.png")
+ _png(pngs / "items" / "_refs" / "mystery-source.png")
+ out = tmp_path / "run"
+ r = _run_import(pngs, out, "--force")
+ assert r.returncode != 0
+ combined = r.stderr + r.stdout
+ assert "mystery-source.png" in combined
+ assert "anchor-/basis-/guide-" in combined
+ assert not out.exists() or not (out / "references" / "imported").exists()
+
+
+def _snapshot(run: Path) -> dict:
+ return {p.relative_to(run): p.read_bytes()
+ for p in run.rglob("*") if p.is_file() and p.name != ".sprite-gen.lock"}
+
+
+def test_force_reimport_failure_preserves_prior_run(tmp_path):
+ """A failed --force re-import must leave the prior valid run byte-intact (Atomicity:
+ a rebuild fully succeeds or rolls back — never clear-then-fail)."""
+ pngs = tmp_path / "pngs"
+ _png(pngs / "_base" / "b.png", size=(96, 96))
+ _png(pngs / "items" / "1-a.png")
+ _png(pngs / "items" / "_refs" / "anchor-x.png")
+ out = tmp_path / "run"
+ assert _run_import(pngs, out, "--force").returncode == 0
+ before = _snapshot(out)
+ assert (out / "base-source.png").is_file() and before # a real prior run exists
+ # make the next import invalid (unknown role) and re-run --force → must fail...
+ _png(pngs / "items" / "_refs" / "mystery-source.png")
+ r = _run_import(pngs, out, "--force")
+ assert r.returncode != 0
+ # ...and the prior run must be untouched (not destroyed / emptied), no staging leak
+ assert _snapshot(out) == before
+ assert not (out.parent / f".{out.name}.sg-staging").exists()
+
+
+def test_publish_phase_failure_rolls_back(tmp_path, monkeypatch):
+ """If a publish move fails mid-swap, the prior run is rolled back byte-intact, no
+ partial new run is exposed, and staging/backup are cleaned."""
+ import pathlib
+
+ from sprite_gen.frames import unpack_atlas as ua
+
+ pngs = tmp_path / "pngs"
+ _png(pngs / "items" / "1-a.png")
+ out = tmp_path / "run"
+ assert _run_import(pngs, out, "--force").returncode == 0
+ before = _snapshot(out)
+ _png(pngs / "items" / "2-b.png") # a real change the re-import would publish
+
+ orig_rename = pathlib.Path.rename
+
+ def flaky(self, target):
+ if ".sg-staging" in str(self): # moving new content out of staging into out_dir
+ raise OSError("injected publish failure")
+ return orig_rename(self, target)
+
+ monkeypatch.setattr(pathlib.Path, "rename", flaky)
+ with pytest.raises((OSError, SystemExit)):
+ ua.run(pngs_dir=pngs, out_dir=out, force=True)
+ assert _snapshot(out) == before # prior run byte-intact
+ assert not (out.parent / f".{out.name}.sg-staging").exists() # staging cleaned
+ assert not (out / ".sg-backup").exists() # in-place backup cleaned
+
+
+def test_publish_never_removes_out_dir(tmp_path, monkeypatch):
+ """out_dir (and the lock inside it) must never disappear during publish, so a
+ concurrent writer cannot mkdir+lock the run path mid-swap (Isolation)."""
+ import pathlib
+
+ from sprite_gen.frames import unpack_atlas as ua
+
+ pngs = tmp_path / "pngs"
+ _png(pngs / "items" / "1-a.png")
+ out = tmp_path / "run"
+ assert _run_import(pngs, out, "--force").returncode == 0
+ from sprite_gen.spec.runio import LOCK_FILENAME
+ _png(pngs / "items" / "2-b.png")
+
+ orig_rename = pathlib.Path.rename
+ vanished = {"path": False, "lock": False}
+
+ def watch(self, target):
+ # check both before and after every rename that happens during the publish
+ for _ in range(1):
+ if not out.exists():
+ vanished["path"] = True
+ elif not (out / LOCK_FILENAME).exists():
+ vanished["lock"] = True
+ r = orig_rename(self, target)
+ if not out.exists():
+ vanished["path"] = True
+ elif not (out / LOCK_FILENAME).exists():
+ vanished["lock"] = True
+ return r
+
+ monkeypatch.setattr(pathlib.Path, "rename", watch)
+ assert ua.run(pngs_dir=pngs, out_dir=out, force=True) == 0
+ assert not vanished["path"], "out_dir vanished during publish (isolation window)"
+ assert not vanished["lock"], "run-dir lock vanished during publish (isolation window)"
+ # the new run published cleanly
+ assert (out / "frames" / "items" / "frame-1.png").is_file()
+
+
+def test_api_run_reader_isolated_from_concurrent_publish(tmp_path):
+ """build_run_state reads under read_guard, so it blocks while a publish holds the
+ exclusive publish_guard and returns a COMPLETE snapshot — never a mid-publish 500 or
+ old/new mix (reader isolation)."""
+ import threading
+ import time
+
+ from sprite_gen.serve.serve_curation import build_run_state
+ from sprite_gen.spec import runio
+
+ pngs = tmp_path / "pngs"
+ _png(pngs / "items" / "1-a.png")
+ run = tmp_path / "run"
+ assert _run_import(pngs, run, "--force").returncode == 0
+
+ outcome: dict = {}
+ ready = threading.Event()
+
+ def reader():
+ ready.wait()
+ try:
+ st = build_run_state(run) # read_guard SH -> blocks under the publish EX lock
+ outcome["states"] = len(st["states"])
+ except Exception as exc: # a mid-publish read would raise / 500
+ outcome["err"] = repr(exc)
+ outcome["at"] = time.monotonic()
+
+ th = threading.Thread(target=reader)
+ th.start()
+ with runio.publish_guard(run): # simulate a publish holding the exclusive lock
+ ready.set()
+ time.sleep(0.25) # reader must be blocked for this whole window
+ assert "at" not in outcome, "reader was not blocked by publish_guard (no isolation)"
+ released_at = time.monotonic()
+ th.join(3)
+ assert "err" not in outcome, outcome.get("err")
+ assert outcome.get("states"), "reader got no complete snapshot"
+ assert outcome["at"] >= released_at, "reader returned before the publish released"
+
+
+def test_serve_fails_loud_on_orphan_frames(fixture_run_dir):
+ """serve serves a scaffold only for a genuinely ungenerated run. Physical frames with NO
+ manifest are an orphan/stale generation, not a fresh scaffold — build_run_state must fail loud
+ (HTTP 500 in do_GET), never expose stale frames as present (No Silent Fallback / Consistency)."""
+ from conftest import run_script
+
+ run = fixture_run_dir
+ assert run_script("extract_sprite_row_frames.py", "--run-dir", str(run)).returncode == 0
+ (run / "frames" / "frames-manifest.json").unlink() # orphan: frames, no manifest
+ with pytest.raises(SystemExit):
+ build_run_state(run)
+
+
+def test_import_fails_loud_on_multiple_base_images(tmp_path):
+ """`_base/` is the run's single identity image; multiple images must fail loud, not silently
+ pick the first (identity SSoT / No Silent Fallback)."""
+ from conftest import run_script # noqa: F401 (ensures scripts path is set up like siblings)
+
+ pngs = tmp_path / "pngs"
+ _png(pngs / "_base" / "a.png")
+ _png(pngs / "_base" / "b.png")
+ _png(pngs / "items" / "1-x.png")
+
+ r = _run_import(pngs, tmp_path / "run", "--force")
+ assert r.returncode != 0, "import silently picked one of several _base images"
+ assert "_base" in (r.stdout + r.stderr).lower()
+
+
+def test_serve_run_state_scaffolds_absent_but_fails_loud_on_broken_manifest(fixture_run_dir):
+ """serve build_run_state serves the request/state scaffold when the manifest is ABSENT (a run
+ with no generation yet — legitimate), but a present-but-broken `{}` manifest fails loud
+ (surfaces as HTTP 500 in do_GET), never a silent empty-rows view (No Silent Fallback)."""
+ from conftest import run_script
+
+ run = fixture_run_dir
+ st = build_run_state(run) # absent manifest -> scaffold from request states
+ assert st["states"], "scaffold should list the run's states even before extraction"
+
+ assert run_script("extract_sprite_row_frames.py", "--run-dir", str(run)).returncode == 0
+ (run / "frames" / "frames-manifest.json").write_text("{}", encoding="utf-8")
+ with pytest.raises(SystemExit): # present-but-broken -> fail loud (do_GET -> 500)
+ build_run_state(run)
+
+
[email protected]("modname,kwargs", [
+ ("sprite_gen.qa.preview", {}),
+ ("sprite_gen.compose.compose_gif", {}),
+ ("sprite_gen.compose.compose_cycle", {"state": "walk", "name": "cyc"}),
+])
+def test_finished_consumer_reader_isolated_from_concurrent_publish(fixture_run_dir, modname, kwargs):
+ """preview / run-dir compose_gif / compose_cycle read the manifest + curation + frame tree under
+ one shared read_guard, so they block during a concurrent publish swap and never observe a
+ mid-swap (missing/partial) generation — same reader-isolation contract as serve/inspect."""
+ import importlib
+ import threading
+ import time
+
+ from conftest import run_script
+ from sprite_gen.spec import runio
+
+ run = fixture_run_dir
+ assert run_script("extract_sprite_row_frames.py", "--run-dir", str(run)).returncode == 0
+ mod = importlib.import_module(modname)
+
+ outcome: dict = {}
+ ready = threading.Event()
+
+ def reader():
+ ready.wait()
+ try:
+ mod.run(run_dir=run, **kwargs) # read_guard SH -> blocks under the publish EX lock
+ outcome["ok"] = True
+ except Exception as exc: # a mid-swap read would raise
+ outcome["err"] = repr(exc)
+ outcome["at"] = time.monotonic()
+
+ th = threading.Thread(target=reader)
+ th.start()
+ with runio.publish_guard(run): # model an extract commit holding the exclusive lock
+ ready.set()
+ time.sleep(0.25)
+ assert "at" not in outcome, f"{modname} did not block on read_guard during a publish"
+ released_at = time.monotonic()
+ th.join(20)
+ assert "err" not in outcome, outcome.get("err")
+ assert outcome.get("ok"), f"{modname} did not complete after the publish released"
+ assert outcome["at"] >= released_at, f"{modname} returned before the publish released"
+
+
+def test_inspect_reader_isolated_from_concurrent_commit(fixture_run_dir):
+ """inspect_run reads frames-manifest.json + extract-failure.json together under read_guard,
+ so it blocks while an extract commit holds the exclusive publish_guard and never observes a
+ newly-swapped frames generation beside a stale failure record (the correction loop reads
+ through inspect_run, so its diagnostics stay isolated from a concurrent commit)."""
+ import threading
+ import time
+
+ from conftest import run_script
+ from sprite_gen.spec import runio
+ from sprite_gen.qa.inspect import inspect_run
+
+ run = fixture_run_dir
+ assert run_script("extract_sprite_row_frames.py", "--run-dir", str(run)).returncode == 0
+
+ outcome: dict = {}
+ ready = threading.Event()
+
+ def reader():
+ ready.wait()
+ try:
+ rep = inspect_run(run, states="all") # read_guard SH -> blocks under the publish EX lock
+ outcome["states"] = len(rep["rows"])
+ except Exception as exc: # a mid-commit read would raise / see a torn snapshot
+ outcome["err"] = repr(exc)
+ outcome["at"] = time.monotonic()
+
+ th = threading.Thread(target=reader)
+ th.start()
+ with runio.publish_guard(run): # simulate an extract commit holding the exclusive lock
+ ready.set()
+ time.sleep(0.25)
+ assert "at" not in outcome, "inspect reader was not blocked by publish_guard (no isolation)"
+ released_at = time.monotonic()
+ th.join(5)
+ assert "err" not in outcome, outcome.get("err")
+ assert outcome.get("states"), "inspect reader got no snapshot"
+ assert outcome["at"] >= released_at, "inspect returned before the commit released"
+
+
+def test_publish_guards_fail_loud_without_a_lock_backend(tmp_path, monkeypatch):
+ """Where advisory locks can't be established, read_guard/publish_guard must
+ RAISE, not degrade to a no-op. A no-op guard is a failover that changes canonical truth
+ (a reader could see a half-published run), which the isolation contract forbids — so the
+ guarded code refuses to run rather than serve/publish a partial run."""
+ from sprite_gen.spec import runio
+
+ run = tmp_path / "run"
+ run.mkdir()
+ monkeypatch.setattr(runio, "_LOCK_IMPL", None)
+
+ for guard in (runio.read_guard, runio.publish_guard):
+ with pytest.raises(runio.RWLockUnavailable):
+ with guard(run):
+ pass # pragma: no cover - the guard must raise before yielding
+
+
+def test_stale_curation_post_rejected_across_run_generations(tmp_path):
+ """A curation autosave must echo the runRevision it was loaded with. A `--force`
+ re-import — even one keeping the SAME state name but swapping the candidate images —
+ changes the run generation, so an old-session POST is rejected (409) and never applied;
+ a POST echoing the current revision saves (200) (Consistency: run identity, not just
+ state membership; observable, not a silent overwrite)."""
+ import json as _json
+ import threading
+ import urllib.error
+ import urllib.request
+ from functools import partial
+ from http.server import ThreadingHTTPServer
+
+ from sprite_gen.serve.serve_curation import CurationHandler
+
+ pngs = tmp_path / "pngs"
+ _png(pngs / "items" / "1-a.png", color=(200, 0, 0, 255))
+ _png(pngs / "items" / "2-b.png", color=(0, 200, 0, 255))
+ out = tmp_path / "run"
+ assert _run_import(pngs, out, "--force").returncode == 0
+
+ CurationHandler.run_dir = out
+ CurationHandler.lang = "en"
+ srv = ThreadingHTTPServer(("127.0.0.1", 0), partial(CurationHandler))
+ threading.Thread(target=srv.serve_forever, daemon=True).start()
+ port = srv.server_address[1]
+
+ def get_revision():
+ return _json.loads(urllib.request.urlopen(f"http://127.0.0.1:{port}/api/run").read())["runRevision"]
+
+ def post(revision):
+ body = _json.dumps({"version": 1, "kind": "sprite-gen-curation", "runRevision": revision,
+ "states": {"items": {"selected": [1], "transforms": {"1": {"dx": 9}}}}}).encode()
+ req = urllib.request.Request(f"http://127.0.0.1:{port}/api/curation", data=body, method="POST")
+ try:
+ return urllib.request.urlopen(req).status
+ except urllib.error.HTTPError as exc:
+ return exc.code
+
+ try:
+ old_rev = get_revision() # the webview loads generation 1
+ # re-import the SAME state name with DIFFERENT images (new candidates)
+ shutil.rmtree(pngs)
+ _png(pngs / "items" / "1-a.png", color=(0, 0, 200, 255))
+ _png(pngs / "items" / "2-b.png", color=(200, 200, 0, 255))
+ assert _run_import(pngs, out, "--force").returncode == 0
+ new_rev = get_revision()
+ assert new_rev != old_rev, "run generation did not change on same-state re-import"
+ # the old session autosaves against the stale generation -> rejected, not applied
+ assert post(old_rev) == 409
+ assert not (out / "curation.json").exists(), "stale curation applied to the new run"
+ # a POST echoing the current generation saves
+ assert post(new_rev) == 200
+ assert (out / "curation.json").is_file()
+ finally:
+ srv.shutdown()
+
+
+def test_stored_curation_ignored_after_frame_regeneration(tmp_path):
+ """A saved curation.json is ignored once the frames are regenerated under it (re-extract
+ or re-import): load_curation returns None, so the server, compose, and export all fall
+ back to the all-frames default — stale selections/transforms never apply to new frames.
+ This is the single load_curation gate every consumer passes through."""
+ import time
+
+ from sprite_gen.serve.serve_curation import build_run_state, write_curation_atomic
+ from sprite_gen.curate import curation as cur
+
+ pngs = tmp_path / "pngs"
+ _png(pngs / "items" / "1-a.png")
+ _png(pngs / "items" / "2-b.png")
+ out = tmp_path / "run"
+ assert _run_import(pngs, out, "--force").returncode == 0
+
+ # save a curation stamped for the current generation (a selection + a transform)
+ write_curation_atomic(out, {"version": 1, "kind": "sprite-gen-curation",
+ "states": {"items": {"selected": [1], "transforms": {"1": {"dx": 9}}}}})
+ assert cur.load_curation(out) is not None # applies now (same generation)
+ rev_before = cur.run_revision(out)
+
+ time.sleep(0.01)
+ _png(out / "frames" / "items" / "frame-0.png", color=(1, 2, 3, 255)) # a re-extract-style frame rewrite
+ assert cur.run_revision(out) != rev_before # the run generation changed
+
+ assert cur.load_curation(out) is None # stale sidecar ignored at the single gate
+ st = build_run_state(out)
+ assert st["curation"]["states"] == {} # server serves no stale curation
+
+
+def test_unstamped_curation_ignored(tmp_path):
+ """A curation.json with no run_revision (legacy / hand-written / copied from a doc example)
+ is unverifiable against the current frames, so load_curation ignores it (all-frames default)
+ rather than silently applying stale selections/transforms — the single gate has no bypass."""
+ import json as _json
+
+ from sprite_gen.serve.serve_curation import build_run_state
+ from sprite_gen.curate import curation as cur
+
+ pngs = tmp_path / "pngs"
+ _png(pngs / "items" / "1-a.png")
+ _png(pngs / "items" / "2-b.png")
+ out = tmp_path / "run"
+ assert _run_import(pngs, out, "--force").returncode == 0
+
+ # an UNSTAMPED sidecar written directly, as a legacy/manual file would be
+ (out / "curation.json").write_text(_json.dumps({
+ "version": 1, "kind": "sprite-gen-curation",
+ "states": {"items": {"selected": [1], "transforms": {"1": {"dx": 9}}}}}))
+ assert cur.load_curation(out) is None # unstamped -> ignored, not applied
+ assert build_run_state(out)["curation"]["states"] == {}
+ # a valid save (via the stamping writer) then applies for the matching generation
+ from sprite_gen.serve.serve_curation import write_curation_atomic
+ write_curation_atomic(out, {"version": 1, "kind": "sprite-gen-curation",
+ "states": {"items": {"selected": [0]}}})
+ assert cur.load_curation(out) is not None
+
+
+def test_extract_frame_publish_holds_publish_guard(tmp_path):
+ """extract advances frames/ + extract-failure.json as one generation via _commit_generation,
+ which holds publish_guard for the whole transaction — so it serializes with a curation reader
+ (read_guard) and the reader never observes a half-swapped frames dir or a new generation
+ beside a stale failure record."""
+ import threading
+
+ from sprite_gen.spec import runio
+ from sprite_gen.frames.extract import _commit_generation
+
+ run = tmp_path / "run"
+ (run / "frames" / "items").mkdir(parents=True)
+ (run / "frames" / "items" / "frame-0.png").write_bytes(b"OLD")
+ staging = run / ".frames.sg-staging"
+ (staging / "items").mkdir(parents=True)
+ (staging / "items" / "frame-0.png").write_bytes(b"NEW")
+ result = {"ok": True, "errors": [], "warnings": [], "rows": []}
+
+ reader_holding = threading.Event()
+ release_reader = threading.Event()
+
+ def reader():
+ with runio.read_guard(run):
+ reader_holding.set()
+ release_reader.wait(3)
+
+ threading.Thread(target=reader).start()
+ reader_holding.wait(3)
+
+ published = threading.Event()
+
+ def publisher():
+ _commit_generation(run, staging, result, {"items"}, {"items"})
+ published.set()
+
+ threading.Thread(target=publisher).start()
+ assert not published.wait(0.3), "extract commit did not block on the reader (no isolation)"
+ release_reader.set()
+ published.wait(3)
+ assert published.is_set()
+ assert (run / "frames" / "items" / "frame-0.png").read_bytes() == b"NEW"
+ assert (run / "frames" / "items" / "frame-0.png").read_bytes() == b"NEW" # single new generation
+ assert not staging.exists()
+
+
[email protected]("field,where", [
+ ("run-wide", "top"),
+ ("per-state", "state"),
+])
+def test_autosave_preserves_pixel_perfect_the_view_does_not_author(tmp_path, field, where):
+ """뷰가 **authoring 하지 않는** `pixel_perfect` 선언은 autosave 가 지우면 안 된다.
+
+ `buildPayload` 는 이 필드를 조건부로만 싣는다: per-state 는 트윈이 있는 줄만, 런 전역은
+ 트윈 줄이 전부 같을 때만. 생략은 "안 건드림" 이지 삭제가 아니다 — 삭제로 받으면
+ **굽기가 읽는 변종이 바뀐다**(`frame_variant`). `.plain.png` 가 없는 줄이 `plain` 으로
+ 뒤집히면 `row_frame_rel(row, i, "plain")` 이 없는 파일을 가리켜 굽기가 죽는데, 사용자는
+ 큐레이터를 한 번 열었을 뿐이고 화면에는 아무 알림도 없다 (validator 실측 2026-07-26).
+
+ `anchors`·`frozen` 과 같은 이월 계약이다. 이 그물이 없는 동안 이월 두 줄을 지워도
+ 전체 스위트가 513 passed 로 통과했다 — round-9 R2 가 `bakeFrameUrl` 에 대해 기각한
+ 것과 같은 상태였다."""
+ from sprite_gen.curate.curation import frame_variant, stamp_curation
+
+ pngs = tmp_path / "pngs"
+ _png(pngs / "items" / "1-a.png", color=(200, 0, 0, 255))
+ _png(pngs / "items" / "2-b.png", color=(0, 200, 0, 255))
+ out = tmp_path / "run"
+ assert _run_import(pngs, out).returncode == 0
+
+ curation = {"version": 1, "kind": "sprite-gen-curation", "states": {"items": {}}}
+ if where == "top":
+ curation["pixel_unfake"] = False
+ else:
+ curation["states"]["items"]["pixel_unfake"] = True
+ curation["pixel_unfake"] = False # per-state 가 이기는지도 같이 본다
+ (out / "curation.json").write_text(json.dumps(stamp_curation(out, curation)), encoding="utf-8")
+ before = frame_variant(json.loads((out / "curation.json").read_text(encoding="utf-8")), "items")
+
+ CurationHandler.run_dir = out
+ CurationHandler.lang = "en"
+ srv = ThreadingHTTPServer(("127.0.0.1", 0), partial(CurationHandler))
+ threading.Thread(target=srv.serve_forever, daemon=True).start()
+ port = srv.server_address[1]
+ try:
+ revision = json.loads(
+ urllib.request.urlopen(f"http://127.0.0.1:{port}/api/run").read())["runRevision"]
+ # 뷰가 authoring 하지 않은 저장 — `pixel_perfect` 키가 어디에도 없다
+ body = json.dumps({"version": 1, "kind": "sprite-gen-curation", "runRevision": revision,
+ "states": {"items": {"selected": [0, 1]}}}).encode()
+ req = urllib.request.Request(f"http://127.0.0.1:{port}/api/curation",
+ data=body, method="POST")
+ assert urllib.request.urlopen(req).status == 200
+ finally:
+ srv.shutdown()
+
+ saved = json.loads((out / "curation.json").read_text(encoding="utf-8"))
+ after = frame_variant(saved, "items")
+ assert after == before, (
+ f"{field} 선언이 autosave 에 사라져 굽기 변종이 {before} -> {after} 로 바뀌었다\n"
+ f" 저장된 사이드카: {saved}")
diff --git a/tests/serve/test_curator_pixel_scaling_ssot.py b/tests/serve/test_curator_pixel_scaling_ssot.py
new file mode 100644
index 0000000..0f1ce0d
--- /dev/null
+++ b/tests/serve/test_curator_pixel_scaling_ssot.py
@@ -0,0 +1,261 @@
+# SPDX-License-Identifier: Apache-2.0
+"""표시 샘플링 판정(nearest 여부)의 SSoT 회귀.
+
+maintainer 2026-07-24 "절대 원본 아님": 고해상 orig 트윈이 축소 표시되는 카드에서
+nearest 데시메이션을 겪어(896px → 152px, 전체의 2.1%만 표본) 화면이 양자화된
+형태로 보였다. 원인은 `.stage img { image-rendering: pixelated }` 무조건 규칙이
+`clientWidth > naturalWidth` 조건 판정을 덮어써 죽은 코드로 만든 것 —
+같은 질문에 여섯 군데가 다르게 답하고 있었다 (원칙 1·2).
+
+계약: nearest 부여는 `display.js applyPixelScaling` 한 곳만 하고, CSS 는
+`.px-upscale` 클래스에만 반응한다. 내부 렌더 서피스(snap-canvas·cmp-canvas)는
+표시 해상도로 직접 그려지므로 예외이며 각자 규칙을 유지한다.
+"""
+from __future__ import annotations
+
+import re
+
+from sprite_gen.serve.serve_curation import CURATOR_DIR
+
+CURATOR = CURATOR_DIR
+CSS = (CURATOR / "curator.css").read_text(encoding="utf-8")
+SRC = {p.name: p.read_text(encoding="utf-8") for p in (CURATOR / "src").glob("*.js")}
+
+# 판정 면제는 **버퍼 해상도 = 표시 해상도** 인 서피스뿐이다 (JS 가 표시 크기에 맞춰
+# 직접 래스터를 그리는 경우). `snap-canvas` 는 한때 여기 있었지만 소스 표시 모드가
+# 소스 해상도로 그리게 되면서 전제가 깨졌고, 면제가 남아 있는 동안 이 계약이 그
+# 표시면을 통째로 놓쳤다 (validator R1, 2026-07-24). 화이트리스트를 넓히기 전에
+# "이 서피스는 버퍼와 표시가 정말 같은가" 를 먼저 실측하라.
+INTERNAL_SURFACES = ("cmp-canvas",)
+
+
+def _rule_selectors_with_pixelated() -> list[str]:
+ """`image-rendering: pixelated` 을 켜는 CSS 규칙의 셀렉터 목록."""
+ out = []
+ for block in re.finditer(r"([^{}]+)\{([^{}]*)\}", CSS):
+ selector, body = block.group(1), block.group(2)
+ if "image-rendering" in body and "pixelated" in body:
+ out.append(" ".join(selector.split()))
+ return out
+
+
+def test_pixelated_is_granted_only_through_the_upscale_class():
+ """CSS 에서 nearest 를 켜는 규칙은 `.px-upscale` 과 내부 서피스뿐이다."""
+ offenders = [
+ sel for sel in _rule_selectors_with_pixelated()
+ if "px-upscale" not in sel and not any(s in sel for s in INTERNAL_SURFACES)
+ ]
+ assert not offenders, (
+ "무조건 nearest 규칙이 표시면에 남아 있다 — 축소 표시에서 데시메이션이 되고 "
+ f"조건 판정을 덮어쓴다: {offenders}"
+ )
+
+
+def test_no_blanket_stage_image_rule():
+ """회귀 고정: `.stage img` 자체에 nearest 를 거는 규칙이 되살아나면 안 된다."""
+ for sel in _rule_selectors_with_pixelated():
+ assert not re.search(r"(^|,)\s*\.stage img\s*(,|$)", sel), (
+ f"`.stage img` 무조건 nearest 규칙 부활: {sel}"
+ )
+
+
+def test_single_writer_of_the_upscale_class():
+ """`px-upscale` 을 부여/해제하는 코드는 display.js 한 곳뿐이다."""
+ writers = {
+ name: [ln.strip() for ln in text.splitlines() if "px-upscale" in ln]
+ for name, text in SRC.items()
+ if "px-upscale" in text
+ }
+ assert set(writers) == {"display.js"}, (
+ f"판정이 여러 파일로 흩어졌다 (SSoT 위반): { {k: v for k, v in writers.items()} }"
+ )
+
+
+def test_decision_reads_display_geometry_not_a_heuristic():
+ """판정 입력은 표시 기하(표시폭 vs 원본폭)여야 한다 — 셀 크기 추측 금지."""
+ display = SRC["display.js"]
+ assert "classList.toggle(\"px-upscale\", shown > natural)" in display, (
+ "applyPixelScaling 이 표시폭>원본폭 판정을 잃었다"
+ )
+ # 셀 폭 휴리스틱(`run.cell.width < 160`)으로 되돌아가지 않았는지 확인
+ for name, text in SRC.items():
+ assert "cell.width < 160" not in text, f"{name}: 셀 폭 휴리스틱 부활"
+
+
+def test_decision_is_re_evaluated_on_geometry_change():
+ """기하가 바뀌면 재평가된다 — 1회성 부여로 되돌아가면 축소/확대 전환을 놓친다."""
+ assert "syncPixelScaling()" in SRC["display.js"], "sizePxGrids 가 재평가를 부르지 않는다"
+ assert re.search(r"sizePxGrids\(\)\s*\{[^}]*syncPixelScaling\(\)", SRC["display.js"], re.S), (
+ "sizePxGrids(기하 갱신 지점)가 syncPixelScaling 을 부르지 않는다"
+ )
+ assert 'addEventListener("resize"' in SRC["boot.js"], "창 크기 변경 재평가 훅이 없다"
+
+
+def test_decision_is_re_evaluated_when_the_image_source_changes():
+ """픽셀퍼펙트 토글은 **레이아웃이 아니라 원본 기하**를 바꾼다 — 로드에도 물려야 한다.
+
+ 회귀 (maintainer 2026-07-24 "달리기 시퀀스... 절대 원본 아님"): 토글을 끄면 src 가
+ 64px 출력 → 704px 원본 트윈으로 갈리는데, 레이아웃 이벤트만 보던 재평가는
+ 그 순간을 못 잡아 확대용 nearest 가 축소된 원본 위에 stale 로 남았다.
+ """
+ display = SRC["display.js"]
+ assert "installPixelScalingLoadHook" in display, "이미지 로드 재평가 훅이 없다"
+ # load 는 버블링하지 않는다 — capture 로 받아야 위임이 성립한다
+ assert re.search(
+ r'addEventListener\(\s*"load".*?\}\s*,\s*true\s*\)', display, re.S
+ ), "load 위임 훅이 capture 모드가 아니다 (load 는 버블링하지 않는다)"
+ assert "installPixelScalingLoadHook()" in SRC["boot.js"], "부팅에서 로드 훅을 설치하지 않는다"
+ # 같은 src 재대입(캐시)은 load 가 안 뜨므로 변형 스왑 경로가 직접 한 번 더 답한다
+ assert re.search(
+ r"refreshVariantImages\(\)\s*\{.*?applyPixelScaling\(el\)", display, re.S
+ ), "src 스왑 경로가 판정을 다시 받지 않는다"
+
+
+def test_every_display_surface_is_under_the_decision():
+ """표시면 목록에 캔버스 표시면이 빠지면 계약이 그 경로를 통째로 놓친다.
+
+ 회귀 (validator R1, 2026-07-24): 소스 표시 캔버스의 **버퍼**를 소스 해상도로
+ 올려놓고 `PIXEL_SCALE_TARGETS` 에서는 제외해 둬서, 896 버퍼가 152 표시로
+ nearest 데시메이션(2.9% 생존)됐다. 버퍼 해상도를 올린 것과 표시 샘플링을
+ 지킨 것은 다른 일이다 — 목표한 양(표시 샘플링)을 재야 한다.
+ """
+ display = SRC["display.js"]
+ assert '".stage canvas.snap-canvas"' in display, (
+ "실제 표시면인 snap-canvas 가 판정 대상에서 빠졌다"
+ )
+
+
+# ── 캔버스 버퍼 사이징 지점의 분류표 (계약) ──
+# 같은 병이 호출부를 옮겨다니며 세 번 재발했다 (R2 renderState → R3 renderTick).
+# 호출부 이름으로 테스트를 쓰면 네 번째 이사 자리가 남으므로, **버퍼 크기를 정하는
+# 모든 지점**을 열거하고 각각을 분류하게 강제한다. 미분류 지점은 실패한다 —
+# 새 캔버스를 만드는 사람이 "이건 사용자가 보는 표시면인가" 를 반드시 답하게.
+#
+# display = DOM 에 붙어 사용자가 본다. 버퍼≠표시일 수 있으므로 판정 필수.
+# offscreen= 합성용 작업 캔버스. 화면에 안 붙으므로 판정 무의미.
+# rect = 표시 영역 실측으로 버퍼를 잡는다(버퍼=표시). nearest 가 무연산.
+# not-canvas = 캔버스가 아닌 객체의 width 속성.
+CANVAS_BUFFER_SITES = {
+ ("cards.js", "base"): "offscreen",
+ ("row-export.js", "base"): "offscreen",
+ ("row-export.js", "out"): "offscreen",
+ ("display.js", "src"): "offscreen",
+ ("display.js", "tmp"): "offscreen",
+ ("display.js", "canvas"): "rect", # 격자 오버레이 — stage 실측 크기
+ ("base-editor.js", "probe"): "offscreen",
+ ("base-editor.js", "logical"): "offscreen",
+ ("transforms.js", "canvas"): "display", # snap-canvas (소스/양자화 모드)
+ ("zoom-editor.js", "zoomView"): "not-canvas",
+ ("zoom-editor.js", "c"): "offscreen",
+ ("zoom-editor.js", "work"): "offscreen",
+ ("zoom-editor.js", "base"): "offscreen",
+ ("zoom-editor.js", "cvs"): "offscreen",
+ ("zoom-editor.js", "b"): "offscreen",
+ ("zoom-editor.js", "prev"): "display", # 마키 라이브 프리뷰
+ ("zoom-editor.js", "bcanvas"): "display", # 호흡 모드 줌 재생면
+ ("zoom-editor.js", "cv"): "display", # 호흡 필름스트립 셀
+ ("cards.js", "ref"): "offscreen", # 호흡 신선도 판정용 기준 프레임 합성면
+ ("lasso-select.js", "cv"): "display", # 올가미 윤곽/마스크 오버레이
+ ("region-transform.js", "buf"): "offscreen", # 영역 캡처용 합성면 (읽기 전용)
+ ("region-transform.js", "cv"): "display", # 영역 변형 라이브 프리뷰
+ ("compare.js", "base"): "offscreen",
+ ("compare.js", "ref"): "offscreen", # 호흡 신선도 판정용 기준 프레임 합성면
+ ("compare.js", "canvas"): "rect", # cmp-canvas — 버퍼=표시
+ ("breathe.js", "out"): "offscreen",
+ ("breathe.js", "c"): "offscreen",
+}
+
+_JUDGE = re.compile(r"(applyPixelScaling|syncPixelScaling)\s*\(")
+
+
+def _buffer_sites():
+ """`<var>.width = ...` 버퍼 대입 지점 (CSS `.style.width` 제외)."""
+ for name, text in SRC.items():
+ lines = text.splitlines()
+ for i, line in enumerate(lines):
+ m = re.search(r"(?<!\.style)\b(\w+)\.width\s*=", line)
+ if m and ".style.width" not in line:
+ yield name, m.group(1), i, lines
+
+
+def test_every_canvas_buffer_site_is_classified():
+ """새 버퍼 사이징 지점이 생기면 분류를 강제한다 — 조용히 계약 밖에 놓이지 않게."""
+ unknown = sorted({(f, v) for f, v, _, _ in _buffer_sites()} - set(CANVAS_BUFFER_SITES))
+ assert not unknown, (
+ f"분류되지 않은 캔버스 버퍼 사이징 지점: {unknown}. "
+ "사용자가 보는 표시면이면 'display'(판정 필수), 합성용이면 'offscreen', "
+ "표시 실측으로 잡으면 'rect' 로 CANVAS_BUFFER_SITES 에 등록하라."
+ )
+
+
+def test_display_canvases_are_judged_where_their_buffer_is_set():
+ """표시 대상 캔버스의 버퍼를 정하는 지점은 판정을 부른다.
+
+ 회귀 2건, 같은 병이 호출부만 바꿔 재발 (2026-07-24):
+ - R2: `renderState` 가 만든 캔버스가 판정을 못 받아 리사이즈 전까지 뭉갬.
+ - R3: `renderTick`(호흡 모드 줌)이 버퍼만 바꾸고 판정을 안 불러 64→758 보간
+ (화면 고유색 114 → 10,526, 92배 번짐).
+ 둘 다 "리사이즈하면 소급 복구" 라는 같은 서명이었다 — 판정식은 맞고 부르는
+ 지점이 빠진 것. 그래서 계약을 호출부 이름이 아니라 **버퍼를 정하는 자리**로 쓴다.
+ """
+ # 창 40줄 = "같은 렌더 블록" 의 근사치다 (현행 실측 거리 10·23·32줄 — 부착이
+ # 그리기 뒤에 오는 경로가 있어 바로 다음 줄을 강제할 수 없다). 잡으려는 실패는
+ # "판정이 아예 없음" 이고 그건 블록 전체에 없으므로 이 창으로 충분하다.
+ # 진짜 이빨은 위의 분류표다 — 새 표시면은 등록 없이는 통과 못 한다.
+ missing = []
+ for name, var, idx, lines in _buffer_sites():
+ if CANVAS_BUFFER_SITES.get((name, var)) != "display":
+ continue
+ window = "\n".join(lines[idx: idx + 40])
+ if not _JUDGE.search(window):
+ missing.append(f"{name}:{idx + 1} ({var})")
+ assert not missing, (
+ f"표시 대상 캔버스의 버퍼를 바꾸고 판정을 안 부르는 지점: {missing}. "
+ "버퍼 크기는 기하이므로 바꾼 자리에서 applyPixelScaling 을 불러라."
+ )
+
+
+def test_no_inline_unconditional_pixelated_grant():
+ """인라인 `imageRendering` 무조건 부여 금지 — CSS grep 에 안 잡혀 계약 밖에 숨는다.
+
+ 회귀 (validator R4, 2026-07-24): 마키 프리뷰가 camelCase 인라인으로 무조건
+ 부여하고 있었는데, CSS 규칙 본문과 `px-upscale` 문자열만 훑는 테스트가
+ 구조적으로 못 봤다.
+ """
+ offenders = []
+ for name, text in SRC.items():
+ for i, line in enumerate(text.splitlines()):
+ if "imageRendering" in line and "pixelated" in line:
+ offenders.append(f"{name}:{i + 1}")
+ assert not offenders, (
+ f"인라인 무조건 nearest 부여: {offenders}. 판정 소유자(.px-upscale)에게 맡겨라."
+ )
+
+
+def test_source_display_canvas_renders_at_source_resolution():
+ """실제 표시면이 캔버스일 때도 원본 해상도를 지킨다.
+
+ 회귀 (maintainer 2026-07-24, DOM 을 직접 열어 지목): 픽셀 편집이 있는 프레임은
+ `<img>` 가 `visibility: hidden` 이 되고 `snap-canvas` 가 실제 표시면이 되는데,
+ 그 캔버스가 **항상 셀 크기(64×64)** 라서 896px 원본 트윈이 64픽셀로 파괴됐다.
+ 표시 계약을 이미지에만 걸면 이 경로가 통째로 빠져나간다.
+
+ 양자화 모드(픽셀퍼펙트 결과 미리보기)는 셀 크기가 목적이므로 ss=1 이며,
+ 두 모드는 배타적이다.
+ """
+ tr = SRC["transforms.js"]
+ display = SRC["display.js"]
+ assert "superSampleFor" in display, "소스 해상도 배율 계산자가 없다"
+ assert re.search(r"const ss = quantize \? 1 : superSampleFor\(", tr), (
+ "소스 표시 모드에서 캔버스가 소스 해상도로 올라가지 않는다"
+ )
+ assert re.search(r"canvas\.width = cw \* ss", tr) and re.search(r"canvas\.height = ch \* ss", tr), (
+ "캔버스가 셀 크기에 고정돼 있다 — 고해상 원본이 파괴된다"
+ )
+ # 좌표 계약: 저장·입력은 셀 공간, ss 는 렌더 해상도만 올린다
+ assert re.search(r"sctx\.fillRect\(x \* ss, y \* ss, ss, ss\)", display), (
+ "픽셀 편집이 슈퍼샘플 공간으로 매핑되지 않는다"
+ )
+ assert re.search(r"const ss = canvas\.width / cw", display), (
+ "스포이드가 슈퍼샘플 배율을 반영하지 않는다 — 다른 픽셀을 집는다"
+ )
diff --git a/tests/serve/test_curator_single_display_pipeline.py b/tests/serve/test_curator_single_display_pipeline.py
new file mode 100644
index 0000000..e021e2b
--- /dev/null
+++ b/tests/serve/test_curator_single_display_pipeline.py
@@ -0,0 +1,143 @@
+# SPDX-License-Identifier: Apache-2.0
+"""표시 파이프라인 단일화 계약 (maintainer 2026-07-24 "구현체가 몇 종류라 노이즈").
+
+한 파이프라인("이 프레임을 큐레이션 상태로 보여라")의 구현이 세 갈래였다:
+엔진 트윈 파일 / 서버 추정 스냅 프리뷰 / 클라 양자화 캔버스 — 그리고 표시면도
+img·canvas 두 갈래. 오늘 표시 결함 5건(v1.56.85~89)이 전부 그 fork 의 한쪽만
+보다 생겼다. 계약: 스테이지 표시는 캔버스 렌더러 하나, 퍼펙 양자화 격자는 표시
+격자와 같은 측정값, 레거시(서버 프리뷰)와 게이팅 knob 은 코드에서 사라진다.
+
+주의: 텍스트 어서션은 구현의 글자 모양이 아니라 **메커니즘의 부재**를 고정한다
+(validator R3 교훈 — 존재-정규식은 옆에 새 게이트를 얹으면 통과한다. 부재-어서션은
+그 메커니즘을 되살리는 코드 자체를 금지한다). 클라 런타임 행동 핀은 pytest 밖이라
+실브라우저 감사(plan Verification)로 보완한다.
+"""
+from __future__ import annotations
+
+import re
+from pathlib import Path
+
+from sprite_gen.serve.serve_curation import CURATOR_DIR
+
+ROOT = Path(__file__).resolve().parent.parent.parent
+CURATOR = CURATOR_DIR
+SRC = {p.name: p.read_text(encoding="utf-8") for p in (CURATOR / "src").glob("*.js")}
+SERVE = (ROOT / "sprite_gen" / "serve" / "serve_curation.py").read_text(encoding="utf-8")
+INDEX = (CURATOR / "index.html").read_text(encoding="utf-8")
+
+
+def _no_comment(text: str, lang: str) -> str:
+ """주석 제거본 — 계약은 코드에 걸고, 회고 주석은 허용한다."""
+ if lang == "js":
+ text = re.sub(r"/\*.*?\*/", "", text, flags=re.S)
+ return re.sub(r"(?m)^\s*//.*$|(?<=[;{})\s])//[^\n]*$", "", text)
+ return re.sub(r"(?m)#.*$", "", text)
+
+
+def test_stage_display_is_the_canvas_renderer_only():
+ """applyCardTransform 에 img 표시 분기가 없다 — 표시면은 캔버스 하나다."""
+ tr = SRC["transforms.js"]
+ assert 'el.style.visibility = "hidden"' in tr, "img 가 숨김 로더로 강등되지 않았다"
+ body = _no_comment(tr, "js")
+ assert 'el.style.visibility = ""' not in body, (
+ "img 를 표시면으로 되돌리는 분기 부활 — 표시면이 다시 두 갈래가 된다"
+ )
+ assert 'canvas.style.display = "none"' not in body, (
+ "applyCardTransform 이 캔버스를 끄는 분기 부활 (img 표시 모드의 서명)"
+ )
+
+
+def test_base_pp_off_is_the_raw_source_view():
+ """베이스 pp OFF = 소스 모드로 raw 를 그린다 — 항등 선처리 금지.
+
+ 회귀 (validator 기각 2026-07-24, validator-20260724-154426): `snapScaleFor` 가
+ BASE 분기를 `unfakeOn` 검사보다 먼저 둬서 베이스가 항상 양자화 모드가 됐고, img
+ 표시 분기는 이미 삭제돼 raw 가 표시면에 도달할 경로가 없었다 — 퍼펙 체크박스가
+ 아무것도 안 바꾸는 "거짓말하는 컨트롤"이 됐다.
+ """
+ store = SRC["store.js"]
+ m = re.search(r"function snapScaleFor\(.*?\n\}", store, re.S)
+ assert m, "snapScaleFor 를 찾지 못했다"
+ body = m.group(0)
+ pp_at = body.index("!unfakeOn(stateName)")
+ base_at = body.index("BASE_STATE")
+ assert pp_at < base_at, (
+ "snapScaleFor 에서 BASE 분기가 unfakeOn 검사보다 앞이다 — 베이스 pp OFF 의 "
+ "원본(raw) 뷰가 죽는다"
+ )
+ # 소스 모드의 표시 소스는 el(frameUrl 이 고른 파일)이어야 raw 가 화면에 닿는다
+ tr = SRC["transforms.js"]
+ assert re.search(r"quantize \? editSourceFor\(stateName, el\) : el", tr), (
+ "소스 모드가 편집 소스(논리)로 표시한다 — 베이스 raw 뷰가 다시 사라진다"
+ )
+
+
+def test_quantize_grid_is_the_displayed_grid():
+ """퍼펙 양자화 격자 = 격자 오버레이가 그리는 측정값 — 격자 진실은 하나다."""
+ store = SRC["store.js"]
+ m = re.search(r"function snapScaleFor\(.*?\n\}", store, re.S)
+ assert m, "snapScaleFor 를 찾지 못했다"
+ body = m.group(0)
+ assert "st.pixelScale" in body and re.search(r"\|\|\s*1;", body), (
+ "트윈 없는 줄의 양자화가 측정 k(pixelScale)로 떨어지지 않는다 — "
+ "격자 따로 퍼펙 따로가 재발한다"
+ )
+ assert "run.pixelUnfake.scale" in body, "pp 런의 계약 scale(굽기 거울)이 사라졌다"
+
+
+def test_unfake_toggle_is_ungated_on_every_surface():
+ """퍼펙 토글은 줄 컨트롤·줌 모달 어디에도 게이트가 없다."""
+ assert re.search(r"const showUnfakeToggle\s*=\s*true", SRC["cards.js"]), (
+ "줄별 퍼펙 토글이 조건부로 돌아갔다"
+ )
+ assert not re.search(
+ r"unfakeTwinStates\.has\([^)]*\)\)?\s*controls\.appendChild\(makeUnfakeToggle",
+ SRC["zoom-editor.js"],
+ ), "줌 모달 퍼펙 토글이 트윈 줄로 게이트됐다 (maintainer 재현: 확대화면에 버튼 없음)"
+
+
+def test_legacy_preview_and_gating_knobs_are_gone():
+ """레거시 구현·게이팅 메커니즘의 심볼이 코드에 존재하지 않는다.
+
+ (부재 어서션 — 이 심볼이 없으면 validator R3 의 5줄 mutant 가 뒤집을 knob 자체가 없다)
+ """
+ dead = ["_pixel_preview_meta", "pixelPreviewUrl", "pixelPreviewDeferred",
+ ".pixel-preview", "ppPreviewStates", "ppAvailable", "gridCapableStates"]
+ surfaces = {"serve_curation.py": _no_comment(SERVE, "py"),
+ "index.html": INDEX}
+ for name, text in SRC.items():
+ surfaces[name] = _no_comment(text, "js")
+ for sym in dead:
+ hits = [n for n, text in surfaces.items() if sym in text]
+ assert not hits, f"레거시 심볼 {sym!r} 이 살아 있다: {hits}"
+
+
+def test_server_snapshot_grid_behavior(tmp_path):
+ """실행 행동 핀 (validator R3): 진짜 1:1 임포트 런을 만들어 스냅샷을 어서션한다."""
+ import subprocess
+ import sys
+ import json
+ from PIL import Image
+
+ pngs = tmp_path / "pngs" / "rowa"
+ pngs.mkdir(parents=True)
+ im = Image.new("RGBA", (16, 16))
+ im.putdata([((x * 31) % 256, (y * 17) % 256, 40, 255) for y in range(16) for x in range(16)])
+ im.save(pngs / "1-a.png")
+ im.save(pngs / "2-b.png")
+ out = tmp_path / "run"
+ r = subprocess.run(
+ [sys.executable, str(ROOT / "scripts" / "unpack_atlas_run.py"),
+ "--pngs-dir", str(tmp_path / "pngs"), "--out-dir", str(out), "--force"],
+ capture_output=True, text=True)
+ assert r.returncode == 0, r.stderr
+ import sprite_gen.serve.serve_curation as serve_curation
+ snap = serve_curation.build_run_state(out)
+ assert snap["contract"]["grid"] is True
+ assert snap["pixelUnfake"] and snap["pixelUnfake"]["scale"] >= 1
+ for st in snap["states"]:
+ assert isinstance(st["pixelScale"], int) and st["pixelScale"] >= 1, (
+ f"{st['name']}: pixelScale={st['pixelScale']!r} — 격자 없는 줄이 다시 생겼다"
+ )
+ for fr in st["frames"]:
+ assert "pixelPreviewUrl" not in fr, "레거시 프리뷰 필드가 스냅샷에 되살아났다"
diff --git a/tests/serve/test_pixel_grid_always_available.py b/tests/serve/test_pixel_grid_always_available.py
new file mode 100644
index 0000000..4b060f4
--- /dev/null
+++ b/tests/serve/test_pixel_grid_always_available.py
@@ -0,0 +1,109 @@
+# SPDX-License-Identifier: Apache-2.0
+"""픽셀 격자 컨트롤은 조건부로 숨지 않는다 (계약).
+
+maintainer 2026-07-24 ("10번 넘게 말한 것 같은데"): 격자와 픽셀퍼펙은 스크립트가
+계산하는 것이므로 어떤 이미지에서도 사용 가능해야 한다. 그런데 임포트 런의
+1:1 픽셀아트에서 격자 버튼이 통째로 사라졌다.
+
+단일 근본원인: 피치 측정이 "측정값 1"(항등 — 참)과 "측정 불가"(모름)를 둘 다
+None 으로 뭉갰고, 그 None 이 서버·클라 7겹 게이트를 타고 컨트롤을 숨겼다.
+
+계약: 측정은 **실패할 수 없는 정확 판정**(k×k 블록 단색성, k=1 은 자명히 참)이고,
+따라서 "격자 모름" 상태가 없으며, 그 결과 컨트롤을 숨길 근거도 없다.
+
+회귀는 호출부 이름이 아니라 계약으로 쓴다 — 오늘 `curator-pixel-scaling-ssot`
+에서 호출부 이름 회귀가 같은 병을 세 호출부에 걸쳐 세 번 놓친 교훈.
+"""
+from __future__ import annotations
+
+import re
+from pathlib import Path
+
+from PIL import Image
+
+from sprite_gen.serve.serve_curation import CURATOR_DIR
+
+ROOT = Path(__file__).resolve().parent.parent.parent
+CURATOR = CURATOR_DIR
+SRC = {p.name: p.read_text(encoding="utf-8") for p in (CURATOR / "src").glob("*.js")}
+SERVE = (ROOT / "sprite_gen" / "serve" / "serve_curation.py").read_text(encoding="utf-8")
+
+
+def _pitch(path):
+ from sprite_gen.serve.serve_curation import detect_pixel_pitch # noqa: PLC0415
+ return detect_pixel_pitch(path)
+
+
+def test_measurement_never_fails(tmp_path):
+ """측정은 어떤 입력에도 ≥1 을 돌려준다 — None/0 이 없어야 게이트가 못 생긴다."""
+ cases = {}
+ solid = Image.new("RGBA", (16, 16), (10, 20, 30, 255))
+ solid.save(tmp_path / "solid.png")
+ cases["단색"] = tmp_path / "solid.png"
+ empty = Image.new("RGBA", (16, 16), (0, 0, 0, 0))
+ empty.save(tmp_path / "empty.png")
+ cases["완전투명"] = tmp_path / "empty.png"
+ tiny = Image.new("RGBA", (1, 1), (255, 0, 0, 255))
+ tiny.save(tmp_path / "tiny.png")
+ cases["1x1"] = tmp_path / "tiny.png"
+ noise = Image.new("RGBA", (13, 7))
+ noise.putdata([((x * 37) % 256, (y * 91) % 256, 0, 255)
+ for y in range(7) for x in range(13)])
+ noise.save(tmp_path / "noise.png")
+ cases["소수크기 노이즈"] = tmp_path / "noise.png"
+ for label, p in cases.items():
+ v = _pitch(p)
+ assert isinstance(v, int) and v >= 1, f"{label}: 측정이 {v!r} — 실패 상태가 존재하면 안 된다"
+ assert _pitch(tmp_path / "does-not-exist.png") >= 1, "없는 파일도 항등으로 답해야 한다"
+
+
+def test_measurement_is_exact_not_estimated(tmp_path):
+ """k 배 확대본은 정확히 k, 1:1 은 정확히 1 — 주기성 추정으로 되돌아가면 깨진다."""
+ base = Image.new("RGBA", (8, 8))
+ base.putdata([((x * 31) % 256, (y * 17) % 256, (x ^ y) * 8 % 256, 255)
+ for y in range(8) for x in range(8)])
+ base.save(tmp_path / "k1.png")
+ assert _pitch(tmp_path / "k1.png") == 1, "1:1 픽셀아트는 항등 1 이어야 한다"
+ for k in (2, 3, 4, 8):
+ up = base.resize((8 * k, 8 * k), Image.Resampling.NEAREST)
+ up.save(tmp_path / f"k{k}.png")
+ assert _pitch(tmp_path / f"k{k}.png") == k, f"{k}배 확대본의 측정이 {k} 가 아니다"
+
+
+def test_server_never_reports_grid_as_absent():
+ """서버 스냅샷이 격자 부재를 보고하는 경로가 없어야 한다."""
+ assert re.search(r"has_grid\s*=\s*True", SERVE), (
+ "has_grid 가 조건식으로 되돌아갔다 — 조건이 곧 컨트롤 숨김이다"
+ )
+ # pixelUnfake 가 null 로 접히면 클라의 contractScale 이 사라진다
+ assert not re.search(r'"pixelUnfake":[^\n]*else None', SERVE), (
+ "pixelUnfake 를 None 으로 접는 분기 부활 — 격자 scale 이 사라진다"
+ )
+
+
+def test_grid_controls_are_not_gated_in_the_client():
+ """클라에 '격자 가능 줄' 게이팅 메커니즘 자체가 없다.
+
+ validator R3 교훈: 존재-정규식은 옆에 게이트를 새로 얹으면 통과한다(5줄 mutant 실증).
+ 그래서 특정 줄 모양이 아니라 **knob 의 부재**를 고정한다 — gridCapableStates 집합과
+ pxWrap 재숨김이 코드에 없으면 그 mutant 가 뒤집을 스위치 자체가 없다.
+ (클라 런타임 행동 핀은 pytest 밖 — 실브라우저 감사로 보완, plan Verification)
+ """
+ for name, text in SRC.items():
+ assert "gridCapableStates" not in text, f"{name}: 게이팅 집합 knob 부활"
+ boot = SRC["boot.js"]
+ assert re.search(r"pxWrap\.hidden\s*=\s*false", boot), "격자 전체 토글 상시 노출이 사라졌다"
+ assert not re.search(r"pxWrap\.hidden\s*=\s*(?!\s*false\b)", boot), (
+ "pxWrap.hidden 에 false 외 값을 넣는 코드 — 재숨김 경로"
+ )
+ assert re.search(r"const showGridToggle\s*=\s*true", SRC["cards.js"]), (
+ "줄별 격자 토글이 조건부로 숨겨진다"
+ )
+
+
+def test_grid_spacing_never_resolves_to_null():
+ """격자 간격은 항상 정해진다 (줄별 실측 > 계약 > 항등 1)."""
+ display = SRC["display.js"]
+ assert re.search(
+ r"run\.pixelUnfake && run\.pixelUnfake\.scale\)\s*\|\|\s*1\)", display
+ ), "scale 이 null 로 떨어지는 경로 부활 — 오버레이가 조건부로 사라진다"
diff --git a/tests/serve/test_recolor_curation_view.py b/tests/serve/test_recolor_curation_view.py
new file mode 100644
index 0000000..95df71c
--- /dev/null
+++ b/tests/serve/test_recolor_curation_view.py
@@ -0,0 +1,249 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Baked colourways reach the curation view, and the adopted pick survives.
+
+`sprite-gen recolor` bakes variant sheets into `<run-dir>/variants/`; the view has to
+show them side by side and record which one the human adopted. Three properties are
+load-bearing and each has a test below:
+
+1. The numbers the view prints come from the BAKE REPORT, not from the view recounting
+ pixels — one truth for "how many pixels this colourway swapped".
+2. Nothing disappears quietly: a report row whose PNG is gone is reported as missing
+ rather than dropped from the list, and a pick naming a variant the current bake no
+ longer produces is kept and flagged (`pickedKnown: False`) instead of cleared.
+3. The pick is a normal curation-sidecar field, so it round-trips through the view's own
+ save route and is carried over by a save that does not author it (the same contract
+ `anchors` has — otherwise an edit made in a run without variants would erase it).
+"""
+
+from __future__ import annotations
+
+import json
+import re
+import threading
+import urllib.request
+from functools import partial
+from http.server import ThreadingHTTPServer
+from pathlib import Path
+
+import pytest
+from PIL import Image
+
+from sprite_gen.effects import recolor
+from sprite_gen.curate.curation import load_curation, recolor_pick
+from sprite_gen.serve.serve_curation import CurationHandler, build_run_state
+from sprite_gen.frames.unpack_atlas import import_png_groups
+
+ROOT = Path(__file__).resolve().parents[2]
+CURATOR = ROOT / "sprite_gen" / "serve" / "curator"
+
+SHIRT = (200, 40, 40, 255)
+TRIM = (30, 30, 60, 255)
+
+
+def _png(path: Path, color, size=(48, 48)) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ Image.new("RGBA", size, color).save(path)
+
+
+def _sheet(path: Path) -> None:
+ """A tiny two-colour sheet: left half shirt, right half trim."""
+ image = Image.new("RGBA", (8, 4), SHIRT)
+ for x in range(4, 8):
+ for y in range(4):
+ image.putpixel((x, y), TRIM)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ image.save(path)
+
+
+def baked_run(tmp_path: Path) -> Path:
+ """A run dir with two baked colourways in `variants/`."""
+ pngs = tmp_path / "pngs"
+ _png(pngs / "items" / "1-a.png", (80, 80, 80, 255))
+ _png(pngs / "items" / "2-b.png", (80, 80, 80, 255))
+ run = tmp_path / "run"
+ import_png_groups(run, [{
+ "name": "items",
+ "paths": sorted((pngs / "items").glob("*.png")),
+ "labels": [],
+ "refs": [],
+ }])
+ _sheet(run / "sprite-sheet-alpha.png")
+ spec = tmp_path / "spec.json"
+ spec.write_text(json.dumps({
+ "kind": recolor.SPEC_KIND,
+ "variants": [
+ {"name": "azure", "map": {"#c82828": "#2860c8"}},
+ # `#00ff00` is in no sheet pixel: an unused source the report names.
+ {"name": "moss", "map": {"#c82828": "#3c7a3c", "#00ff00": "#111111"}},
+ ],
+ }), encoding="utf-8")
+ recolor.bake(run / "sprite-sheet-alpha.png", spec, run / recolor.VARIANTS_DIRNAME)
+ return run
+
+
+def _serve(run: Path):
+ CurationHandler.run_dir = run
+ CurationHandler.lang = "en"
+ srv = ThreadingHTTPServer(("127.0.0.1", 0), partial(CurationHandler))
+ threading.Thread(target=srv.serve_forever, daemon=True).start()
+ return srv
+
+
+def _post_curation(run: Path, body: dict) -> int:
+ """The view's own save route, so the server-side write contract is what is tested."""
+ srv = _serve(run)
+ port = srv.server_address[1]
+ try:
+ snapshot = json.loads(urllib.request.urlopen(f"http://127.0.0.1:{port}/api/run").read())
+ payload = {"version": 1, "kind": "sprite-gen-curation",
+ "runRevision": snapshot["runRevision"], "states": {}, **body}
+ req = urllib.request.Request(f"http://127.0.0.1:{port}/api/curation",
+ data=json.dumps(payload).encode(), method="POST")
+ with urllib.request.urlopen(req) as res:
+ return res.status
+ finally:
+ srv.shutdown()
+
+
+def test_baked_variants_surface_with_the_reports_own_numbers(baked_run: Path) -> None:
+ view = build_run_state(baked_run)["recolor"]
+ assert view is not None
+ assert view["match"] == "exact"
+ assert view["base"]["present"] and view["base"]["name"] == "sprite-sheet-alpha.png"
+ names = [v["name"] for v in view["variants"]]
+ assert names == ["azure", "moss"]
+
+ report = json.loads((baked_run / recolor.VARIANTS_DIRNAME / recolor.DEFAULT_REPORT_NAME)
+ .read_text(encoding="utf-8"))
+ for shown, baked in zip(view["variants"], report["variants"]):
+ assert shown["substitutedPixels"] == baked["substituted_pixels"]
+ assert shown["passthroughPixels"] == baked["passthrough_pixels"]
+ assert shown["passthroughColorCount"] == baked["passthrough_color_count"]
+ # the half-sheet that matched, and the half the map never covered — both reported
+ assert view["variants"][0]["substitutedPixels"] == 16
+ assert view["variants"][0]["passthroughPixels"] == 16
+ # a spec typo (a source colour no pixel has) is named, not swallowed
+ assert view["variants"][1]["unusedSources"] == ["#00ff00"]
+ assert view["variants"][0]["unusedSources"] == []
+
+
+def test_variant_urls_serve_and_bust_the_cache(baked_run: Path) -> None:
+ view = build_run_state(baked_run)["recolor"]
+ srv = _serve(baked_run)
+ port = srv.server_address[1]
+ try:
+ for entry in [view["base"], *view["variants"]]:
+ assert re.search(r"\?v=\d+$", entry["url"]), entry["url"]
+ res = urllib.request.urlopen(f"http://127.0.0.1:{port}{entry['url']}")
+ assert res.status == 200
+ assert res.headers["Content-Type"] == "image/png"
+ finally:
+ srv.shutdown()
+
+
+def test_the_thumbnail_crop_comes_from_the_manifest_layout(baked_run: Path) -> None:
+ """Thumbnails crop to a frame, and the box is the one compose wrote — never an
+ assumed origin. Without a layout there is no box, and they show the whole sheet."""
+ assert build_run_state(baked_run)["recolor"]["swatch"] is None, \
+ "no manifest yet — the view must not invent a frame box"
+
+ (baked_run / "manifest.json").write_text(json.dumps({
+ "frame_layout": {"sheetWidth": 8, "sheetHeight": 4, "cellWidth": 4, "cellHeight": 4,
+ "rows": {"items": [{"x": 4, "y": 0, "w": 4, "h": 4}]}},
+ }), encoding="utf-8")
+ assert build_run_state(baked_run)["recolor"]["swatch"] == {
+ "x": 4, "y": 0, "w": 4, "h": 4, "sheetWidth": 8, "sheetHeight": 4}
+
+ (baked_run / "manifest.json").write_text(json.dumps({"atlas": "sprite-sheet-alpha.png"}),
+ encoding="utf-8")
+ assert build_run_state(baked_run)["recolor"]["swatch"] is None
+
+
+def test_a_run_without_a_bake_has_no_variant_section(tmp_path: Path) -> None:
+ pngs = tmp_path / "pngs"
+ _png(pngs / "items" / "1-a.png", (80, 80, 80, 255))
+ run = tmp_path / "run"
+ import_png_groups(run, [{"name": "items",
+ "paths": sorted((pngs / "items").glob("*.png")),
+ "labels": [], "refs": []}])
+ assert build_run_state(run)["recolor"] is None
+
+
+def test_a_foreign_report_file_fails_loud(baked_run: Path) -> None:
+ """A file where the report belongs but of another kind is an error, not "no variants" —
+ reading it as an empty result would hide a bake that landed somewhere unexpected."""
+ path = baked_run / recolor.VARIANTS_DIRNAME / recolor.DEFAULT_REPORT_NAME
+ path.write_text(json.dumps({"kind": "something-else"}), encoding="utf-8")
+ with pytest.raises(SystemExit) as excinfo:
+ build_run_state(baked_run)
+ assert recolor.REPORT_KIND in str(excinfo.value)
+
+
+def test_a_missing_sheet_is_reported_not_dropped(baked_run: Path) -> None:
+ (baked_run / recolor.VARIANTS_DIRNAME / "moss.png").unlink()
+ view = build_run_state(baked_run)["recolor"]
+ assert [v["name"] for v in view["variants"]] == ["azure", "moss"]
+ missing = view["variants"][1]
+ assert missing["present"] is False and missing["url"] is None
+
+
+def test_the_pick_round_trips_through_the_view_save_route(baked_run: Path) -> None:
+ assert _post_curation(baked_run, {"recolor": {"picked": "moss"}}) == 200
+ assert recolor_pick(load_curation(baked_run)) == "moss"
+ view = build_run_state(baked_run)["recolor"]
+ assert view["picked"] == "moss" and view["pickedKnown"] is True
+ # clearing is an intent too: the view sends an empty object, and it lands
+ assert _post_curation(baked_run, {"recolor": {}}) == 200
+ assert recolor_pick(load_curation(baked_run)) is None
+
+
+def test_a_save_that_does_not_author_the_pick_carries_it_over(baked_run: Path) -> None:
+ """A view on a run with no variant section omits the field — that must read as
+ "untouched", not as "cleared" (same carry-over contract as `anchors`)."""
+ assert _post_curation(baked_run, {"recolor": {"picked": "azure"}}) == 200
+ assert _post_curation(baked_run, {}) == 200
+ assert recolor_pick(load_curation(baked_run)) == "azure"
+
+
+def test_a_pick_the_bake_no_longer_produces_is_kept_and_flagged(baked_run: Path) -> None:
+ assert _post_curation(baked_run, {"recolor": {"picked": "azure"}}) == 200
+ report_path = baked_run / recolor.VARIANTS_DIRNAME / recolor.DEFAULT_REPORT_NAME
+ report = json.loads(report_path.read_text(encoding="utf-8"))
+ report["variants"] = [v for v in report["variants"] if v["name"] != "azure"]
+ report_path.write_text(json.dumps(report), encoding="utf-8")
+
+ view = build_run_state(baked_run)["recolor"]
+ assert view["picked"] == "azure", "채택이 조용히 사라졌다"
+ assert view["pickedKnown"] is False, "없는 컬러웨이인데 정상으로 보고했다"
+ assert recolor_pick(load_curation(baked_run)) == "azure"
+
+
+def test_the_spa_wires_the_section_in_every_language() -> None:
+ """The section is three files agreeing: index.html loads the module, boot renders it,
+ and both dictionaries know its strings. A key present in only one language falls back
+ to English silently, which is exactly the drift this catches."""
+ index = (CURATOR / "index.html").read_text(encoding="utf-8")
+ assert '<script src="/src/recolor.js"></script>' in index
+ assert index.index("/src/recolor.js") < index.index("/src/boot.js"), \
+ "recolor.js must load before boot.js calls it"
+
+ boot = (CURATOR / "src" / "boot.js").read_text(encoding="utf-8")
+ assert "seedRecolorPick(run)" in boot and "renderRecolorVariants(run.recolor)" in boot
+
+ module = (CURATOR / "src" / "recolor.js").read_text(encoding="utf-8")
+ for fn in ("function seedRecolorPick", "function renderRecolorVariants",
+ "function pickRecolorVariant"):
+ assert fn in module
+
+ persistence = (CURATOR / "src" / "persistence.js").read_text(encoding="utf-8")
+ assert "payload.recolor" in persistence
+
+ i18n = (CURATOR / "src" / "i18n.js").read_text(encoding="utf-8")
+ en, ko = i18n.split(" ko: {", 1)
+ for key in ("rcTitle", "rcBase", "rcPick", "rcPicked", "rcMissing", "rcMeta",
+ "rcVariantNote", "rcUnusedSources", "rcPickUnknown", "rcPickSaved",
+ "rcPickCleared", "tRcSection", "tRcThumb", "tRcPick",
+ "treeRecolorNote", "tTreeRecolor"):
+ assert f"{key}:" in en, f"en dictionary is missing {key}"
+ assert f"{key}:" in ko, f"ko dictionary is missing {key}"
diff --git a/tests/spec/test_migrate_breathe.py b/tests/spec/test_migrate_breathe.py
new file mode 100644
index 0000000..4c51400
--- /dev/null
+++ b/tests/spec/test_migrate_breathe.py
@@ -0,0 +1,112 @@
+# SPDX-License-Identifier: Apache-2.0
+"""`sprite-gen migrate-breathe` — 폐기 사이드카를 옮기는 유일한 경로.
+
+모듈 docstring 이 "무엇을 버렸는지 전부 출력한다" 를 계약으로 걸었으므로, 폐기 키가
+하나라도 보고에서 빠지면 그 계약이 깨진다 (validator note 2026-07-25: `hold` 가 목록에
+없어 조용히 사라졌다).
+"""
+
+import json
+import sys
+from pathlib import Path
+
+import pytest
+
+ROOT = Path(__file__).resolve().parent.parent.parent
+sys.path.insert(0, str(ROOT))
+
+from sprite_gen.curate.curation import RETIRED_BREATHE_KEYS, state_breathe # noqa: E402
+from sprite_gen.spec.migrate_breathe import migrate_entry, run # noqa: E402
+
+
+def _sidecar(tmp_path, breathe):
+ data = {"version": 1, "kind": "sprite-gen-curation",
+ "states": {"idle": {"selected": [0, 1], "breathe": breathe}, "jump": {"selected": [0]}}}
+ (tmp_path / "curation.json").write_text(json.dumps(data), encoding="utf-8")
+ return tmp_path / "curation.json"
+
+
+ALL_RETIRED = {"splits": [0.32, 0.55], "amplitude": 2, "subpixel": True, "hold": 3}
+
+
[email protected]("key", sorted(RETIRED_BREATHE_KEYS))
+def test_every_retired_key_is_reported_as_dropped(key):
+ """버린 것을 전부 출력한다 — 목록에서 빠진 키는 조용히 사라진다."""
+ fresh, dropped = migrate_entry({key: ALL_RETIRED[key], "breaths": 3})
+ assert any(line.startswith(f"{key}=") for line in dropped), \
+ f"{key} 를 버렸다는 보고가 없다: {dropped}"
+ assert key not in fresh
+
+
+def test_breaths_survives_and_the_rest_is_reset():
+ fresh, _ = migrate_entry({**ALL_RETIRED, "breaths": 5})
+ assert fresh["breaths"] == 5, "사람이 고른 호흡 횟수는 보존한다"
+ assert set(fresh) == {"depth", "lag", "breaths"}
+ assert not any(k in fresh for k in RETIRED_BREATHE_KEYS)
+
+
+def test_a_non_integer_breaths_falls_back_loudly():
+ fresh, dropped = migrate_entry({"splits": [0.5], "breaths": "셋"})
+ assert fresh["breaths"] == 1
+ assert any("breaths=" in line for line in dropped), "되돌린 사실이 보고돼야 한다"
+
+
+def test_dry_run_does_not_touch_the_file(tmp_path, capsys):
+ path = _sidecar(tmp_path, dict(ALL_RETIRED, breaths=3))
+ before = path.read_text(encoding="utf-8")
+ assert run(run_dir=tmp_path) == 0
+ assert path.read_text(encoding="utf-8") == before, "dry-run 이 파일을 건드렸다"
+ assert "dry-run" in capsys.readouterr().out
+
+
+def test_apply_makes_the_sidecar_bakeable(tmp_path):
+ path = _sidecar(tmp_path, dict(ALL_RETIRED, breaths=3))
+ with pytest.raises(SystemExit): # 옮기기 전에는 loud reject
+ state_breathe(json.loads(path.read_text(encoding="utf-8")), "idle")
+ assert run(run_dir=tmp_path, apply=True) == 0
+ data = json.loads(path.read_text(encoding="utf-8"))
+ cfg = state_breathe(data, "idle") # 이제 통과한다
+ assert cfg["breaths"] == 3 and cfg["rigid_row"] is None
+ assert data["states"]["jump"] == {"selected": [0]}, "관계없는 상태를 건드렸다"
+
+
+def test_running_twice_is_idempotent(tmp_path, capsys):
+ path = _sidecar(tmp_path, dict(ALL_RETIRED, breaths=2))
+ run(run_dir=tmp_path, apply=True)
+ once = path.read_text(encoding="utf-8")
+ capsys.readouterr()
+ assert run(run_dir=tmp_path, apply=True) == 0
+ assert path.read_text(encoding="utf-8") == once
+ assert "옮길 분할선 설정이 없다" in capsys.readouterr().out
+
+
+def test_a_missing_sidecar_fails_loudly(tmp_path, capsys):
+ assert run(run_dir=tmp_path) == 1
+ assert "없다" in capsys.readouterr().out
+
+
+def test_a_non_integer_breaths_is_reported_not_truncated() -> None:
+ """비정수 `breaths` 는 조용히 깎지 않고 **버렸다고 말한다**.
+
+ `int(2.7)` 은 조용히 2 다 — 사용자가 적은 값과 다른 값이 산출물에 들어가고 `dropped`
+ 엔 한 줄도 안 남는다. `"3.5"` 문자열만 `ValueError` 로 걸려 보고됐고 실수만 샜다
+ (validator note 2026-07-26). 굽기(`curation._exact_int`)와 큐레이터 미러가 이미 거부하는
+ 값이라 이 **세 번째 구현**만 규칙을 안 지키고 있었고, 이 모듈 자신의 계약이
+ "무엇을 버렸는지 전부 출력한다" 다."""
+ from sprite_gen.spec.migrate_breathe import migrate_entry
+
+ # `nan`/`inf` 도 담는다: `json.loads` 는 기본값으로 `NaN` 리터럴을 받으므로 사이드카에서
+ # 실제로 들어오고, `int(nan)` 은 `ValueError` 를 올려 마이그레이션을 **트레이스백으로
+ # 죽인다**. 값 목록에 없어서 그 회귀를 그물이 못 봤다 (노을이 실측 2026-07-26 R2).
+ for value in (2.7, "3.5", 1.5, 0.5, float("nan"), float("inf"), float("-inf")):
+ fresh, dropped = migrate_entry({"splits": [10], "breaths": value})
+ said = [d for d in dropped if d.startswith("breaths=")]
+ assert said, f"breaths={value!r} 를 조용히 {fresh['breaths']} 로 바꿨다 — 버린 걸 안 말한다"
+ assert "정수" in said[0], f"breaths={value!r}: 정수 계약이 아닌 사유로 버렸다 ({said[0]})"
+
+ # 정수로 표현되는 실수·정수는 그대로 통과한다 (과잉 거부 금지)
+ for value in (3, 3.0):
+ fresh, dropped = migrate_entry({"splits": [10], "breaths": value})
+ assert fresh["breaths"] == 3, f"{value!r} 가 3 으로 안 들어갔다"
+ assert not [d for d in dropped if d.startswith("breaths=")], \
+ f"{value!r} 는 멀쩡한 값인데 버렸다고 보고한다"
diff --git a/tests/spec/test_publish_rwlock_cross_process.py b/tests/spec/test_publish_rwlock_cross_process.py
new file mode 100644
index 0000000..91e628e
--- /dev/null
+++ b/tests/spec/test_publish_rwlock_cross_process.py
@@ -0,0 +1,110 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Cross-process and shared-mode contracts for the publish reader/writer lock."""
+
+from __future__ import annotations
+
+import json
+import subprocess
+import sys
+import threading
+import time
+from pathlib import Path
+
+import pytest
+
+from sprite_gen.spec import runio
+
+_TIMEOUT = 30.0
+_CHILD = """
+import json, sys, time
+from pathlib import Path
+from sprite_gen.spec import runio
+run, mode, hold = Path(sys.argv[1]), sys.argv[2], float(sys.argv[3])
+guard = runio.read_guard if mode == "read" else runio.publish_guard
+print(json.dumps({"phase": "start", "at": time.time()}), flush=True)
+with guard(run):
+ print(json.dumps({"phase": "acquired", "at": time.time()}), flush=True)
+ time.sleep(hold)
+print(json.dumps({"phase": "released", "at": time.time()}), flush=True)
+"""
+
+
+class ChildGuard:
+ def __init__(self, run_dir: Path, mode: str, hold: float) -> None:
+ self.events: list[dict] = []
+ self.process = subprocess.Popen(
+ [sys.executable, "-c", _CHILD, str(run_dir), mode, str(hold)],
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ text=True,
+ encoding="utf-8",
+ )
+ self.thread = threading.Thread(target=self._drain, daemon=True)
+ self.thread.start()
+
+ def _drain(self) -> None:
+ assert self.process.stdout is not None
+ for line in self.process.stdout:
+ self.events.append(json.loads(line))
+
+ def at(self, phase: str) -> float | None:
+ return next((event["at"] for event in self.events if event["phase"] == phase), None)
+
+ def wait_for(self, phase: str) -> float:
+ deadline = time.monotonic() + _TIMEOUT
+ while time.monotonic() < deadline:
+ value = self.at(phase)
+ if value is not None:
+ return value
+ if self.process.poll() is not None:
+ self.thread.join(1)
+ if self.at(phase) is None:
+ assert self.process.stderr is not None
+ raise AssertionError(
+ f"child exited {self.process.returncode} before {phase}:\n"
+ f"{self.process.stderr.read()}"
+ )
+ time.sleep(0.01)
+ raise AssertionError(f"child did not reach {phase} within {_TIMEOUT}s")
+
+ def finish(self) -> None:
+ try:
+ self.process.wait(timeout=_TIMEOUT)
+ finally:
+ if self.process.poll() is None: # pragma: no cover - hung regression
+ self.process.kill()
+ self.thread.join(2)
+
+
+def run_dir(tmp_path: Path) -> Path:
+ path = tmp_path / "run"
+ path.mkdir()
+ return path
+
+
+def test_reader_process_blocks_until_publish_releases(run_dir: Path) -> None:
+ child = ChildGuard(run_dir, "read", 0)
+ try:
+ with runio.publish_guard(run_dir):
+ child.wait_for("start")
+ time.sleep(0.5)
+ assert child.at("acquired") is None
+ released = time.time()
+ assert child.wait_for("acquired") >= released
+ finally:
+ child.finish()
+
+
+def test_two_process_readers_hold_shared_lock_concurrently(run_dir: Path) -> None:
+ hold = 2.0
+ child = ChildGuard(run_dir, "read", hold)
+ try:
+ child.wait_for("acquired")
+ started = time.monotonic()
+ with runio.read_guard(run_dir):
+ waited = time.monotonic() - started
+ assert child.at("released") is None
+ assert waited < hold / 2
+ finally:
+ child.finish()
diff --git a/tests/spec/test_request_read_no_mutation.py b/tests/spec/test_request_read_no_mutation.py
new file mode 100644
index 0000000..3e73d61
--- /dev/null
+++ b/tests/spec/test_request_read_no_mutation.py
@@ -0,0 +1,176 @@
+# SPDX-License-Identifier: Apache-2.0
+"""조회는 런 파일을 쓰지 않는다 (plan sprite-gen/state-revision-read-mutation).
+
+합성 회귀는 `state_revision()` 조회 중 은퇴 키를 정규화하더라도 request 바이트와
+세대 지문이 바뀌지 않아야 함을 고정한다.
+
+계약 (SRP): **읽는 쪽은 읽기만 한다.** 은퇴 키는 로더가 메모리에서 현행 키로 정규화해
+호출부 동작을 유지하고, 디스크 스키마 이관은 사용자가 명시적으로 부르는 단일 writer
+(`runio.migrate_request_file` / `sprite-gen migrate-request`) 에서만 원자적으로 일어난다.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+from pathlib import Path
+
+import pytest
+
+from sprite_gen.curate import curation as curation_mod
+from sprite_gen.curate.curation import state_revision
+from sprite_gen.spec.runio import REQUEST_FILENAME, load_request
+
+
+def write_synthetic_fixture_a_request(run_dir: Path, fit: dict) -> None:
+ """은퇴 키를 안은 합성 scratch 런의 최소 모형."""
+ run_dir.mkdir(parents=True, exist_ok=True)
+ (run_dir / REQUEST_FILENAME).write_text(json.dumps({
+ "version": 1, "kind": "sprite-gen-request", "engine": "component-row",
+ "character": {"id": "synthetic_fixture_a", "description": "", "base_image": None},
+ "cell": {"shape": "square", "width": 96, "height": 96, "safe_margin_x": 8,
+ "safe_margin_y": 8, "size": 96, "safe_margin": 8},
+ "chroma_key": {"name": "magenta", "hex": "#FF00FF", "rgb": [255, 0, 255],
+ "selection": "fallback"},
+ "states": {"walk": {"frames": 2, "fps": 8, "loop": True, "action": "x"}},
+ "fit": fit,
+ }, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
+
+
+def write_frames_manifest(run_dir: Path) -> None:
+ """`state_revision` 이 행 지문을 계산하려면 manifest row 가 있어야 한다 (없으면 None
+ 을 돌려주고 조기 반환해, 재현하려는 로더 경로를 통과하지 않는다)."""
+ frames = run_dir / "frames"
+ frames.mkdir(parents=True, exist_ok=True)
+ (frames / "frames-manifest.json").write_text(json.dumps({
+ "rows": [{"state": "walk", "frames": 2, "files": ["frame-0.png", "frame-1.png"]}],
+ }), encoding="utf-8")
+
+
+def sha256_of(path: Path) -> str:
+ return hashlib.sha256(path.read_bytes()).hexdigest()
+
+
+def synthetic_fixture_a_run(tmp_path: Path) -> Path:
+ run_dir = tmp_path / "synthetic_fixture_a"
+ write_synthetic_fixture_a_request(run_dir, {"pixel_perfect": True, "logical_height": 48})
+ write_frames_manifest(run_dir)
+ return run_dir
+
+
+def test_state_revision_does_not_rewrite_the_request(synthetic_fixture_a_run: Path) -> None:
+ """사고 재현 고정: 조회 한 번이 canonical 런 파일을 바꾸지 않는다."""
+ path = synthetic_fixture_a_run / REQUEST_FILENAME
+ before = sha256_of(path)
+
+ assert state_revision(synthetic_fixture_a_run, "walk") is not None
+
+ assert sha256_of(path) == before, (
+ "state_revision() 이 sprite-request.json 을 재기록했다 — 조회가 canonical 런을 "
+ "오염시킨다 (합성 조회 회귀)")
+ assert "pixel_perfect" in json.loads(path.read_text(encoding="utf-8"))["fit"]
+
+
+def test_state_revision_does_not_move_the_generation_fingerprint(synthetic_fixture_a_run: Path) -> None:
+ """`run_revision` 은 request 바이트를 해싱한다 — 읽기가 파일을 쓰면 조회만으로 세대
+ 지문이 움직여, 그 런의 큐레이션 사이드카가 stale 로 떨어진다. 읽기는 세대를 흔들지
+ 않는다."""
+ before = curation_mod.run_revision(synthetic_fixture_a_run)
+ state_revision(synthetic_fixture_a_run, "walk")
+ assert curation_mod.run_revision(synthetic_fixture_a_run) == before
+
+
+def read_everything(run_dir: Path) -> None:
+ """조회 API 전수 — 어느 진입점으로 읽어도 런 디렉터리는 바이트 불변이어야 한다."""
+ from sprite_gen.curate import anchor as anchor_mod
+ from sprite_gen.curate.curation import load_curation, load_curation_report
+
+ load_request(run_dir)
+ anchor_mod.load_request(run_dir)
+ state_revision(run_dir, "walk")
+ curation_mod.run_revision(run_dir)
+ load_curation(run_dir)
+ load_curation_report(run_dir)
+
+
+def run_dir_sha256(run_dir: Path) -> dict[str, str]:
+ return {str(p.relative_to(run_dir)): sha256_of(p)
+ for p in sorted(run_dir.rglob("*")) if p.is_file()}
+
+
+def test_read_api_surface_is_byte_stable(synthetic_fixture_a_run: Path) -> None:
+ """조회 API 전수: 어느 진입점으로 읽어도 런 디렉터리 바이트가 불변이다.
+
+ 한 진입점만 잠그면 다음 진입점이 같은 병을 다시 만든다 — 계약은 "이 함수" 가 아니라
+ "읽는 쪽" 전체다."""
+ before = run_dir_sha256(synthetic_fixture_a_run)
+ read_everything(synthetic_fixture_a_run)
+ assert run_dir_sha256(synthetic_fixture_a_run) == before
+
+
+def test_read_api_surface_is_byte_stable_when_the_sidecar_is_stale(synthetic_fixture_a_run: Path) -> None:
+ """세대가 어긋난 큐레이션 사이드카를 읽어도 런 디렉터리에 파일이 생기지 않는다.
+
+ `load_curation_report` 는 드롭을 판정하면서 원문을 `curation.stale-<hash>.json` 으로
+ 써 뒀다 — 조회만 했는데 런 디렉터리에 새 파일이 생겼다는 뜻이고, 이 플랜이 request
+ 로더에서 잡은 것과 같은 계열이다 (노을이 검수 Scope 밖 관찰, 2026-08-02). 드롭 시점엔
+ 아직 잃은 것이 없다: `curation.json` 은 그대로고, 백업은 실제로 덮는 writer
+ (`write_curation_atomic`) 한 곳에서만 난다."""
+ from sprite_gen.curate.curation import CURATION_FILENAME
+
+ (synthetic_fixture_a_run / CURATION_FILENAME).write_text(json.dumps({
+ "version": 1, "kind": "sprite-gen-curation",
+ "run_revision": "0" * 12, # 현재 세대와 어긋난다 → 행 단위 구제 경로
+ "states": {"walk": {"selected": [1]}}, # 행 스탬프 없음 → 드롭 대상
+ }), encoding="utf-8")
+ before = run_dir_sha256(synthetic_fixture_a_run)
+
+ doc, report = curation_mod.load_curation_report(synthetic_fixture_a_run)
+ assert doc is None and report["dropped"] == ["walk"], "드롭 경로를 실제로 밟아야 한다"
+ read_everything(synthetic_fixture_a_run)
+
+ assert run_dir_sha256(synthetic_fixture_a_run) == before, (
+ "조회가 런 디렉터리에 썼다 — 세대 불일치 사이드카를 읽는 것만으로 파일이 생기거나 바뀐다")
+ assert not list(synthetic_fixture_a_run.glob("curation.stale-*.json"))
+
+
+def test_retired_key_still_reads_as_the_current_key(synthetic_fixture_a_run: Path) -> None:
+ """읽기 호환은 유지된다 — 은퇴 키 런의 호출부는 현행 키를 본다 (메모리 정규화).
+
+ 디스크를 안 쓰는 것과 은퇴 키를 못 읽는 것은 다르다. 후자가 되면 승인 런이 파이프라인
+ 에서 통째로 떨어진다."""
+ request = load_request(synthetic_fixture_a_run)
+ assert request["fit"]["pixel_unfake"] is True
+ assert "pixel_perfect" not in request["fit"]
+ assert request["fit"]["logical_height"] == 48
+
+
+def test_loader_holds_no_writer_call(synthetic_fixture_a_run: Path) -> None:
+ """구조 단정: 로더 경로에 쓰기 호출 자체가 없다.
+
+ 런타임 단정만 두면 "락이 있을 때만 안 쓴다" 류의 조건부 쓰기가 다시 기어들어와도
+ fixture 가 그 조건을 안 밟으면 초록으로 통과한다. 그래서 읽기 경로에 writer 심볼이
+ **존재하지 않는다**는 것을 AST 로 본다."""
+ import ast
+
+ WRITERS = {"atomic_write_text", "atomic_write_set", "atomic_save_image",
+ "write_text", "write_bytes", "replace", "rename", "unlink", "mkdir"}
+ 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"}
+ offenders: list[str] = []
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.FunctionDef) or node.name not in read_path:
+ continue
+ for child in ast.walk(node):
+ if isinstance(child, ast.Call):
+ target = child.func
+ name = (target.attr if isinstance(target, ast.Attribute)
+ else target.id if isinstance(target, ast.Name) else None)
+ if name in WRITERS:
+ offenders.append(f"runio.py:{child.lineno} {node.name}() -> {name}()")
+ assert not offenders, (
+ "읽기 경로가 쓰기를 호출한다:\n " + "\n ".join(offenders)
+ + "\n→ 스키마 이관은 `migrate_request_file` (명시 writer) 에서만 한다")
diff --git a/tests/spec/test_request_write_isolation.py b/tests/spec/test_request_write_isolation.py
new file mode 100644
index 0000000..12d026f
--- /dev/null
+++ b/tests/spec/test_request_write_isolation.py
@@ -0,0 +1,232 @@
+# SPDX-License-Identifier: Apache-2.0
+"""`sprite-request.json` 의 read-modify-write 는 격리 도메인 **하나** 안에서만 일어난다
+(plan sprite-gen/state-revision-read-mutation).
+
+이 파일이 소유하는 계약은 조회 무변(그건 `test_request_read_no_mutation.py` 가 갖는다)이
+아니라 **쓰기끼리의 상호배제**다:
+
+- request 를 read-modify-write 하는 모든 프로덕션 경로 — 이관 writer(`migrate_request_file`),
+ 리롤 테이크 기록(`reroll.record_take`), 트윈 테이크 기록(`interpolate.write_take`), 뷰의
+ fps POST — 는 **같은 `publish_guard` 배타락** 안에서 락 획득 **후** fresh 재독하고 원자
+ 교체한다. 그래서 lost update 가 구조적으로 불가능하다.
+
+왜 이 파일이 생겼나 (노을이 검수 note 1, 2026-08-02): 이관 writer 는 문서를 락 **밖에서**
+읽고 나서 `.sprite-gen.lock` (파이프라인 단계용 단일 writer 락)을 잡았다. 두 가지가 동시에
+틀렸다 — (a) read-then-lock 이라 읽은 뒤 잡기 전 사이의 편집을 stale 문서로 덮고,
+(b) 편집 writer 들은 `publish_guard` 를 쓰므로 **서로 배제하지 않는 두 도메인**이었다.
+밀리초 창이지만 리롤이 방금 기록한 테이크가 이관 한 번에 통째로 사라질 수 있었다.
+"""
+
+from __future__ import annotations
+
+import ast
+import json
+import threading
+import time
+from pathlib import Path
+
+from PIL import Image
+
+from sprite_gen.effects import interpolate, reroll
+from sprite_gen.spec import runio
+from sprite_gen.spec.runio import REQUEST_FILENAME, migrate_request_file
+
+# 이관 writer 가 문서를 읽은 **뒤** 쓰기 전까지 편집자에게 주는 시간. 배제되지 않는 두 도메인
+# (수리 전 코드)이라면 이 창 안에서 편집이 통째로 완료되고, 이관이 그것을 덮어 잃는다.
+# 배제되면 편집자는 이 시간 동안 락에서 대기만 하고 아무것도 잃지 않는다.
+RACE_WINDOW_SECONDS = 0.3
+
+
+def _write_request(run_dir: Path, fit: dict) -> None:
+ run_dir.mkdir(parents=True, exist_ok=True)
+ (run_dir / REQUEST_FILENAME).write_text(json.dumps({
+ "version": 1, "kind": "sprite-gen-request", "engine": "component-row",
+ "character": {"id": "racebot", "description": "", "base_image": None},
+ "cell": {"shape": "square", "width": 96, "height": 96, "safe_margin_x": 8,
+ "safe_margin_y": 8, "size": 96, "safe_margin": 8},
+ "chroma_key": {"name": "magenta", "hex": "#FF00FF", "rgb": [255, 0, 255],
+ "selection": "fallback"},
+ "states": {"walk": {"frames": 2, "fps": 8, "loop": True, "action": "x"}},
+ "fit": fit,
+ }, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
+
+
+def _run_the_race(monkeypatch, run_dir: Path, edit) -> None:
+ """이관 writer 의 read→write 사이에 편집 writer 를 밀어 넣고 둘 다 끝날 때까지 기다린다.
+
+ 이관자가 문서를 읽은 직후 `read_done` 을 올리고, 편집자가 "지금 들어간다"(`edit_attempted`)
+ 를 올릴 때까지 기다린 뒤 `RACE_WINDOW_SECONDS` 를 더 준다. 배제가 없으면 편집이 그 창
+ 안에서 완주하고 이관의 stale 쓰기에 지워진다. 배제되면 편집자는 창 내내 락 대기다."""
+ read_done = threading.Event()
+ edit_attempted = threading.Event()
+ failures: list[BaseException] = []
+ real_read = runio._read_request_document
+
+ def hooked(target_dir):
+ document = real_read(target_dir)
+ if threading.current_thread().name == "migrator":
+ read_done.set()
+ edit_attempted.wait(5.0)
+ time.sleep(RACE_WINDOW_SECONDS)
+ return document
+
+ monkeypatch.setattr(runio, "_read_request_document", hooked)
+
+ def migrate() -> None:
+ try:
+ migrate_request_file(run_dir, apply=True)
+ except BaseException as exc: # noqa: BLE001 - 스레드 밖으로 옮긴다
+ failures.append(exc)
+ read_done.set()
+
+ def editor() -> None:
+ try:
+ read_done.wait(5.0)
+ edit_attempted.set()
+ edit()
+ except BaseException as exc: # noqa: BLE001
+ failures.append(exc)
+
+ threads = [threading.Thread(target=migrate, name="migrator"),
+ threading.Thread(target=editor, name="editor")]
+ for thread in threads:
+ thread.start()
+ for thread in threads:
+ thread.join(30.0)
+ assert not thread.is_alive(), f"{thread.name} 스레드가 끝나지 않았다 (락 교착 의심)"
+ assert not failures, failures
+
+
+def test_migration_racing_a_reroll_take_loses_neither_write(tmp_path, monkeypatch) -> None:
+ """이관 vs 리롤 테이크 기록: 둘 다 살아남는다 (lost update 불가).
+
+ 수리 전에는 이관자가 락 밖에서 읽은 stale 문서를 원자 교체해, 그 사이 리롤이 기록한
+ `states.walk.takes` 가 흔적 없이 사라졌다 (반대 순서면 이관이 조용히 되돌아간다)."""
+ run_dir = tmp_path / "run"
+ _write_request(run_dir, {"pixel_perfect": True, "logical_height": 48})
+
+ _run_the_race(monkeypatch, run_dir,
+ lambda: reroll.record_take(run_dir, "walk", "reroll1", 2))
+
+ on_disk = json.loads((run_dir / REQUEST_FILENAME).read_text(encoding="utf-8"))
+ assert on_disk["fit"] == {"logical_height": 48, "pixel_unfake": True}, "이관이 사라졌다"
+ assert on_disk["states"]["walk"].get("takes") == [{"label": "reroll1", "frames": 2}], (
+ "리롤이 기록한 테이크가 이관의 stale 쓰기에 지워졌다 — 두 writer 가 서로 배제되지 않는다")
+
+
+def test_migration_racing_an_interpolate_take_loses_neither_write(tmp_path, monkeypatch) -> None:
+ """이관 vs 트윈 테이크 기록: 같은 계약, 같은 락 (`interpolate.write_take`)."""
+ run_dir = tmp_path / "run"
+ _write_request(run_dir, {"pixel_perfect": True, "logical_height": 48})
+ request = json.loads((run_dir / REQUEST_FILENAME).read_text(encoding="utf-8"))
+ image = Image.new("RGBA", (8, 8), (255, 0, 255, 255))
+
+ _run_the_race(monkeypatch, run_dir,
+ lambda: interpolate.write_take(run_dir, request, "walk", "tween1", image))
+
+ on_disk = json.loads((run_dir / REQUEST_FILENAME).read_text(encoding="utf-8"))
+ assert on_disk["fit"] == {"logical_height": 48, "pixel_unfake": True}, "이관이 사라졌다"
+ assert on_disk["states"]["walk"].get("takes") == [{"label": "tween1", "frames": 1}], (
+ "트윈이 기록한 테이크가 이관의 stale 쓰기에 지워졌다")
+
+
+def test_migration_does_not_take_the_pipeline_writer_lock(tmp_path) -> None:
+ """이관은 `.sprite-gen.lock` 도메인을 쓰지 않는다 — 그 락은 request 를 지키지 않는다.
+
+ 파이프라인 락이 지키는 것은 프레임·아틀라스 같은 단계 산출물이고, 추출·굽기는
+ `sprite-request.json` 을 쓰지 않는다. 안 만지는 자원의 락을 잡으면 보호받는다는 착시만
+ 남는다 — 실제 경쟁자(리롤·트윈·fps 편집)는 그 락을 안 잡으므로 그대로 통과했다.
+ 한 자원에 격리 도메인은 하나이고, request 의 도메인은 `publish_guard` 다."""
+ from sprite_gen.spec.runio import LOCK_FILENAME
+
+ run_dir = tmp_path / "run"
+ _write_request(run_dir, {"pixel_perfect": True})
+ # 다른 살아있는 홀더의 최소 모형 (pid 1 = launchd/init) — 이관은 이걸 보지 않는다
+ (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 json.loads((run_dir / REQUEST_FILENAME).read_text(
+ encoding="utf-8"))["fit"] == {"pixel_unfake": True}
+ # 남의 락을 소비하지도 않는다 (파일은 그대로)
+ assert json.loads((run_dir / LOCK_FILENAME).read_text(encoding="utf-8"))["owner"] == "extract"
+
+
+def test_migration_leaves_no_lock_residue_in_the_run_dir(tmp_path) -> None:
+ """이관이 끝나면 런 디렉터리에 새로 남는 파일이 없다 — request 하나만 바뀐다.
+
+ publish rwlock 사이드카는 런 디렉터리 **밖**(`.<name>.sg-rwlock`)에 산다. 안에 남으면
+ 이관 한 번이 그 런의 파일 목록·세대 판정을 건드린다."""
+ from sprite_gen.spec.runio import LOCK_FILENAME
+
+ run_dir = tmp_path / "run"
+ _write_request(run_dir, {"pixel_perfect": True})
+ before = {p.name for p in run_dir.iterdir()}
+
+ migrate_request_file(run_dir, apply=True)
+
+ assert {p.name for p in run_dir.iterdir()} == before
+ assert not (run_dir / LOCK_FILENAME).exists()
+
+
+def _callee_name(func: ast.expr) -> str | None:
+ if isinstance(func, ast.Attribute):
+ return func.attr
+ if isinstance(func, ast.Name):
+ return func.id
+ return None
+
+
+def _calls_inside_publish_guard(tree: ast.AST) -> set[int]:
+ """`with publish_guard(...)` 블록 안에 있는 Call 노드 id 집합."""
+ guarded: set[int] = set()
+ for node in ast.walk(tree):
+ if not isinstance(node, (ast.With, ast.AsyncWith)):
+ continue
+ if not any(isinstance(item.context_expr, ast.Call)
+ and _callee_name(item.context_expr.func) == "publish_guard"
+ for item in node.items):
+ continue
+ for child in ast.walk(node):
+ if isinstance(child, ast.Call):
+ guarded.add(id(child))
+ return guarded
+
+
+def test_every_request_write_is_inside_the_publish_guard() -> None:
+ """구조 단정: request 를 되쓰는 프로덕션 호출은 전부 `publish_guard` 블록 안에 있다.
+
+ 런타임 경쟁 테스트만 두면 새 편집 진입점(다음 POST 핸들러)이 락 밖에서 `write_request`
+ 를 부르는 회귀를 못 잡는다 — 그 경로를 밟는 fixture 가 없으면 초록으로 지나간다. 그래서
+ "락 안에 있다" 를 AST 로 본다.
+
+ 범위: 되쓰기 게이트(`write_request`) 호출 전부 + 이관 writer 의 원자 교체. 새 런을
+ **만드는** 경로(`prepare`, `unpack_atlas` 의 스테이징)는 제외한다 — 기존 문서를 읽어
+ 고치는 것이 아니라 처음 발행하는 것이고, unpack 의 발행 스왑 자체는 `_publish_run` 의
+ `publish_guard` 안에서 일어난다."""
+ root = Path(__file__).resolve().parents[2]
+ offenders: list[str] = []
+ for path in sorted((root / "sprite_gen").rglob("*.py")):
+ tree = ast.parse(path.read_text(encoding="utf-8"))
+ guarded = _calls_inside_publish_guard(tree)
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.Call) or _callee_name(node.func) != "write_request":
+ continue
+ if id(node) not in guarded:
+ offenders.append(f"{path.relative_to(root)}:{node.lineno} write_request()")
+
+ runio_path = root / "sprite_gen" / "spec" / "runio.py"
+ runio_tree = ast.parse(runio_path.read_text(encoding="utf-8"))
+ runio_guarded = _calls_inside_publish_guard(runio_tree)
+ for node in ast.walk(runio_tree):
+ if not isinstance(node, ast.FunctionDef) or node.name != "migrate_request_file":
+ continue
+ for child in ast.walk(node):
+ if (isinstance(child, ast.Call) and _callee_name(child.func) == "atomic_write_text"
+ and id(child) not in runio_guarded):
+ offenders.append(f"sprite_gen/spec/runio.py:{child.lineno} "
+ f"atomic_write_text() in migrate_request_file()")
+
+ assert not offenders, (
+ "publish_guard 밖에서 request 를 되쓰는 경로:\n " + "\n ".join(offenders)
+ + "\n→ 락 획득 후 fresh 재독 → 원자 교체. request 의 격리 도메인은 publish_guard 하나다")
diff --git a/tests/spec/test_runio_publish_set.py b/tests/spec/test_runio_publish_set.py
new file mode 100644
index 0000000..e341b3a
--- /dev/null
+++ b/tests/spec/test_runio_publish_set.py
@@ -0,0 +1,60 @@
+# SPDX-License-Identifier: Apache-2.0
+"""`runio.atomic_write_set` — publish a set of files, or publish none of them.
+
+The single-file writers make each artifact appear whole, which is enough for a
+stage that writes one file. A stage that publishes a set (the composite bake:
+sheets, their manifests, and the report naming which sheets are current) needs
+the set to appear together — a write error partway through must not leave a
+published sheet that no report mentions.
+
+What is pinned here is the observable failure: staging allocates everything
+first, so a payload that cannot be written publishes nothing and leaves no temp
+files behind. A crash between renames is out of reach of any userspace writer and
+is documented as such, not tested as if it were prevented.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+from sprite_gen.spec.runio import atomic_write_set
+
+
+def _names(directory: Path) -> set[str]:
+ return {path.name for path in directory.iterdir()}
+
+
+def test_a_set_lands_together(tmp_path: Path) -> None:
+ atomic_write_set({
+ tmp_path / "sheet.png": b"\x89PNG-ish",
+ tmp_path / "sheet.manifest.json": '{"ok": true}\n',
+ })
+
+ assert (tmp_path / "sheet.png").read_bytes() == b"\x89PNG-ish"
+ assert (tmp_path / "sheet.manifest.json").read_text(encoding="utf-8") == '{"ok": true}\n'
+ assert _names(tmp_path) == {"sheet.png", "sheet.manifest.json"}
+
+
+def test_a_failing_payload_publishes_nothing_and_leaves_no_temp_files(tmp_path: Path) -> None:
+ """The second payload cannot be staged, so the first must not appear either."""
+ (tmp_path / "report.json").write_text("previous\n", encoding="utf-8")
+
+ with pytest.raises(OSError):
+ atomic_write_set({
+ tmp_path / "sheet.png": b"new",
+ tmp_path / "missing-dir" / "other.png": b"new",
+ tmp_path / "report.json": "new\n",
+ })
+
+ assert _names(tmp_path) == {"report.json"}
+ assert (tmp_path / "report.json").read_text(encoding="utf-8") == "previous\n"
+
+
+def test_an_existing_target_is_replaced_not_appended(tmp_path: Path) -> None:
+ (tmp_path / "sheet.png").write_bytes(b"old-and-longer")
+
+ atomic_write_set({tmp_path / "sheet.png": b"new"})
+
+ assert (tmp_path / "sheet.png").read_bytes() == b"new"
diff --git a/tests/test_subject_profile.py b/tests/test_subject_profile.py
new file mode 100644
index 0000000..01f8167
--- /dev/null
+++ b/tests/test_subject_profile.py
@@ -0,0 +1,222 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Subject profile: the sparse-frame floor is declared by what the run draws.
+
+Synthetic boundary cases demonstrate that one absolute floor cannot scale across
+cell resolutions. Profiles preserve debris rejection while deriving the floor
+from drawable cell geometry.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+from PIL import Image, ImageDraw
+
+from conftest import run_script
+from sprite_gen.spec.subject import cell_area, default_min_used_pixels, subject_kind
+
+FRAMES = 3
+
+
+def _make_run(run_dir: Path, density: int, subject: str | None, cell: int = 64) -> Path:
+ """A hand-built minimal run: request + one magenta-keyed strip whose frames
+ carry ~density opaque pixels each (solid square, no AA)."""
+ run_dir.mkdir(parents=True, exist_ok=True)
+ request = {
+ "version": 1, "kind": "sprite-gen-request", "engine": "component-row",
+ "character": {"id": "profiled", "description": "", "base_image": None},
+ "cell": {"shape": "square", "width": cell, "height": cell,
+ "safe_margin_x": 6, "safe_margin_y": 6, "size": cell, "safe_margin": 6},
+ "chroma_key": {"name": "magenta", "hex": "#FF00FF", "rgb": [255, 0, 255],
+ "selection": "explicit"},
+ "states": {"burst": {"frames": FRAMES, "fps": 8, "loop": True}},
+ "style": "test", "motion_phase_guides": False, "layout": "taxonomy/v1",
+ }
+ if subject:
+ request["subject"] = subject
+ (run_dir / "sprite-request.json").write_text(json.dumps(request) + "\n", encoding="utf-8")
+ strip = Image.new("RGB", (cell * FRAMES, cell), (255, 0, 255))
+ draw = ImageDraw.Draw(strip)
+ side = max(1, round(density ** 0.5))
+ for i in range(FRAMES):
+ x = i * cell + cell // 2 - side // 2 + (i - 1) * 3
+ y = cell // 2 - side // 2
+ draw.rectangle([x, y, x + side - 1, y + side - 1], fill=(40, 40, 120))
+ (run_dir / "raw").mkdir(exist_ok=True)
+ strip.save(run_dir / "raw" / "burst.png")
+ return run_dir
+
+
+def _extract(run_dir: Path, *flags: str):
+ return run_script("extract_sprite_row_frames.py", "--run-dir", str(run_dir), *flags)
+
+
+def _manifest(run_dir: Path) -> dict:
+ for name in ("frames/frames-manifest.json", "extract-failure.json"):
+ p = run_dir / name
+ if p.is_file():
+ return json.loads(p.read_text(encoding="utf-8"))
+ raise AssertionError("no extract output at all")
+
+
+def _request_for_cell(width: int, height: int, margin_x: int, margin_y: int) -> dict:
+ return {
+ "cell": {
+ "width": width,
+ "height": height,
+ "safe_margin_x": margin_x,
+ "safe_margin_y": margin_y,
+ }
+ }
+
+
+def test_profile_resolves_floor_and_rejects_unknown_kinds() -> None:
+ request = _request_for_cell(64, 64, 6, 6)
+ assert subject_kind(request) == "character"
+ assert cell_area(request) == 64 * 64
+ assert default_min_used_pixels(request) == 64
+ assert default_min_used_pixels({**request, "subject": "effect"}) == 32
+ with pytest.raises(SystemExit):
+ subject_kind({**request, "subject": "creature"})
+
+
+ ("width", "height", "margin_x", "margin_y", "character", "effect"),
+ [
+ (16, 16, 1, 1, 16, 8),
+ (32, 32, 2, 2, 32, 16),
+ (64, 64, 6, 6, 64, 32),
+ (128, 128, 12, 12, 128, 64),
+ (256, 256, 24, 24, 256, 128),
+ (512, 512, 48, 48, 512, 256),
+ (192, 208, 18, 19, 200, 100),
+ ],
+)
+def test_floor_scales_continuously_for_square_and_rect_cells(
+ width: int,
+ height: int,
+ margin_x: int,
+ margin_y: int,
+ character: int,
+ effect: int,
+) -> None:
+ request = _request_for_cell(width, height, margin_x, margin_y)
+ assert default_min_used_pixels(request) == character
+ assert default_min_used_pixels({**request, "subject": "effect"}) == effect
+ assert character in {effect * 2, effect * 2 - 1}
+
+
+def test_floor_rejects_invalid_cell_geometry() -> None:
+ with pytest.raises(SystemExit, match="positive"):
+ default_min_used_pixels(_request_for_cell(0, 64, 0, 0))
+
+
+def test_floor_is_monotone_across_every_square_size_from_16_to_512() -> None:
+ prior_character = 0
+ prior_effect = 0
+ for size in range(16, 513):
+ margin = int(size * 0.094)
+ request = _request_for_cell(size, size, margin, margin)
+ character = default_min_used_pixels(request)
+ effect = default_min_used_pixels({**request, "subject": "effect"})
+ assert character >= prior_character
+ assert effect >= prior_effect
+ assert character in {effect * 2, effect * 2 - 1}
+ prior_character = character
+ prior_effect = effect
+
+
+def test_floor_is_monotone_when_each_rect_axis_grows() -> None:
+ base = _request_for_cell(192, 208, 18, 19)
+ wider = _request_for_cell(193, 208, 18, 19)
+ taller = _request_for_cell(192, 209, 18, 19)
+ for subject in (None, "effect"):
+ def floor(request: dict) -> int:
+ return default_min_used_pixels(
+ request if subject is None else {**request, "subject": subject}
+ )
+
+ assert floor(wider) >= floor(base)
+ assert floor(taller) >= floor(base)
+
+
+def test_character_profile_rejects_a_sparse_effect_with_a_remedy(tmp_path: Path) -> None:
+ # 36px/frame lies between the 64px-cell profile floors: character 64,
+ # effect 32. The error names the way out.
+ run = _make_run(tmp_path / "run", 40, subject=None)
+ proc = _extract(run)
+ assert proc.returncode != 0
+ doc = _manifest(run)
+ assert doc.get("ok") is False or doc.get("states")
+ text = json.dumps(doc)
+ assert "character profile floor" in text
+ assert '\\"subject\\": \\"effect\\"' in text or '"subject": "effect"' in text.replace("\\", "")
+
+
+def test_effect_profile_passes_a_sparse_synthetic_effect(tmp_path: Path) -> None:
+ run = _make_run(tmp_path / "run", 40, subject="effect")
+ proc = _extract(run)
+ assert proc.returncode == 0, proc.stdout + proc.stderr
+ doc = _manifest(run)
+ assert doc["ok"] is True
+ px = [r["nontransparent_pixels"] for r in doc["rows"][0]["frame_records"]]
+ assert all(32 <= p < 64 for p in px)
+
+
+def test_effect_profile_still_catches_debris(tmp_path: Path) -> None:
+ # 16px/frame sits below the 64px-cell effect floor (32).
+ run = _make_run(tmp_path / "run", 20, subject="effect")
+ assert _extract(run).returncode != 0
+ assert "effect profile floor" in json.dumps(_manifest(run))
+
+
+def test_explicit_flag_beats_the_profile_and_is_stamped(tmp_path: Path) -> None:
+ run = _make_run(tmp_path / "run", 20, subject="effect")
+ proc = _extract(run, "--min-used-pixels", "12")
+ assert proc.returncode == 0, proc.stdout + proc.stderr
+ doc = _manifest(run)
+ # explicit flag is recorded for heal reproduction...
+ assert doc["extract_args"].get("min_used_pixels") == 12
+
+
+def test_profile_derived_floor_is_not_stamped_into_extract_args(tmp_path: Path) -> None:
+ # ...but a profile-derived floor is not: frames are a derived cache of
+ # (raw + request + engine), so heal must re-resolve from the request.
+ run = _make_run(tmp_path / "run", 40, subject="effect")
+ assert _extract(run).returncode == 0
+ assert "min_used_pixels" not in _manifest(run)["extract_args"]
+
+
+def test_compose_floor_follows_the_profile(tmp_path: Path) -> None:
+ run = _make_run(tmp_path / "run", 40, subject="effect")
+ assert _extract(run).returncode == 0
+ proc = run_script("compose_sprite_atlas.py", "--run-dir", str(run))
+ assert proc.returncode == 0, proc.stdout + proc.stderr
+ manifest = json.loads((run / "manifest.json").read_text(encoding="utf-8"))
+ assert manifest["frame_layout"]["rows"]["burst"]
+
+
+def test_prepare_writes_the_subject_field_only_when_declared(tmp_path: Path) -> None:
+ base = ["prepare_sprite_run.py", "--character-id", "profiled"]
+ plain = run_script(*base, "--out-dir", str(tmp_path / "plain"))
+ assert plain.returncode == 0, plain.stdout + plain.stderr
+ request = json.loads((tmp_path / "plain" / "sprite-request.json").read_text(encoding="utf-8"))
+ assert "subject" not in request # legacy shape untouched
+
+ flagged = run_script(*base, "--out-dir", str(tmp_path / "flagged"), "--subject", "effect")
+ assert flagged.returncode == 0, flagged.stdout + flagged.stderr
+ request = json.loads((tmp_path / "flagged" / "sprite-request.json").read_text(encoding="utf-8"))
+ assert request["subject"] == "effect"
+
+ via_json = run_script(*base, "--out-dir", str(tmp_path / "via-json"),
+ "--request-json", '{"subject": "effect"}')
+ assert via_json.returncode == 0, via_json.stdout + via_json.stderr
+ request = json.loads((tmp_path / "via-json" / "sprite-request.json").read_text(encoding="utf-8"))
+ assert request["subject"] == "effect"
+
+ bad = run_script(*base, "--out-dir", str(tmp_path / "bad"),
+ "--request-json", '{"subject": "creature"}')
+ assert bad.returncode != 0
+ assert "unknown subject kind" in bad.stderr