Skip to content

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

92.5 KB
Raw Blame
#!/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.effects import interpolate as interpolate_mod
from sprite_gen import gen as gen_mod
from sprite_gen.gen.base import PROVIDER_CODEX, PROVIDER_GROK
from sprite_gen.curate.curation import (CURATION_FILENAME, SCHEMA_VERSION, effective_logical_height,
                                 REF_ANCHOR, REF_BASIS, REF_GUIDE,
                                 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_FAILED, HEAL_HEALED, HEAL_KEPT_STALE, HEAL_NOTES, PROGRESS_REL,
                                       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 (LOCK_FILENAME, REQUEST_FILENAME, load_request, publish_guard,
                                   read_guard, write_request)
from sprite_gen.util.hexcolor import parse_hex
from sprite_gen._modules import qualified
from sprite_gen.util.console import utf8_streams

# 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",
}


class Wire:
    """The curator's wire: every key this server puts in a body (or header) the curator SPA
    (`curator/src/*.js`) reads, declared once. Each body is written through these names, and
    the server reads its own keys back through them; tests/serve/test_curator_wire_keys.py
    holds the SPA's read of each one. A key is declared under the first object it appears in.
    Keys other modules own arrive under their own names: the heal report and the progress
    file (`frames.extract`), the ref roles (`curate.curation`)."""

    # /api/run — the run snapshot
    CHARACTER_ID = "characterId"
    RUN_DIR = "runDir"
    BASE_URL = "baseUrl"
    CELL = "cell"
    PIXEL_UNFAKE = "pixelUnfake"
    SCHEMA_VERSION = "schemaVersion"
    RUN_REVISION = "runRevision"
    REQUEST_STAMP = "requestStamp"
    DIRECTION_GROUPS = "directionGroups"
    ANCHOR_FILES = "anchorFiles"
    STATES = "states"
    CURATION = "curation"
    CURATION_DROPPED = "curationDropped"
    ISO = "iso"
    LANG = "lang"
    HAS_ATLAS = "hasAtlas"
    ATLAS = "atlas"
    RECOLOR = "recolor"
    FIT_PIXEL_UNFAKE = "fitPixelUnfake"
    CONTRACT = "contract"
    HEAL = "heal"
    # cell
    WIDTH = "width"
    HEIGHT = "height"
    SAFE_MARGIN_X = "safeMarginX"
    SAFE_MARGIN_Y = "safeMarginY"
    # pixelUnfake
    LOGICAL_HEIGHT = "logicalHeight"
    SCALE = "scale"
    SOURCE = "source"
    LABEL = "label"
    # states[] — one row
    NAME = "name"
    RAW_PRESENT = "rawPresent"
    PIXEL_SCALE = "pixelScale"
    REFS = "refs"
    FPS = "fps"
    LOOP = "loop"
    ACTION = "action"
    REQUEST_FRAMES = "requestFrames"
    EXTRACT_OK = "extractOk"
    FRAMES = "frames"
    TAKES = "takes"
    # states[].frames[] — one frame
    INDEX = "index"
    URL = "url"
    PRESENT = "present"
    PLAIN_URL = "plainUrl"
    STAMP = "stamp"
    PLAIN_BAKE_URL = "plainBakeUrl"
    PLAIN_BAKE_STAMP = "plainBakeStamp"
    INPUT_GRID = "inputGrid"
    SIZE = "size"
    CONTENT_SIZE = "contentSize"
    CONTENT_BOX = "contentBox"
    # states[].refs[] — one generation-material chip
    ROLE = "role"
    ANCHOR_FRAME = "anchorFrame"
    # directionGroups[] — one direction, and its anchorFrame {state, index, source}
    DIRECTION = "direction"
    ANCHOR = "anchor"
    STATE = "state"
    ANCHOR_ERROR = "anchorError"
    ANCHOR_ERROR_CODE = "anchorErrorCode"
    ANCHOR_PENDING = "anchorPending"
    ANCHOR_URL = "anchorUrl"
    MIRROR_OF = "mirrorOf"
    # contract — the view's self-report
    BASE = "base"
    REFS_STATES = "refsStates"
    GRID = "grid"
    SOURCELESS = "sourceless"
    # atlas
    MTIME = "mtime"
    MANIFEST_URL = "manifestUrl"
    # recolor — the baked colourways, the thumbnail box (swatch) and each variant
    DIR = "dir"
    SWATCH = "swatch"
    MATCH = "match"
    TOLERANCE = "tolerance"
    VARIANTS = "variants"
    PICKED = "picked"
    PICKED_KNOWN = "pickedKnown"
    X = "x"
    Y = "y"
    W = "w"
    H = "h"
    SHEET_WIDTH = "sheetWidth"
    SHEET_HEIGHT = "sheetHeight"
    SHEET = "sheet"
    SUBSTITUTED_PIXELS = "substitutedPixels"
    PASSTHROUGH_PIXELS = "passthroughPixels"
    PASSTHROUGH_COLOR_COUNT = "passthroughColorCount"
    UNUSED_SOURCES = "unusedSources"
    # replies — an error, a busy run and its long-op progress
    ERROR = "error"
    PATH = "path"
    BUSY = "busy"
    PROGRESS = "progress"
    # /api/progress — states[]
    RAW = "raw"
    RAW_URL = "rawUrl"
    FRAME0_URL = "frame0Url"
    REL_RAW = "relRaw"
    REL_FRAMES = "relFrames"
    # /api/breathe-anatomy
    ANATOMY = "anatomy"
    DEFAULTS = "defaults"
    DEPTH = "depth"
    LAG = "lag"
    BREATHS = "breaths"
    # /api/base-grid
    NOTE = "note"
    X_EDGES = "xEdges"
    Y_EDGES = "yEdges"
    PITCH = "pitch"
    # POST results
    OK = "ok"
    RETURNCODE = "returncode"
    STDOUT = "stdout"
    STDERR = "stderr"
    EXPORT = "export"
    GIF = "gif"
    APPLIED = "applied"
    SPACE = "space"
    BACKUP = "backup"
    # downloads — the file name the browser saves under
    FILENAME_HEADER = "X-Filename"



# ── 픽셀 격자 자동 측정 ──────────────────────────────────────────────
# 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 / REQUEST_FILENAME),
                            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)
    from sprite_gen.frames.cutout import KEY_TARGETS, MAGENTA
    chroma = tuple(request.get("chroma_key", {}).get("rgb") or KEY_TARGETS[MAGENTA])
    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 = {Wire.GRID: None, Wire.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 = {Wire.GRID: None, Wire.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 = {Wire.GRID: {Wire.X_EDGES: x_edges, Wire.Y_EDGES: y_edges,
                               Wire.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 {
        Wire.ANCHOR_FRAME: ({Wire.STATE: view["state"], Wire.INDEX: view["index"], Wire.SOURCE: view["source"]}
                        if view.get("state") is not None else None),
        Wire.ANCHOR_ERROR: view.get("error"),
        Wire.ANCHOR_ERROR_CODE: view.get("code"),
        Wire.ANCHOR_PENDING: bool(view.get("pending")),
        Wire.ANCHOR_URL: 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({Wire.ROLE: REF_ANCHOR,
                             Wire.NAME: f"{view['state']}#{view['index']}"
                                     f"{' · picked' if view.get('source') == 'picked' else ''}",
                             Wire.URL: view["url"], Wire.ANCHOR_FRAME: True})
            elif anchor.is_file():
                # 앵커 행이 아직 큐레이션/추출 전 — 실재하는 raw 스트립을 그대로 보여준다
                refs.append({Wire.ROLE: REF_ANCHOR, Wire.NAME: anchor.name, Wire.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({Wire.ROLE: REF_BASIS, Wire.NAME: basis.name, Wire.URL: _url("run", *basis_rel.split("/"))})
    guide = run_dir / "references" / "layout-guides" / f"{state}.png"
    if guide.is_file():
        refs.append({Wire.ROLE: REF_GUIDE, Wire.NAME: guide.name, Wire.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({Wire.ROLE: role, Wire.NAME: ref.name,
                         Wire.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 / PROGRESS_REL).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 = {
        Wire.WIDTH: int(cell.get("width", cell.get("size", 0))),
        Wire.HEIGHT: int(cell.get("height", cell.get("size", 0))),
        # 안전영역/여백 알림 계산용 (여백 침범 = 정보성, 리롤 대상 아님)
        Wire.SAFE_MARGIN_X: int(cell.get("safe_margin_x", cell.get("safe_margin", 0))),
        Wire.SAFE_MARGIN_Y: 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[Wire.HEIGHT]
        pixel_unfake = {Wire.LOGICAL_HEIGHT: logical_height, Wire.SCALE: scale, Wire.SOURCE: "request", Wire.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 = {Wire.INDEX: index, Wire.URL: _url(*rel.split("/")), Wire.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[Wire.PLAIN_URL] = _url(*orig_rel.split("/"))
            elif (run_dir / plain_rel).is_file():
                frame[Wire.PLAIN_URL] = _url(*plain_rel.split("/"))
            # **굽기가 실제로 읽는 파일** — `row_frame_rel(row, i, "plain")` 과 같은 경로다.
            # 위 `plainUrl` 은 표시 화질용이라 `orig/` 고해상본을 우선하는데, 굽기는 그걸
            # 절대 안 읽는다. 호흡 프리뷰·신선도 판정이 `plainUrl` 을 쓰면 지문이 **영구
            # 불일치**라 그 줄의 영상 내보내기가 영구 차단된다 (validator 2026-07-26).
            if present:
                frame[Wire.STAMP] = _file_stamp(run_dir / rel)
            if (run_dir / plain_rel).is_file():
                frame[Wire.PLAIN_BAKE_URL] = _url(*plain_rel.split("/"))
                # URL 과 **짝으로** 나간다. 굽기가 읽는 파일이 곧 호흡 기준 프레임 키의
                # 원본 조각이라, 둘 중 하나만 보내면 웹뷰가 키를 못 만든다.
                frame[Wire.PLAIN_BAKE_STAMP] = _file_stamp(run_dir / plain_rel)
            # 트윈 없는 프레임의 퍼펙은 클라 렌더러가 측정 k(pixelScale)로 양자화한다
            # — 서버 추정 스냅 프리뷰 레거시는 표시 격자와 다른 검출기(엔진 주기성,
            # 1:1 에 4.99)로 스냅해 같은 줄의 프레임마다 다른 진실을 만들었다
            # (validator R1 기각, plan curator-single-display-pipeline 에서 삭제).
            if index < len(labels):
                frame[Wire.LABEL] = labels[index]
            # 추출이 검출한 실제 절단선 (쌍둥이 셀 좌표) — 원본 화질 뷰의 최종 대응
            # 격자가 균등 분할 대신 이 선을 그린다 (중간 드리프트 제거)
            row_grids = row.get("input_grids") or []
            if index < len(row_grids) and row_grids[index]:
                frame[Wire.INPUT_GRID] = row_grids[index]
            if present and Image is not None:
                # 실제 스프라이트 픽셀 크기(투명 패딩 제외 알파 bbox) — 사이즈 통일 검수용
                try:
                    with Image.open(run_dir / rel) as im:
                        frame[Wire.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[Wire.CONTENT_SIZE] = [bbox[2] - bbox[0], bbox[3] - bbox[1]]
                            # 최종 픽셀 콘텐츠 bbox(셀 좌표) — 원본 뷰의 "최종 대응 격자"
                            # (칸 수 = 최종 픽셀 수)가 이 상자를 균등 분할해 그린다
                            frame[Wire.CONTENT_BOX] = list(bbox)
                except OSError:
                    pass
            frames.append(frame)
        state_scale = None
        if pixel_unfake is not None:
            state_scale = pixel_unfake[Wire.SCALE]
        else:
            for fr in frames:
                if fr.get(Wire.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[Wire.INDEX]] if fr[Wire.INDEX] < len(row_files_m) else f"{state_frames_rel}/frame-{fr[Wire.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(
            {
                Wire.NAME: state,
                Wire.RAW_PRESENT: raw_present,
                Wire.PIXEL_SCALE: state_scale,
                Wire.REFS: _state_refs(run_dir, state, request, anchor_views),
                Wire.FPS: int(entry.get("fps", 6)),
                Wire.LOOP: bool(entry.get("loop", True)),
                Wire.ACTION: entry.get("action", ""),
                Wire.REQUEST_FRAMES: frame_count,
                Wire.EXTRACT_OK: bool(row.get("ok", bool(files))),
                Wire.FRAMES: frames,
                # 테이크 선언 (호흡 에디터가 저장된 선/진폭을 복원하는 데 쓴다)
                Wire.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({
                Wire.DIRECTION: direction,
                Wire.ANCHOR: anchor if anchor in request["states"] else None,
                Wire.STATES: members,
                **_anchor_group_fields(anchor_views.get(direction) or {}),
            })
        for target, source in (directions_cfg.get("mirror") or {}).items():
            direction_groups.append({Wire.DIRECTION: target, Wire.MIRROR_OF: source, Wire.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({Wire.NAME: path.name, Wire.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(Wire.REFS))
    # 격자는 언제나 있다 — `detect_pixel_pitch` 가 실패할 수 없는 정확 판정이라
    # 모든 상태가 ≥1 의 scale 을 갖는다. 조건부 False 는 곧 컨트롤 숨김이었고
    # 그게 버그였다 (maintainer 2026-07-24).
    has_grid = True
    contract = {
        Wire.BASE: has_base,
        Wire.REFS: refs_states > 0,
        Wire.REFS_STATES: refs_states,
        Wire.GRID: has_grid,
        # 격자가 보편이 된 뒤로는 판별자가 못 된다 — 항상 참인 항을 or 에 두면
        # sourceless 가 영원히 False 라 경고가 죽는다. 남은 판별자(base/refs)로만 본다.
        Wire.SOURCELESS: not (has_base or refs_states > 0),
    }
    return {
        Wire.CHARACTER_ID: request["character"]["id"],
        Wire.RUN_DIR: str(run_dir),
        Wire.BASE_URL: base_url,
        Wire.CELL: cell_state,
        # 계약 scale(pp 런)이 없으면 줄별 실측이 진실이다 — null 로 접지 않는다.
        Wire.PIXEL_UNFAKE: pixel_unfake if pixel_unfake is not None else {
            Wire.SOURCE: "auto", Wire.LABEL: "auto",
            Wire.SCALE: min((st[Wire.PIXEL_SCALE] for st in states if st.get(Wire.PIXEL_SCALE)), default=1)},
        Wire.SCHEMA_VERSION: SCHEMA_VERSION,
        Wire.RUN_REVISION: revision,
        # 호흡 기준 프레임 키의 조각 — 셀 크기·`pixel_snap_scale` 같은 request 파생값을
        # 웹뷰가 재구현하지 않고 원인 하나로 덮는다 (`breathe.reference_key` 주석).
        Wire.REQUEST_STAMP: _file_stamp(run_dir / REQUEST_FILENAME),
        Wire.DIRECTION_GROUPS: direction_groups,
        Wire.ANCHOR_FILES: anchor_files,
        Wire.STATES: states,
        Wire.CURATION: curation,
        # 세대 불일치로 이번 로드에서 무효화(드롭)된 행 — 뷰가 배너로 알린다 (stderr 만으로는
        # 사용자가 못 본다; 조용한 소실 금지). 백업 파일명은 싣지 않는다: 로드는 아무것도
        # 쓰지 않고, 원문은 덮이는 순간 writer 가 백업한다 (`write_curation_atomic`).
        Wire.CURATION_DROPPED: curation_report["dropped"],
        Wire.ISO: request.get("iso"),
        Wire.LANG: CurationHandler.lang,
        Wire.HAS_ATLAS: (run_dir / "sprite-sheet-alpha.png").is_file(),
        # 최종 산출물 섹션 (뷰 맨 아래, 아틀라스+manifest 좌우) — 파일이 실재할 때만.
        # 아틀라스는 다운로드/합성 시점 산출물이라 mtime 을 실어 시점을 표시한다.
        Wire.ATLAS: _atlas_info(run_dir),
        # 팔레트 스왑 베이크 산출물 (`<run>/variants/`) — 없으면 None (섹션 자체가 안 뜬다).
        Wire.RECOLOR: _recolor_info(run_dir, curation),
        Wire.FIT_PIXEL_UNFAKE: bool((request.get("fit") or {}).get("pixel_unfake")),
        # 예산에 밀려 아직 못 만든 온디맨드 픽셀 프리뷰 수 — 0 이 아니면 리로드가 이어서 계산
        Wire.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 {
                    Wire.X: int(cell["x"]), Wire.Y: int(cell["y"]),
                    Wire.W: int(cell["w"]), Wire.H: int(cell["h"]),
                    Wire.SHEET_WIDTH: int(layout["sheetWidth"]),
                    Wire.SHEET_HEIGHT: 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({
            Wire.NAME: entry.get("name"),
            Wire.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.
            Wire.URL: (_url("run", VARIANTS_DIRNAME, sheet) + f"?v={int(path.stat().st_mtime)}") if present else None,
            Wire.PRESENT: present,
            Wire.SUBSTITUTED_PIXELS: entry.get("substituted_pixels"),
            Wire.PASSTHROUGH_PIXELS: entry.get("passthrough_pixels"),
            Wire.PASSTHROUGH_COLOR_COUNT: entry.get("passthrough_color_count"),
            Wire.UNUSED_SOURCES: [record.get("from") for record in entry.get("unused_sources", [])],
            Wire.MANIFEST_URL: (_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 {
        Wire.DIR: VARIANTS_DIRNAME,
        # 썸네일이 잘라 볼 프레임 상자 (없으면 시트 전체를 보여준다 — _first_frame_rect 참조)
        Wire.SWATCH: _first_frame_rect(run_dir),
        Wire.MATCH: report.get("match"),
        Wire.TOLERANCE: report.get("tolerance"),
        Wire.BASE: {
            Wire.NAME: base_name,
            Wire.URL: (_url("run", base_name) + f"?v={int(base_path.stat().st_mtime)}") if base_present else None,
            Wire.PRESENT: base_present,
        },
        Wire.VARIANTS: variants,
        Wire.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.
        Wire.PICKED_KNOWN: picked is not None and any(v[Wire.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 {
        Wire.URL: _url("run", "sprite-sheet-alpha.png") + f"?v={mtime}",
        Wire.MTIME: mtime,
        Wire.MANIFEST_URL: (_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 / REQUEST_FILENAME, run_dir / CURATION_FILENAME,
             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 {HEAL_HEALED: [], HEAL_KEPT_STALE: [], HEAL_FAILED: failed,
            HEAL_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 = {HEAL_HEALED: [], HEAL_KEPT_STALE: [], HEAL_FAILED: [],
                  HEAL_NOTES: [f"heal skipped: {exc}"]}
    with _heal_lock:
        if report[HEAL_HEALED] or report[HEAL_KEPT_STALE] or report.get(HEAL_FAILED) or report[HEAL_NOTES]:
            _heal_state["pending_report"] = report
        if report.get(HEAL_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[Wire.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[Wire.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[Wire.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[Wire.OK]:
            return result
        gif_path = run_dir / "exports" / f"{state}.gif"
        if not gif_path.is_file():
            return {Wire.OK: False, Wire.ERROR: f"gif not produced: {gif_path}"}
        return gif_path.read_bytes(), f"{character}-{state}.gif"
    return {Wire.OK: False, Wire.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 {
        Wire.OK: proc.returncode == 0,
        Wire.RETURNCODE: proc.returncode,
        Wire.STDOUT: proc.stdout,
        Wire.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)


# The providers the curator's reroll and in-between buttons run, in the order its select offers them
# (gen-trigger.js GEN_PROVIDERS mirrors it). The curator's own set: the reroll CLI takes every gen provider,
# and capabilities.PROVIDER_CALLS["curation"] counts on openai not being here.
CURATOR_PROVIDERS = (PROVIDER_CODEX, PROVIDER_GROK)


def run_interpolate(run_dir: Path, state: str, index_a: int, index_b: int,
                    t: float, label: str | None, provider: str = interpolate_mod.DEFAULT_PROVIDER) -> 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 = gen_mod.HARD_DEFAULT_PROVIDER) -> 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[Wire.OK] and result[Wire.STDOUT]:
        try:
            result[Wire.EXPORT] = json.loads(result[Wire.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[Wire.OK] and result[Wire.STDOUT]:
        try:
            result[Wire.GIF] = json.loads(result[Wire.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({Wire.ERROR: "not found", Wire.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({
                        Wire.ERROR: "re-extraction in progress — frames are being "
                                 "re-derived for the current engine; the view opens "
                                 "automatically when it finishes",
                        Wire.BUSY: True, Wire.LANG: CurationHandler.lang,
                        Wire.PROGRESS: _read_op_progress(self.run_dir)}, 503)
                    return
                snapshot = build_run_state(self.run_dir)
                heal = take_heal_report()  # 스냅샷 성공 뒤에만 소비 (단일 소비자)
                if heal:
                    snapshot[Wire.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 / LOCK_FILENAME).exists():
                    self._send_json({Wire.ERROR: "re-extraction in progress — "
                                     "the run is being re-derived; reload when it finishes",
                                     Wire.BUSY: True, Wire.PROGRESS: _read_op_progress(self.run_dir)}, 503)
                else:
                    self._send_json({Wire.ERROR: str(exc)}, 500)
            return
        if path == "/api/op-progress":
            # 오래 걸리는 파이프라인(추출 등)의 잘게 쪼갠 진행도 — 큐레이터가 폴링해
            # 퍼센트 표시 (maintainer 요청 2026-07-18). busy=락 보유 여부, progress=엔진 기록.
            self._send_json({
                Wire.BUSY: (self.run_dir / LOCK_FILENAME).exists(),
                Wire.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({Wire.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({Wire.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({Wire.ERROR: f"no extracted frame for state {state!r}"}, 404)
                    return
                frozen = freeze_anatomy(frame, overrides, key)
                self._send_json({Wire.ANATOMY: frozen, Wire.DEFAULTS: {
                    Wire.DEPTH: DEFAULT_DEPTH, Wire.LAG: DEFAULT_LAG, Wire.BREATHS: 1}})
            except (Exception, SystemExit) as exc:
                self._send_json({Wire.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({Wire.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({Wire.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({
                        Wire.ERROR: "re-extraction in progress — retry the download "
                                 "when it finishes",
                        Wire.BUSY: True,
                        Wire.PROGRESS: _read_op_progress(self.run_dir)}, 503)
                    return
                built = build_download(self.run_dir, kind)
            except (Exception, SystemExit) as exc:
                self._send_json({Wire.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(Wire.FILENAME_HEADER, 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({Wire.BUSY: True,
                                     Wire.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({
                            Wire.NAME: state,
                            Wire.RAW: (self.run_dir / state_raw).is_file(),
                            Wire.FRAMES: count,
                            # 트리 썸네일용 실제 경로 URL (클라이언트 패턴 조립 금지)
                            Wire.RAW_URL: _url("run", *state_raw.split("/")),
                            Wire.FRAME0_URL: _url(*f"{state_frames}/frame-0.png".split("/")),
                            Wire.REL_RAW: state_raw,
                            Wire.REL_FRAMES: state_frames,
                        })
                    self._send_json({Wire.STATES: progress, Wire.RUN_REVISION: run_revision(self.run_dir)})
            except (Exception, SystemExit) as exc:
                self._send_json({Wire.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({Wire.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({Wire.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({Wire.ERROR: "path escapes curator dir"}, 403)
            return
        if asset.is_file():
            self._send_file(asset)
            return
        self._send_json({Wire.ERROR: "not found", Wire.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(Wire.RUN_REVISION) != 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({Wire.ERROR: "curation is from a different run generation "
                                     "(the run changed under this session; reload the view)"}, 409)
                else:
                    self._send_json({Wire.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({Wire.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({Wire.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({Wire.ERROR: "format: gif|webm|mp4"}, 400)
                    return
                if fmt != "gif" and shutil.which("ffmpeg") is None:
                    self._send_json({Wire.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({Wire.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(Wire.FILENAME_HEADER, 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[Wire.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({Wire.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({Wire.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(Wire.GRID)
                    if not grid:
                        self._send_json({Wire.ERROR: "logical ops need a detected base grid"}, 422)
                        return
                elif space != "raw":
                    self._send_json({Wire.ERROR: f"unknown ops space: {space}"}, 400)
                    return
                request = load_request(self.run_dir)
                from sprite_gen.frames.cutout import KEY_TARGETS, MAGENTA
                chroma = tuple(request.get("chroma_key", {}).get("rgb") or KEY_TARGETS[MAGENTA])
                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:
                        try:
                            fill = parse_hex(str(value)) + (255,)
                        except ValueError:
                            continue
                    else:
                        fill = chroma + (255,)  # 지우개 = 크로마 배경 복원
                    if grid is not None:
                        xe, ye = grid[Wire.X_EDGES], grid[Wire.Y_EDGES]
                        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[Wire.PITCH][0]
                        tnorm["dy"] = tnorm.get("dy", 0.0) * grid[Wire.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({Wire.OK: True, Wire.APPLIED: applied, Wire.SPACE: space,
                                 Wire.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({Wire.ERROR: "fps:int required"}, 400)
                    return
                if not 1 <= fps <= 30:
                    self._send_json({Wire.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({Wire.ERROR: f"unknown state: {state}"}, 400)
                        return
                    request["states"][state]["fps"] = fps
                    # 쓰기도 게이트 경유 — fps 편집이 디스크 스키마를 바꾸지 않는다.
                    write_request(self.run_dir, request)
                self._send_json({Wire.OK: True, Wire.STATE: state, Wire.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({Wire.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(
                        {Wire.ERROR: "body needs integer 'from'/'to' (+ optional float 't')"}, 400)
                    return
                if not 0.0 < t_value < 1.0:
                    self._send_json({Wire.ERROR: f"t must be inside (0, 1): {t_value}"}, 400)
                    return
                provider = str(payload.get("provider") or interpolate_mod.DEFAULT_PROVIDER)
                if provider not in CURATOR_PROVIDERS:
                    self._send_json({Wire.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[Wire.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({Wire.ERROR: f"unknown state: {state}"}, 400)
                    return
                provider = str(payload.get("provider") or gen_mod.HARD_DEFAULT_PROVIDER)
                if provider not in CURATOR_PROVIDERS:
                    self._send_json({Wire.ERROR: f"unknown provider: {provider}"}, 400)
                    return
                result = run_reroll(self.run_dir, state, provider)
                self._send_json(result, 200 if result[Wire.OK] else 500)
                return
            if path == "/api/export":
                result = run_export(self.run_dir)
                self._send_json(result, 200 if result[Wire.OK] else 500)
                return
            if path == "/api/export-gif":
                result = run_export_gif(self.run_dir)
                self._send_json(result, 200 if result[Wire.OK] else 500)
                return
        except Exception as exc:
            self._send_json({Wire.ERROR: str(exc)}, 500)
            return
        self._send_json({Wire.ERROR: "not found", Wire.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 / REQUEST_FILENAME).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(Wire.CONTRACT, {})
        n_states = len(snapshot.get(Wire.STATES, []))
        print(f"  view-contract: base={'yes' if c.get(Wire.BASE) else 'no'} · "
              f"refs={c.get(Wire.REFS_STATES, 0)}/{n_states} states · "
              f"grid={'yes' if c.get(Wire.GRID) else 'no'}")
        if c.get(Wire.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."""
    utf8_streams()
    parser = argparse.ArgumentParser(description=__doc__)
    add_arguments(parser)
    return run(**vars(parser.parse_args(argv)))


if __name__ == "__main__":
    raise SystemExit(main())