Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.
Merge plan/decontam-palette-default-1021 (video-frames and video-set default to --decontam auto; the video fit holds an edge pixel's calls from frame to frame, blends a change of call over frames and settles a still edge; one warning line says what auto did not do) into main, validated in sprite-gen/decontam-palette-default-1021
Soohong Kim3dbd35747d96
diff --cc CHANGELOG.mdindex 290ee9f,1a24e34..f1a6d3f--- a/CHANGELOG.md+++ b/CHANGELOG.md@@@ -4,244 -4,229 +4,467 @@@ All notable public changes to `sprite-g## Unreleased+**Upgrading from 3.0.0: Bakes retain the same bytes for figures whose anatomy is unchanged. The `pixel` refusal message now names the sides and pixel counts. A figure that had `face-absent` may now have a face, with a lower rigid boundary only when that face ends below the neck. `video-sway-inspect` records use schema 3, and a cell whose every offset is 0 is now copied as it was, including colour under clear pixels with `--gain 0`; the other changes add options, and without them the strip, records and inspection stay as before.**++The Breathe layer still supports `pixel` and `smooth`.++- **Changed: Pixel refusal.** `pixel` still refuses stretched content past the top, left, or right of a cell instead of cropping it.+ The message names each side and its opaque pixel count. A pixel past a corner counts on both sides.+ When an overflowing side is the drawing's own border, the message also gives the number of pixels covering that edge.+ It advises `--mode smooth` or sidecar `mode: "smooth"` for an illustration cut by its frame.+ It advises a wider cell margin or lower `depth` for a pixel sprite.+ It warns that padding, baking, and cropping back silently loses pushed off content.+ The curator preview uses the same refusal wording.+ The border reading follows the 2% rule in [video pipeline](docs/video-pipeline.md) section 3.+ See [breathing](docs/breathing.md) for behavior at frame edges.+- **New: Second eye pair search.** It runs only when the existing search finds no pair.+ Its minimum eye area is 0.2% of opaque pixels above the neck.+ Its eye width to height limit is 3.0, and its minimum eye center distance from the body axis is 0.02 of content width.+ Pair placement, separation, size similarity, and row overlap conditions remain the same.+ A face found by this search clears `face-absent`. It lowers the boundary only if the face ends below the neck.+- **Faster: Breathe bakes.** Array operations speed up pixel outline thinning, appendage weights, and row mapping.+ `smooth` solves displacement only for pixels that move.+ Anatomy and settings checks run once per row, and `sprite-gen breathe` shares one anatomy measurement between its report and bake.+ On synthetic 960 x 960 cells with Apple M1, bake time fell from 0.20 s to 0.10 s for `smooth`.+ For an outlined figure with arms in `pixel`, it fell from 0.98 s to 0.05 s.+ These measurements exclude PNG reading and writing.+ `bake_breathe_sequence(images, cfg, anat=None)` and `anatomy_report(images, cfg, anat=None)` accept measured anatomy.+ `protect(anat)` accepts one column or an array of columns.+- **New: Sway on a cycle's frames.** `video-sway --frames` moves full-size frames and writes them with `sway.json` to a new folder.+ A whole `cycle/` can supply its frame time; other damped-mass runs require `--fps`.+- **New: Sway on the breath.** `--breathe` drives the move from a checked smooth `breathe.json`, with `--lag` setting how late the part follows.+ The first cell, rests and close have zero offset.+- **New: A region moved whole.** A fifth `--region` number, `flat`, keeps the centre at full weight before the weight falls to the rim.+- **New: Across apart from down.** `--gain-across` sets the across gain separately from `--gain`, which sets the gain down.+- **Changed: Zero-offset cells.** A cell where no region moves is copied byte for byte, including colour under clear pixels.+- **Changed: Inspection seams.** `video-sway-inspect` drops a pair's seam points covered by a third moving region.+ Its record uses `schema_version` 3.+- **New: Breathe beat chosen to miss the hands.** In `smooth` mode, `--avoid-region` chooses a breath beat whose peaks keep the chest above the hands' own rise and records the choice in `breathe.json`.+- **Tests:** `tests/effects/test_breathe.py` checks border counts, advice, smooth edge preservation, and the second face search.+ `tests/effects/test_breathe_js_mirror.py` checks curator refusal wording and byte identity with the pixel bake.+ `tests/effects/test_breathe_smooth.py` checks pixel and smooth byte goldens and shared anatomy and strain measurements.+ `tests/effects/test_breathe_publish.py` checks that the stand-in bake accepts the new argument.+ `tests/video/test_sway_frames.py`, `tests/video/test_sway_breath.py`, `tests/video/test_sway_flat_across.py`, and `tests/video/test_sway_seams.py` check the Sway paths, drives, weights, gains and seams.+ `tests/effects/test_breath_beat.py` checks beat choice and refusals.+ `tests/video/test_follow_stretch_floor.py` and `tests/video/test_follow_inspect.py` cover the changed inspection schema and frames options.++- **Tests**: A plain `pytest` runs a fast bundle: tests marked `slow` are deselected, the header points to `pytest --full`, and the summary counts deselections. `pytest --full` runs every test. The release lane, `scripts/linux_lane.sh`, passes `--full` to both `pytest` calls, including `-m real_rife`, so its gate still runs every test. `tests/release/test_fast_bundle.py` checks both calls and probes selection with and without `--full`. The `slow` rule in `pyproject.toml` is 1 s per case or 5 s across a function's cases on an 8-core M1 running the whole suite; marking a function marks every case. Five tests remain unmarked as the only fast callers of `video-stop`, `workflow`, `defaults`, `video-sway`, and `export-aseprite`. Three fixture-first tests remain unmarked because other fast tests build their fixtures. In `tests/frames/test_ui_kit.py`, the fast bundle keeps 16 of 512 scattered-drawing grid seeds, 8 of 256 full-size-frame band grid seeds, 9 of 256 missing-element sets, 2 of 17 counterexample sheets, and one placement and start in each publish sweep. `tests/curate/test_anchor_selection.py` extracts each run once per module instead of repeating 1.5 to 2.6 s of setup per test; 25 of 27 affected tests are now fast. Removed `tests/video/test_loop_overlap.py::test_a_tail_on_its_own_beat_is_closed_at_the_wrap_with_the_clips_frames_a_cycle_apart[on]`; its wordless case makes the same call with the default "on". Removed `tests/video/test_walk_steps.py::test_cycle_align_takes_a_loop_cut_two_steps_as_one_cycle` and `tests/video/test_one_step_cut.py::test_cycle_align_takes_the_loop_cut_again_on_its_count`; `tests/video/test_loop_prop_seam_held.py::test_cycle_align_aligns_a_two_step_loop_as_the_one_cycle_it_is` covers alignment from recorded `steps: 2`. Merged `tests/video/test_loop_overlap.py::test_the_cli_passes_overlap_wrap_off_and_on_is_its_default` into `tests/video/test_loop_overlap.py::test_with_the_overlapped_wrap_off_nothing_is_read_for_the_wrap_and_the_gate_refuses_the_cut_as_filmed`, retaining both sets of assertions on one CLI cut with `--overlap-wrap off`. In a new virtual environment, the former suite ran 7,881 tests (7,880 passed, 1 skipped) in 21 minutes 54 seconds; `pytest --full` now runs 7,881, including two new release tests, and the fast bundle runs 6,555 in about 6 minutes. Package code, commands, and outputs are unchanged.++**Upgrading from 3.0.0: the `sprite-gen logo` text checks read a refused image once more before refusing it, and on codex they read on a fixed model and effort.** A mood or logo reading of `mismatch` or `no-text` is read again, up to `logo.MAX_READS` readings, which is 2. One reading that spells the asked text passes. An image is refused only when every reading differs. A logo now costs four to six calls: two images and two text checks, each read once or twice. Beyond a check's second reading nothing is sent again on its own. On codex the text checks no longer follow the login's `~/.codex/config.toml`. They read on `gpt-6-sol` at reasoning effort `high`, and the report names the model and effort of every reading. **`sprite-gen logo` refuses a chroma key that is one of the title's own colours, and a cut that is see-through inside its letters.** A letter colour in the key's hue is, by its pixels, a mix with the key, so the matte cuts it see-through. `--chroma-key auto` now skips a key whose hue covers 5 % or more of the title's box in the mood image, or 1 % when the brief names a colour in that hue. When both keys are the title's colours, the run is refused at the new step `key` before the lettering image is bought. After the matte, see-through pixels walled in by the lettering, farther from it than the logo's own glow reaches, refuse the logo at `matte` on 1 % of the visible lettering or more. A run that went through before with a key in the title's hue, or with a see-through cut inside its letters, is now refused at `key` or at `matte` instead of passing with `status: ok`. Runs whose title carries neither key's hue pick the same key as before.++- **A misreading is read once more before it refuses an image.** Before, each check read the image once, and one misreading refused it. A model reading stylised lettering can read the same picture two ways, so a correctly drawn title could be refused on one reading. Both checks use the one rule, `logo.read_text`. A call that fails is not asked again. With no reading before it, the check is `unverified` as before. With a misreading before it, the misreading stands and the image is refused. A refusal message names every reading, for example `the mood image reads ['IO'] and then ['I0'], not ['ION']`. docs/logo.md records a measurement on a synthetic pixel title drawn one stroke short (the Hangul syllable 쿠 drawn as 구, the middle bar of ㅋ left out). The codex reader at gpt-6-sol/high read it as 구 in 10 readings of 10 and never as 쿠, so neither one reading nor a check of two readings (0 of 5) passed the wrong picture. A second reading can only pass a wrong picture if the reader writes a stroke that is not drawn.+- `logo.report.json`: `text_check.mood` and `text_check.logo` keep the deciding reading's `verdict` and `read` and gain `max_reads` and `readings`, each reading in order with its `reading` number, `verdict` and `read` lines, or `reason` when it could not be read. `calls` lists a check's call once per reading, each with `reading` (1 or 2) and `effort` (`null` where the provider names none).+- Codex reader: the text checks run `codex exec --model gpt-6-sol -c model_reasoning_effort="high"`, named on each call, so a check's verdict does not change with the machine it runs on. Before, each machine read on its own config and the report recorded `model: null`. The values are `facing_vision.CODEX_READ_MODEL` and `facing_vision.CODEX_READ_EFFORT`. `--model` still names the images' model only. The facing check still runs on the login's config, unchanged. The xAI and OpenAI text checks read on their own fixed models, as before.+- Python callers: `logo.read_text` returns `(check, calls)`, a list of call records, instead of `(check, call)`. `facing_vision.codex_inspect` takes optional `model` and `effort` keyword arguments. Without them its command line is as before.+- **With `--chroma-key auto`, a key in the title's hue is not chosen.** `logo_matte.choose_key` rules out a key whose hue is 5 % or more of the title's box (`logo_matte.CLASH_HUED_PCT`), or 1 % (`logo_matte.NAMED_CLASH_HUED_PCT`) when `--style` or `--scene` names a colour in its hue (`logo.KEY_COLOUR_WORDS`: green, mint, lime, emerald, jade, chartreuse for green; magenta, fuchsia, pink, purple, violet, plum, orchid for magenta). A word alone never rules a key out; the pixels decide. The keys left are scored as before. When both keys are the title's colours there is no third: the run is refused at `key` (`refused_at: key`) before the lettering image is bought. The message gives each key's share and the brief's words for it and says to restyle the title without one of the two hues or to name the key to lose with `--chroma-key` (`--mood <mood.png>` skips the mood image). An explicit `--chroma-key` is kept; when it is one of the title's colours, a warning says so. Before, such a cut passed with `status: ok`, no warning, `key_hue_left` 0 and a matching text check.+- **A cut that is see-through inside its letters is refused at `matte`.** `logo_matte.see_through_inside` measures see-through pixels (coverage under 240 of 255) walled in by opaque lettering and farther from it than the logo's own glow reaches beside it. Walled in means no way out to the picture's edge except across opaque pixels: the way out starts from the transparent pixels on the edge of the trimmed logo and runs through transparent pixels and see-through ones; a see-through gap of 2 px or narrower does not count as a way, a transparent gap of any width does. A hole joined to the outside, even through one pixel, is outside; a transparent hole walled in by the letters (an O's counter, or a letter colour cut all the way to nothing) is no way out, and a see-through patch round such a hole is still counted inside. Transparent pixels are never counted, only see-through ones. The same way out decides the glow's reach (`glow_reach_px`): the 99th percentile of how far the see-through pixels that have a way out to the picture's edge lie from the opaque lettering, and at least 2 px. On 1 % of the visible lettering or more (`logo_matte.INSIDE_MAX_PCT`) the logo is refused before its text is read, the cut is kept as `logo.rejected.png` and the preview is written. The message says to generate the lettering again on the other key or to restyle the title without that colour. Only the logo matte's own cut (`method: logo-unmix`) is refused; a lettering image returned with its own alpha is measured, not refused. A glow fades out beside the letters and pools in a counter no farther than it reaches there, so glows are not counted.+- `logo.report.json`: `steps.key.scores.<key>` gains `named`, `clash_at_pct` and `clashes`, and `steps.key.key` is `null` when refused at `key`. `logo` gains `see_through_inside` with `px`, `pct_of_visible`, `glow_reach_px`, `max_pct` and `wide`. `refused_at` can now be `key`.+- Python callers: `logo_matte.choose_key(mood, box=None, named=None)` takes `named`, the brief's colour words per key from `logo.named_colours(style, scene)`, and returns `key: None` when both keys are the title's colours. `logo_matte.see_through_inside(image)` is new.+- **Tests**: `tests/gen/test_logo.py` checks that one matching reading is the whole check, that a misreading read again as asked passes at either check, that two misreadings refuse the mood image and refuse the logo and keep it aside with a refusal naming both, that a check reads no more than `MAX_READS` (set to 3, a third reading is taken), that a failed call is not asked again, that a misreading stands when the second call failed, and that the report names the reader model and effort of every reading. The existing refusal tests now script two misreadings. `tests/gen/test_vision_read.py` checks that codex reads on the named model and effort, passed before the image list, that docs/logo.md names both values, and that the facing check's command carries neither. `tests/frames/test_logo_matte.py` checks that a title in both keys' hues (synthetic patchwork letters: pink and plum in magenta's hue, mint in green's) gets neither key, that a colour in a key's hue rules the key out, that a colour the brief names rules it out at the smaller share while the same share unnamed and the word with no such pixels do not, that on green the mint patches are cut see-through and found inside (9.5 % of the visible lettering) while the other key keeps them and finds nothing, that six glow fixtures (a white glow, an outlined cyan glow, a cyan glow pooled in an O's counter on green and on magenta, an orange glow on green, pixel lettering) find nothing inside, that a mint patch walled in by a navy letter on green is still found inside, with the glow's reach at 2 px, when one or four squares of the key in it are cut to nothing, that a hole glued to the letter's edge is inside while sealed and outside once one pixel joins it to the key round the letter, and that big hollow O and A letters find nothing inside, plain or with a glow pooled round a counter whose middle stays clear (three glows). `tests/gen/test_logo.py` checks that a title in both keys' hues is refused at `key` before the lettering is bought, that a named key in the title's hue is kept and the warning says so, that a see-through cut is refused at `matte` and kept aside with no text check, with or without a 9x9 square of the key in the middle of its patch, and that a glowing title is not see-through inside. `tests/logo_lettering.py` gains the `quilt` fixture: square fabric patches in outlined pixel letters, one with a counter, on a key. It also gains `walled_patch` (a navy letter with a mint patch on pure green, with squares or a pixel of the key painted in) and `hollow_letters` (the big O and A shapes), which `lettering` draws through its new `shapes` argument.++**Upgrading from 3.0.0:** Existing runs and commands do not change. This release adds two verbs and a JavaScript player. The wheel now also carries `sprite_gen/video/*.mjs`.++- `sprite-gen video-face` builds a face pack from a reference, a keyed talking clip, and keyed body motions.+- `sprite-gen face-bake` runs the pack's player through node to bake a voice onto body frames, with optional MP4 and beside video output.+- Face request kind `sprite-gen-face-request`, version 1, records face geometry, clip placement, a rest loop, and optional own-mouth spans or timelines.+- Face pack kind `sprite-gen-face-pack`, version 1, carries sprites, body cells, anchors, keeps, rules, a report, a copied player, and SHA-256 digests.+- The lower-face layer covers the mouth, jaw line, cheeks, and chin. The body's own dark grey and black that reach in from the layer's boundary, such as a headset boom or a choker, the body's own lines in the layer's feather, and a hand that reaches over the face from outside the layer stay above it.+- Each body frame receives a place, size, and tilt anchor. The pack records anchor residuals and corrects outlying readings against neighbouring frames. A body frame whose own mouth is closed has its place read again on a ring of skin round the mouth, because a head that turns moves its hair, headset, and cheeks further than its mouth, and a frame whose mouth is open takes the move of the read frames round it. The pack records each frame's move and the frames read on the ring.+- Talking frames are assigned to smile or neutral sets by closed-mouth lift. Entry chooses a matching set and rest.+- The player `sprite-gen-face-v1.mjs` contains the voice flap, face pick, scene plan, and live canvas playback rules.+- A clip's own mouth and sound finish before a requested line starts. The voice and layer then wait together for the first frame whose switch to the chosen rest is within the 1.4 jump line. Layer exit also uses that jump line.+- The live player keeps one queue of every `play` and `say` request, in the order the calls are made, and starts each request on the frame after the one before it has ended, so two voices never overlap. A line placed right after a clip with its own mouth is planned together with that clip, the plan `planScene` makes and `face-bake --play` bakes, and its voice and layer start at the plan's `line_start` after the own-mouth span. The queue has no length limit and drops nothing: a request whose sound does not load or decode, or whose line `planScene` refuses, rejects its promise when its turn comes, and the next request goes on.+- Bakes check pack digests, changed pixels outside the weight, and composite jumps. Refused bakes retain their frames for inspection.+- See [docs/face-parts.md](docs/face-parts.md) for the request, pack, player, commands, and limits.+- **Tests**: `tests/video/test_face_layer.py` uses `tests/talking_face.py` to check smile and neutral sets; clip entry set and rest; own-mouth timelines, including a close during voiced sound and refusal of a missing or never-closing timeline; a head 60 px from its place and tilted 3 degrees; a head that turns, tilting up to 5 degrees about its mouth while its hair, headset, and cheeks move up to 12 px sideways and its mouth stays where it is, with two of its eleven frames open, whose anchor place is within 1 px of the mouth on closed frames and within 2 px on the two open frames and whose tilt is the band's, below minus 2.5 degrees where the turn is fullest; hand, headset boom, and choker keeps; a tongue in the body's own open mouth, joined to a hand by a finger at its corner, covered by the layer; unchanged pixels outside the weight; synthetic cells keeping the key's colour under no coverage; digests and new-folder pack writes; the player flap against its original numpy rule and the pick against the draft Viterbi over every frame; a line waiting for a clip's own mouth and for a frame its layer can come on at; the live player run by node on a fake audio clock, with two lines requested during a greeting's own mouth, three lines requested on the loop, one line requested during the own mouth and one after it, a line whose voice loads late, a line requested right after a clip whose sound loads late, a line whose voice loads only after the greeting's own mouth has ended or only after the greeting has ended, which waits for the greeting to end while the greeting plays to its end with the layer off, a line that plays on the loop when requested right after a clip whose sound fails to load, and a request that fails; loop and post-greeting bakes with greeting frames unchanged byte for byte; and refusal of a changed pack.++ **Upgrading from 2.45.3: This release changes defaults for video frames.**++ Outputs that change bytes are frames from `video-frames` and `video-set` on a green or magenta key.+ These changes occur within 6 px inside the keyed silhouette only.+ Video frames keyed with explicit `--decontam palette` also change bytes, because they use the same video fit.++ Outputs that do not change bytes include runs on a white key, subjects with no interior, and runs with `--alpha-mode brightness`.+ Stills (`cutout`, `gen`) and row extraction (`extract`, `inspect`) do not change bytes.+ Runs with `--decontam off` also give the 2.45.3 bytes back exactly.++ To get the 2.45.3 frames back, pass:+ `--decontam off`++ - **Default change: `video-frames` and `video-set` now default to `--decontam auto` (before: `off`).**+ This release updates these defaults to clean chroma-bleed edges automatically.++ On a chroma key, H.264 4:2:0 chroma mixes key colour into strands one to three pixels wide.+ With decontamination off, a red hair strand on green keeps an olive rim.+ The `auto` pass restores the subject's own colour to those edges.++ The video default stayed `off` until now out of caution rather than any known defect.+ The pass was benchmarked on a green key only.+ The video fit is less decisive than the still fit.+ In the documentation's benchmark table, the video-fit row (10.8 % residual contamination, 9.38/8.73 halo, 91.4 % recall) was measured in September 2026 with flank recovery.+ It has not been remeasured since flank recovery was dropped, because those benchmark inputs and tools are not at hand.+ The diagnosis table in `docs/chroma-alpha.md` (its `decontam` section) has the current video fit's numbers.+ Still-fit rows in that table are unchanged.++ Earlier fixes resolved the Grok-magenta regression through the key-hue cap and corrected the frame-edge interaction.+ No blocking defect remains known.++ On synthetic diagnosis clips (CRF 18, `--spill small`, 6 frames, one machine), `auto` reduced key contamination on red strands on painted green from 24.2 % to 10.2 %, and on pure green from 27.4 % to 10.9 %.+ Halo composite error on dark and white backgrounds shifted from 11.6/12.1 to 9.6/10.1 on painted green, and from 12.0/11.9 to 10.0/9.9 on pure green.+ Strand recall stayed at 91.4 % on painted green and 92.4 % on pure green.+ Strand recall no longer rises with the pass, because that gain came from the flank that the video fit no longer recovers.+ Halo gains are smaller than before for the same reason.+ On these moving scenes, key contamination is about one point higher than with the hold and settle alone, because a change of call now takes a few frames to reach the fit's colour.++ Key contamination dropped from 3.4 % to 0.5 % on magenta, and from 5.4 % to 1.8 % on Grok darker magenta.+ Halo shifted from 15.0/19.6 to 12.7/16.4 on magenta, and from 20.7/31.5 to 19.3/30.0 on Grok darker magenta (compared to 17.1/24.7 when flank recovery was present).+ Strand recall shifted from 87.0 % to 86.9 % on magenta and from 73.3 % to 73.2 % on Grok darker magenta.+ Outline ink CIELAB error shifted from 19.3 to 20.2 on magenta, and from 21.7 to 22.6 on Grok darker magenta.+ Red hair counts as key-coloured material there, so the palette is not key-free and the warning line appears.++ Contamination dropped from 20.6 % to 8.8 % on a translucent glow scene (halo 12.6/9.4 to 11.7/8.5, strand recall 85.7 % to 85.4 %).+ It dropped from 23.8 % to 11.4 % on a small green charm scene (halo 11.8/12.9 to 10.0/11.1, strand recall 90.7 %).++ Changed pixels make up about 2.4 % of each frame (4.7 % in translucent scenes).+ All changed pixels lie within 6 px inside the silhouette.+ Nothing outside the silhouette changes any more.+ Interior pixels remain byte-identical.++ Stills (`cutout`, `gen`) and row extraction (`extract`, `inspect`) still default to `off`.+ The row extractor frames are a derived cache that `heal` re-derives, so changing their default would silently rewrite existing runs.+ Stills remain as they were.++ - **Temporal fit: The video fit holds edge decisions across frames, blends a change of call over frames, settles still pixels, and drops flank recovery.**+ With default `auto`, the edge of a subject standing still sparkled from frame to frame where `--decontam off` remained calm.+ Codec noise pushed edge pixels across the pass's threshold tests from frame to frame.+ These tests decide blends, tints, material behind, explained pixels, palette colours, and flank coverage.+ Each crossing changed the written colour by far more than the noise itself did.+ The raw matte with `off` follows codec noise smoothly, staying calm despite keeping an olive rim.++ `video-frames` and `video-set` now maintain a clip history in clip order.+ This history passes to each frame through `decontaminate` as `history` (`decontam_history` in `cutout` and `remove_chroma_background`).++ Each test now holds its previous outcome at that pixel until current evidence passes the bar the other way by 16 (an RGB distance, `VIDEO_HOLD`).+ A palette colour picked in the previous frame stays unless another colour's line passes closer by 16.+ Moving pixels change their evidence far beyond 16 and are decided afresh.+ Only near-threshold calls stick.+ With the hold alone, a call that did change could still move a still edge through the whole gap between the matte and the fit in one frame.++ The blend mixes two renderings made from this frame's evidence at every pixel the pass examines.+ One is the matte with its key hue capped, and the other is the fit's palette colour at the pixel's light, with the fit's coverage where the call refits coverage and the matte's coverage elsewhere.+ For a palette-colour change, the fit's rendering mixes the two colours' renderings.+ A new palette colour waits until the change in hand is done, while a return to the old colour turns that change around.+ The mix moves toward this frame's call by at most 0.2 a frame (`VIDEO_BLEND`).+ It moves less if needed to limit the output change to 4 (`VIDEO_STEP`) plus 0.25 (`VIDEO_STEP_MOTION`) per unit the source moved, measured in premultiplied colour or coverage across its 3x3 box.+ A pixel new to the band starts at its call if it was transparent in the previous frame, and otherwise starts from the matte.+ Both renderings follow a moving subject at once; the change of call is spread over frames.++ A still pixel whose mix moved, has not reached its call, or came into or left the band moves at most 4 a frame from its previous output, measured in premultiplied colour and coverage.+ Here, still means its source moved by at most 8 in any channel anywhere in its 3x3 box (`VIDEO_STILL`).+ A pixel the hard cut keyed in this frame stays transparent.++ Still pixels settle toward the current fit when their mix is at its call in both frames.+ When a pixel was written in both frames in the same palette colour, and its source is still, it settles.+ It moves a tenth of the way (`VIDEO_SETTLE` 0.1) toward this frame's fit and stays within 12 per channel (`VIDEO_SETTLE_REACH`) of it.+ When it must catch up to get within 12, it now moves at most 4 a frame in premultiplied colour and coverage instead of moving all at once.+ This dampens codec noise while following real slow changes within 12 levels.++ The video fit also drops flank recovery.+ It no longer gives coverage back to keyed pixels (hard cut background within 3 px of the subject).+ Decoded chroma blur created faint blends on keyed pixels, and codec noise carried them back and forth over the noise floor.+ This filled dark gaps between strands with a faint smear that came and went across frames.+ The video fit now examines the band only (subject pixels within 6 px of the keyed background).+ The still fit keeps its flank recovery unchanged.++ With history enabled, frame bytes depend strictly on previous frames in clip order and remain deterministic.+ A single video-fit call without history gives the same band bytes as before, leaving keyed flank pixels as the matte keyed them.++ On a synthetic still scene under decoder noise (red strands 1 to 3 px wide on painted green, 8 frames, sigma 2):+ Mean edge change between frames on a dark background was 2.34 with `off` (99th percentile 8.3).+ With the hold and settle alone, the mean was 2.27 (99th percentile 8.3).+ With the blend and still steps, the mean is 2.25 (99th percentile 8.0).+ Key contamination on that scene was 6.5 % with `off`, 2.3 % with the hold and settle alone, and 2.4 % now.++ On a second synthetic scene, decoder noise changed between two frames and the source then stayed still for 19 frames.+ With the hold and settle alone, changed calls appeared in one frame and their pixels stopped moving when the source stopped.+ Now those edge pixels keep moving toward their new calls, by no more than 4.31 premultiplied a frame including uint8 rounding, and arrive by frame 14.++ Per-frame stats and clip totals include `held_px`, `blending_px`, and `settled_px`.+ `held_px` counts pixels where a held outcome or colour differed from an independent fit.+ `blending_px` counts pixels showing a mix of two calls rather than this frame's call.+ `settled_px` counts pixels the settle or a still step moved from the previous frame's output.+ In video, `recovered_px` is now 0.++ Keying cost was remeasured on an Intel i5-7500 with a 1080x1920 synthetic clip at CRF 18 and `--spill small`, six frames, one process per run, in the same session.+ Keying took 1.14 s a frame with `off`, 3.25 s with the hold and settle alone, and 3.36 s now.+ Peak memory was about 400 MB with `off`, 945 MB with the hold and settle alone, and 1155 MB now, adding about 365 MB over `off` per megapixel.+ Because `video-set` keys three items at once by default, it can use about 2.3 GB more than `off` at that size.++ - **Guards: Two new guards protect key-coloured details and material behind edges in the video fit.**+ The still fit output is unchanged byte for byte, but explicit `--decontam palette` runs in video also use these guards.++ The key-coloured parts guard protects small details that share the key colour.+ A subject can own a key-coloured part too small for the palette to keep, such as a green charm on red hair under a green key.+ When such a part covers under 0.5 % of the interior, the palette learns key-free colours.+ Without the guard, the pass repainted the rim in the nearest key-free colour, turning the green charm's rim brown.++ Now, when the palette is key-free, band pixels within 6 px of such a part keep the matte's bytes.+ There is no flank in video any more, so this guard covers band pixels only.+ This applies to pixels near parts that are opaque, deeper than 6 px, and have key hue above 8.+ The key-hue cap leaves those pixels alone.++ On synthetic tests, the share of the charm's key-coloured edge pixels that lost half their key hue or coverage was 0.77 with `off` and 0.82 now.+ Its colour error was 41.7 with `off` and 45.6 now (64.9 without the guard in the diagnosis).++ The material-behind guard preserves edges where subject material continues to the silhouette boundary.+ A band pixel keeps the matte's bytes when its colour, observed directly or at its own luma, falls within the opaque margin of the mean colour of subject pixels right behind it.+ This check reads subject pixels deeper than 2 px within a 3 px box radius.+ Such pixels are treated as material continued to the edge rather than blends or tints.+ The key-hue cap still applies to them.+ Unlike the still fit, this guard does not require the pixel to be free of the key's hue, because decoded chroma blur gives every edge some key colour.++ - **Diagnostics: A one-line stderr warning and new report fields track skipped frames and guard activity.**+ `video-frames` prints a single line on stderr after its JSON summary when edge decontamination warrants attention.+ The line starts with `video-frames: warning: decontam auto ...` and ends by naming `--decontam off` as the way to keep the matte as it is.++ The warning prints when `auto` ran on no frames, when `auto` skipped some frames, or when the subject owns key-coloured material so the palette is not key-free.+ On magenta keys, the red hair's blue channel sits more than 8 above its green, making the hair key-coloured material (9.6 % of the interior on magenta and 6.6 % on Grok's darker magenta) and triggering this warning.+ The warning also prints when the key-coloured part guard kept edge pixels, reporting how many and noting that thin details farther out may be repainted.+ A few key-hued pixels deep inside from codec noise guard no edge and raise no warning.+ Brightness alpha raises no warning.+ `video-set` prefixes this warning line with the item name and records it under `warnings` in the set report.++ The JSON report adds `decontam.reason` for the first skip reason and `decontam.skipped_frames` when frames are skipped.+ Per-frame stats and clip totals in the video fit add `key_part_kept_px`, `behind_kept_px`, `held_px`, `blending_px`, and `settled_px`.+ Where `auto` cannot run, frames remain exactly as the matte keyed them.+ The report records "the white matte has no key colour to remove" for a white key.+ It records "no interior to learn the subject's colours from" when no pixel lies deeper than 6 px inside the silhouette.+ Under `--alpha-mode brightness`, `auto` defaults to off, recording `{"mode": "auto", "applied_frames": 0, "reason": "brightness alpha has no key colour to remove"}`.+ Explicit `--decontam palette` with brightness alpha remains refused.++ Known limits apply to this release.++ The hold works on pixels that stay put.+ A change of call on a still edge arrives at most 4 a frame.+ The largest change, between the matte's full coverage and a faint fit, can take up to about 64 frames, or about 2.7 s at 24 fps.+ Until it arrives, the edge shows a mix of the matte's colour and the fit's.+ A strand that moves is decided afresh in every frame, while its change of call is spread over a few frames and both renderings follow it.+ A moving edge still changes from frame to frame as its colour does, so a red rim moving over a dark background changes more than the olive rim `off` leaves.+ Pixels whose call changes show a mix of the two calls for a few frames.++ The settle follows a slow change within 12 levels per channel and catches up past that at most 4 a frame.++ The video fit gives back no coverage the hard cut keyed.+ Outer pixels of a soft edge that the cut erased stay erased.+ Only on stills, outside a dark outline the flank can give a few faint pixels in the subject's colour.++ A thin feature whose colour is absent from the interior can be read as a palette colour plus key.+ For example, a thin yellow line beside red hair with a pink highlight turned pink (colour error 26.2 with `off`, 47.5 now).+ `--decontam off` keeps that line.++ A thin key-coloured detail farther than 6 px from any key-coloured interior is repainted in a palette colour.++ The thinnest strands retain some olive because decoders share chroma across aligned 2x2 blocks, leaving a one-pixel strand with half the key's chroma.+ A block-aware fit is planned separately.++ Pixel-art rows binarizing alpha, the green-only benchmark, and increased processing time and memory remain known limits.++ - **Tests**: `tests/frames/test_chroma_decontam.py` checks that both video verbs default to `auto` and that still verbs and the row extractor do not.+ It checks that `off` gives the engine's original bytes.+ It checks that `video-set` hands its value to `video-frames` and lists the warning.+ It checks that a white key, a subject with no interior, and brightness alpha give the same bytes as `off` with the reason.++ A new section tests the video fit over time on the red-strand scene standing still while decoder noise changes every frame (luma per pixel, chroma per aligned 2x2 block, eight frames).+ The default's edge changes from one frame to the next no more than `off`'s, in mean and at the 99th percentile.+ The edge is still cleaned, with key contamination at most half of `off`'s.+ Clip totals count held and settled pixels, and the first frame has none.+ A frame given twice comes out with the same bytes both times.+ Another test decodes one frame of the red-strand scene, then holds a second noise draw (sigma 3) still for nineteen frames.+ After the source stops changing, the default keeps moving toward the calls the noise changed.+ No pixel moves more than `VIDEO_STEP` in one frame in premultiplied colour or coverage, plus one for uint8 rounding.+ It arrives by the last frame.+ Clip totals count `blending_px`, and the first frame has none.++ The video fit leaves every pixel the hard cut keyed transparent and recovers nothing.+ The still fit still recovers its flank.++ Changed tests reflect dropped flank recovery in video.+ A head 6 px under the top frame edge passes the edge gate under the default and keeps the blur rows below the edge band as the matte keyed them.+ For magenta skin tone in a 4:2:0 frame, the video fit's halo is read on the band where it acts (at most 0.9 of `off`'s), and the keyed flank keeps the matte's bytes.+ The still fit keeps its halved halo.++ The rim of a small green charm keeps the matte's pixels and loses at most 0.1 more than `off` while strands away from it are cleaned.+ On magenta and Grok magenta, halo and alpha error do not rise.++ A few key-hued pixels deep inside raise no warning.+ `video-frames` prints the warning line on stderr.++ `tests/video/test_gait_guard_anchor_wide.py` has its stand-in for `run_frames` take `decontam` and checks that the set's `auto` reaches it.++## v3.0.0 - Remove rig layer composition++**Upgrading from 2.46.0: `sprite-gen compose-layers` and its other launch forms are removed, and rig layer declarations are no longer read.** `compose-atlas` no longer writes a manifest `rig` block or `animation.rows.<state>.track` for a run that declared a rig. Runs that never declared `rig`, `layers` or a state `track` get the same manifest as before. Existing run files and `layers/` folders stay on disk.++### Breaking++The rig layer feature has no replacement in 3.0.0:++| Removed | Use |+|---|---|+| `sprite-gen compose-layers`, `python -m sprite_gen.compose.compose_layers`, `scripts/compose_layers.py` | No replacement. The CLI verb now ends as an unknown command with argparse exit code 2. |+| `sprite_gen/compose/layers.py` (declaration checks for rig profiles, row tracks and composite stacks), `sprite_gen/compose/compose_layers.py` (baking declared stacks into `<run>/layers/`) | No replacement. |+| `sprite-request.json` keys `rig`, `layers` and `states.<state>.track` | Remove them with `sprite-gen migrate-request <run> --apply`. |+| `sprite_gen.spec.runio.normalize_retired_fit_keys` | `normalize_retired_keys`, which returns a list of keys moved or left out, or an empty list. |+| `docs/layer-tracks.md` | No replacement. Its links are gone from the other docs, READMEs and `SKILL.md`; the skill description no longer lists "rig layers". |++- `prepare` drops the retired keys from `--request` and `--request-json`, naming them in its existing stderr note. Code no longer reads them. On the first read of an old run's request, the process prints one stderr line naming the keys, treats them as absent in memory and leaves the file byte for byte unchanged. Unrelated request rewrites, including reroll and interpolate takes and curation fps edits, preserve those keys as they were.+- `sprite-gen migrate-request <run>` lists the keys it would remove without writing. `--apply` removes them from the file; a second apply has nothing to move. The changed bytes move `run_revision`, and the command names the curation rows it will drop before writing. The command also retains its existing `fit.pixel_perfect` to `fit.pixel_unfake` migration. `runio.migrate_request_file` now returns the list of keys moved or left out instead of a boolean.+- Talking face parts are planned as a new feature in a later 3.x minor release.+- **Tests**: Added `tests/spec/test_request_retired_rig_keys.py` to check the one-time stderr note and unchanged old request bytes, migration dry runs and repeated applies, preservation on unrelated edits, and named drops in `prepare`. Removed `tests/compose/test_layer_compose.py`, `tests/compose/test_layer_contract.py` and `tests/packaging/test_layer_cli_entrypoint.py` with the feature.++## v2.46.0 - Changed loop and framing defaults, recognition of cyan or yellow leaning green border keys, Breathe smooth mode and Sway commands++**Upgrading from 2.45.3: Some existing runs produce different bytes because defaults changed.**+`video-loop --cycle pinned` with `--anchor none` now blends the wrap when the pin passes its gate and the pinned last frame redraws the first.+A redraw means the first cell differs from the pinned frame by more than `--seam-max` (default 2.0) times the cut's median step at full size.+Those cuts have different `cycle/` cells over the last half second, and a different strip, GIF and WebP.+`video-set` takes this default for idle and attack clips filmed with their first frame as the last; a walk or run cut the same way is blended too.+The blend does not read the state, and `--wrap-blend off` cuts as filmed.+Every pinned cut gains the report key `wrap_blend`, which also appears in strip metadata where the blend applied.+A source projection reads a blended strip as `source-processing-unsupported`.+Under `--repair auto` or `--repair on`, a loop that is not a walk or run and is cut to play as a loop now has its wrap read against the steps beside it.+This excludes `--cycle once`, `once-return` and an effect's lifetime.+When the wrap step exceeds `--seam-max` times the mean of the three steps on either side and exceeds 0.005, RIFE makes one, two or four frames round the wrap again.+Such a loop can have different cells, strip, GIF and WebP, or pass where 2.45.3 refused it.+Its report now reads `jump_repair.reading: "seam"` instead of `"why": "not a gait state (...)"`.+Without RIFE, a wrap needing the bridge is cut as filmed and a `warning:` line names `sprite-gen rife install`; with `--repair on`, the run is refused.+The bridge reads the wrap after the blend, so a pinned idle or attack can receive both.+A pinned clip whose pin the gate refuses is not bridged and is refused on its pin as before.+Walk and run loops retain their 2.45.3 bytes except when cut pinned with `--anchor none` and a last frame that redraws the first; `--wrap-blend off` restores those bytes.+For a loop that is not a walk or run, `--repair off --wrap-blend off` restores the 2.45.3 cells, strip, GIF and WebP, with `"why": "--repair off"` in the report.+Do not use `--repair off` to restore a walk or run: it also disables the jump repair that ran by default in 2.45.3.+The default `video-frames` edge check (`edge_policy`) is now `border` instead of `refuse`.+A clip whose first-frame subject covers at least 2 % of the outermost row or column on the top, left or right now passes where 2.45.3 refused every frame as "framed too tight".+If the first frame crosses no side, it is judged and worded as in 2.45.3; `--allow-subject-edge-contact` and `--allow-edge-contact` also judge as before.+In a refusal, the top, left and right numbers now count pixels the border does not take.+The `video-frames` report gains `edge_border`, and each contact row gains `rim`.+A refused `video-frames` run leaves frames in `keyed.refused/`, removes `keyed/` even from an earlier run, and writes a report with `status` set to `passed` or `refused`.+A refused `video-loop` run removes an earlier cut's `cycle/`, strip, strip metadata, GIF, WebP, `cycle.source/` and `follow.source.png` from the output folder; a cut already written is kept as `cycle.refused/`.+A passing run delivers the same bytes as before, while a caller that misses a refusal's exit code no longer finds an earlier run's files.+Borders already recognised as a green key in 2.45.3 key byte for byte as before under the same key.+A border green leaning toward cyan or yellow, such as `#00B140`, now uses the green key: `cutout --key auto` and `video-frames` use it instead of the position-based white matte, `video-canvas` repaints such a still to the exact key and accepts `--key green`, and `video-frames --spill auto` reads it as `full`.+Those outputs can change; Python callers of `extract.detect_background_key_rgb` can pass the new `threshold` argument, which the engine supplies from `--key-threshold` (default 96).+New commands are `sprite-gen breathe`, `video-sway` and `video-sway-inspect`, and Breathe gains a smooth mode for large illustrations and video frames.+Breathe without `mode` or with `mode: "pixel"` keeps the same bytes and sidecar; new Breathe values set to 0 or omitted also keep the same bytes.+`video-follow` and `video-follow-inspect` keep their names and files, including the `follow` record, `follow.source.png` strip and `follow-inspect.*` inspection files.+Moving the written names to `sway` is a later change made together with the tools that read them.+Every command now reopens stdout and stderr as UTF-8 where needed so it can print on Windows consoles or pipes using cp949 or cp1252; importing `sprite_gen` leaves the caller's streams alone.+Restoration schemas remain `source-restoration-v5`, repair report `schema_version` 4 and comparison `schema_version` 6, while the report's `producer` names the new version.+2.45.3 changed only the `--anchor body` seam check, so detailed comparisons below with 2.45.2 for keying, framing and `video-frames` also hold for 2.45.3.++- **Changed (default):** A video model given the first frame as the last draws that frame again (softer or sharper, another tone, hair strands a pixel over).+ The pin gate reads the pose and passes.+ The drawing stays, so the loop's wrap shows one jump in sharpness where every other step shows the motion.+ Over the cut's last half second (K = min(round(0.5 s x fps), floor(L / 4)) cells, 12 at 24 fps), wrap blending adds back j/(K+1) of the redraw's difference (first cell minus pinned frame, premultiplied) on the j-th cell.+ Each pose stays the cell's own, and its drawing turns into the first cell's by the wrap.+ Only a redraw is ramped.+ A pixel is held where the two ends hold a part, a line or a dot in different places, and where a ramp cell does not stand where the pinned frame stands.+ This check applies after one softness match of at most 0.7 px.+ A pixel is held if it is more than 12 levels outside what the other end holds within 1 px on a 7x7 mean or a 7 px run, over black and over white.+ It is also held if its value is more than 12 outside the other end's 1 px range where the other end has under half this end's range there, in any direction, length or width.+ Held pixels are widened 3 px and the weight feathered 7x7.+ A pixel of weight 0 is the filmed byte.+ A ramp that steps more than the cut already does, or that does not shrink the wrap, is not used: the cut is written as filmed and a `warning:` line says so.+ A wrap still over `--seam-max` after blending also gets a `warning:` line.+ New flag (default `auto`, and `video-set` takes the default):+ `video-loop --wrap-blend auto|off`+ New report key `wrap_blend` on every pinned cut (`applied`, `why`, `K`, `cells`, `residual_ratio`, `wrap_ratio_before`, `wrap_ratio_after`, `ramp_step_max_ratio`, `bound_ratio`, `pose_share`, `presence_share`, `never_settled`, `equalize`, `after_check`, `seconds`).+ `wrap_blend: {cells, K}` appears in the strip metadata where it applied, and in the CLI summary.+ [loop repair](docs/loop-repair.md#6-the-redrawn-wrap-a-pinned-clip-whose-last-frame-the-model-drew-again)+- **Tests**: `tests/video/test_wrap_blend.py` on synthetic clips:+ a redraw of tone and 0.5 px softness has its wrap brought from 7.31x to 0.57x the median step and only the ramp's cells, strip, GIF and WebP differ from off;+ an arm still coming down in the ramp stays the filmed arm;+ a part moved 2 to 64 px, or present at one end only, is never drawn twice (the 14 px part on a flat figure is cut as filmed with a warning);+ 1 px lines moved 2 to 32 px on a flat figure are byte for byte;+ stripes swinging inside the ramp keep their swing;+ a strand against the silhouette is held over white where black alone lets it through;+ the softness match blurs the sharper end, never past 0.7 px;+ the idle-still fixture gives every output byte for byte;+ fixed cuts, body-anchored pinned cuts and refused pins are not touched;+ a ramp that steps past the cut is refused with a warning;+ a 1 px line at slope 1/3 moved 8 px is held line for line, thin structures change by at most 2 levels and busier quiet grounds by at most 3, strands off the silhouette by none.+- **Changed: `video-loop` bridges a jumping wrap on idle and action loops (`repair.seam_bridge`).** Under `--repair auto` (the default) or `--repair on`, a loop whose state is not a gait (idle, jump, attack, or a generic in-place action) has its wrap read against the steps beside it; where it jumps, one, two, or four frames round the wrap are made again by RIFE between the frames either side; the loop is not read for its flow (an idle's own motion would leave it). See [loop repair](docs/loop-repair.md#the-seam-bridge-a-loop-that-is-not-a-walk-whose-wrap-jumps).+- **Tests**: `tests/video/test_seam_bridge.py` covers the synthetic idle with wrap jump J = 2.6 closed by one frame and passing the gate, J = 5 tried at one and two frames then closed by four, J = 12 refused without frames made, J = 1 closed loop untouched without an interpolator, whole-pixel stepped motion not bridged, near-still loop under the noise floor not bridged, loop drawn on twos skipped, real RIFE (rife-v4.6 with augmentation) closing J = 2.6 without faults, frames made with a fault (a stand-in painting a dark patch: smear at every width, seven calls, nothing taken, gate refuses as before), missing RIFE where the wrap is cut as filmed with the install line in `jump_repair` and a `warning:` line, a wrap that reads as a step saying nothing, `--repair on` refusing with the install line, a pinned clip whose pin the gate refuses skipped without reading and refused on its pin, the CLI summary naming the frames made, and the report naming the RIFE that made them; a `--repair on` run without RIFE, in an output folder where an earlier cut passed, refused on a wrap needing the bridge and leaving none of that cut's `cycle/`, strip, strip metadata, GIF or WebP, and no `cycle.refused/` because the new cut was not yet written.+- **Default change: A drawing cut by its own frame is no longer refused as framed too tight.** A bust or half-length drawing runs off the frame itself (its sleeve cut off at the left, its hair at the top), so in every frame of its clip the subject touches those edges and no canvas gives it room there. In 2.45.2 the default `video-frames` edge check refused every frame of such a clip with "the subject touches the frame edge ... framed too tight". Only a flag let it through: `--allow-subject-edge-contact`, which also lets through a subject that really leaves the frame, or `--allow-edge-contact`, which turns the check off. The default (`edge_policy` is now `border`, was `refuse`) reads the drawing's own border on the clip's first frame, keyed with its specks erased: a side (top, left, right) whose outermost row or column the subject covers for at least 2 % of its length (`frames.BORDER_MIN_FRACTION`) is a border side. Subject contact there is accepted in every frame, wherever along the side. Subject contact on any other side is still refused as framed too tight (a bust cut at the top and left whose hand leaves the right). The top / left / right numbers in a refusal are now the pixels the border does not take, so a caller that reads them to choose a taller or wider canvas reads the side that needs room. Leftover key is still refused, except the body's rim the matte cut loose: a key-only piece is accepted only on a border side the same frame's subject reaches, holding fewer than 8 pixels in all (`SPECK_MIN_PX`) and lying wholly within 10 px of the frame's body (`frames.RIM_REACH`, counted each way and diagonally; the body is the largest piece holding a pixel off the key). A thin outline blended with the key leaves such pieces at the edge between strands. Larger pieces, farther pieces, pieces on other sides or on a side the frame's subject left, and a detached stain beside a sleeve on the same side are refused as in 2.45.2. A clip whose first frame crosses no side is judged and worded exactly as in 2.45.2, byte for byte. The two flags judge as in 2.45.2. Taking a side as the border prints one stderr line. The report gains `edge_border` (`frame`, `sides`, `outer_px`, `min_fraction`, `rim_reach`, `rim_under_px`); each contact row gains `rim`, and under the default `border` (pixels taken) and `off` (pixels not taken, by side). Known limit: a hand that newly leaves the frame on a side that is already a border side is accepted; by position it cannot be told from the sleeve moving along the edge. [video pipeline](docs/video-pipeline.md), section 3.+- **Default change: A refused run hands nothing over.** A caller that does not read the exit code used a refused run's output as if it had passed. In 2.45.2 a refused `video-frames` run left its keyed frames in `keyed/` and wrote no report. `keyed/` was not emptied before keying, so a pass after a longer earlier run in the same folder also held the earlier run's extra frames. A refused `video-loop` run could leave a mixed set: for example after the pin gate refused, `cycle/` and the strip were the refused run's while the GIF and WebP were an earlier run's; a refusal before the cut left the earlier run's whole set. Now `video-frames` keys into a hidden working folder and hands over `keyed/` only when the run passes. A refused run (the edge check, or a frame keyed to 0 % transparency) leaves its frames as `keyed.refused/` and no `keyed/`, not even an earlier run's. A pass removes `keyed.refused/`. The report is written either way, with `status` (`passed` or `refused`); a refused report adds `error`, `refused_dir` and `keyed_dir: null`. Keyed frames that pass are the same bytes as before. Every `video-loop` refusal that writes `status: failed` (selection, motion anchor, jump repair, jolt, pin, seam, a strip with no body, a GIF or WebP that could not be written or verified) removes `cycle/`, `<name>.strip.png`, `<name>.strip.json`, `<name>.gif`, `<name>.webp`, `cycle.source/` and `follow.source.png` from the output folder. A cut it had already written is kept as `cycle.refused/`, which the next pass removes. A strip with no body and a GIF or WebP that could not be written now also write the failed report. Argument errors touch nothing. [video pipeline](docs/video-pipeline.md), sections 3 and 4.+- **Tests** - `tests/video/test_edge_border.py` (a bust cut at the top and left passes and the report names its border; a padded jump whose head leaves the top and a first frame with a 2 px wisp on the top are refused with the 2.45.2 message, byte for byte; a key-only patch with no border is worded as in 2.45.2; a hand leaving the right of a bust is framing, its message counting only the right; a hand leaving a border side elsewhere is accepted (the known limit); leftover key that is not the body's rim is refused (a patch on the right, a 48 px fringe beside the sleeve, a patch where the sleeve left, a detached 20 x 90 stain, 2 px pieces 11 and 14 px from the sleeve, pieces of 8 px and more, stripes hugging the head, stains beside the head, a fringe on a side that is not the border, a fringe above a head clear of the top band, a stain round a fleck of the body's colour); 1 px dots are judged piece by piece; 2 px pieces 2 to 10 px from the sleeve and a 7 px piece are the rim; an 8 px piece with 4 pixels in the band and a 7 px piece 11 px away are refused; the two flags judge as in 2.45.2; `classify_edge_contact` counts the rim; a refused `video-frames` run leaves `keyed.refused/`, no `keyed/` and a refused report; a pass after a refusal leaves `keyed/` alone; a pass over a longer run holds its own frames only; a frame keyed to 0 % transparency is refused the same way; an argument error touches nothing; a `video-loop` cut refused after it was written hands nothing over and keeps `cycle.refused/`, removed by the next pass; a cut refused before it was written hands nothing over; a loop argument error touches nothing), `tests/video/test_canvas_key_normalize.py` and `tests/video/test_fit_tight.py` (the 2.45.2 default's framing and mixed-contact tests now move the contact after the first frame and read the refused frames from `keyed.refused/`), `tests/video/test_edge_speck_lead_in.py` (the default policy is named `border`, and the refused frames are read from `keyed.refused/`), `tests/frames/test_chroma_key_relative.py` (the edge-contact split states the `rim` count `classify_edge_contact` now gives).+- **Fix: Green screens that lean toward cyan or yellow are now recognised as border keys.** A green screen that leans toward cyan or yellow was not recognised as the key on the border. Examples: the studio chroma-key green `#00B140`, (0, 177, 64); (0, 200, 90), which leans toward cyan; (90, 210, 0), which leans toward yellow. Each sits more than 96 from pure green. With `--key green` the whole background stayed opaque, and `video-canvas` refused `--key green` on such a still; but with `--key auto` the old rule did not take the green route at all: `cutout` and `video-frames` routed the frame to the white (position-based) matte, and `video-canvas` treated the still as a non-key base and did not normalize it. `video-frames --spill auto` did not always choose `full`: when the reference still had the same leaning green, `auto` read the surviving background as key material and chose `small`; when it chose `full` (a reference whose own background the old rule did recognise), the clip's surviving background was despilled to a blue-grey instead of being erased. The cause was that the border rule `extract.is_border_key_candidate` held every unkeyed channel under 64. That bar was set between magentas, whose one unkeyed channel (green) tells a painted magenta from hot pink. Green has two unkeyed channels, and a green screen leans on one of them. For the fix, the darkest unkeyed channel keeps the bar (under 64, and at most 35 % of the brightest keyed channel). The brightest one only has to stay under half of the brightest keyed channel (`extract._BORDER_KEY_MAX_LEAN_RATIO`, 0.5), that is a hue nearer green than yellow or cyan (between 90 and 150 degrees). The border detector, `extract.detect_background_key_rgb`, reads the lean second. It first counts, on their own, the candidates the 2.45.2 rule admitted. When those make up at least 12% of the samples, it returns the mean of their most populated bin, exactly the colour 2.45.2 returned. Below 12%, the samples only the lean admits join them, but their most populated bin gives the colour only where the declared key's own cut would leave that background on the border. Two conditions, both needed: the samples only the lean admits that lie farther from the declared key than the cut (the radius the caller keys with: the new `threshold` argument of `detect_background_key_rgb`, which the engine sets from `--key-threshold`, 96 by default), in that most populated bin or in a bin beside it on every channel, make up at least 2% of the samples; and the candidates outside that bin and the bins beside it make up less than 12% of the samples (the border holds one key-coloured background). Otherwise the declared key is kept, as in 2.45.2. A leaning border the declared key clears by itself gains nothing from the leaning colour; its ball would only reach further into a subject near that colour: (0, 210, 80) sits 91.8 from pure green, inside the cut of 96, so the declared key erases that background on its own, and a teal subject (0, 154, 149), 180 from the key, is kept; read as the painted colour, (0, 210, 80), 88.9 from the teal, let the ball reach the teal subject through the background and erase all of it, with no background gained. The 2% keeps the soft rim where a subject meets an edge of the frame (its blend with the background crossing the cut there) from being read as background the cut left; and a background whose tail past the cut is under 2% of the border keys as before the lean, the few pixels past the cut included. A second key-coloured colour on the border may be the subject's own (a leaf along an edge, another green); read as part of the background it would let the ball take a subject colour near the dominant one. `cutout`, the reference window `video-frames --spill auto` keys, and the YCbCr path's decontamination pass hand the detector the radius they key with, as the engine does. The painted key's erase ball, the spill judgment's subject window and the `video-frames` edge-contact split take the lean only from a painted colour that leans itself (`extract._painted_key_leans`). A colour found the first way never leans itself (magenta has no lean; for green the floor of the mean of one 8-wide bin of 2.45.2 candidates is always one of them), so they read it as 2.45.2 did. `cutout --key auto` and `video-canvas --key` classify the flat corner colour with the border rule, lean included (there the question is what the painted colour can be): a corner colour 2.45.2 took routes as before, and a leaning corner colour now routes to green. The magenta key is exactly as before (its one unkeyed channel is both the darkest and the brightest), so hot pink (250, 77, 150) and purple (213, 112, 246) are still refused. For green, nothing that was a candidate is dropped. Ivory, cyan, teal, sea green, a grey-green with both unkeyed channels lit and a green as near cyan as green are still refused. The interior rule `is_key_family` is unchanged. As a consequence, every image whose border the 2.45.2 rule recognised (its candidates at least 12% of the corner and border samples) keys byte for byte as in 2.45.2 under the same key, whatever leaning green is mixed into that border and in whatever share. Under the same key, every image is keyed either exactly as in 2.45.2 or exactly as with the leaning colour read. As in 2.45.2: wherever the 2.45.2 rule recognised the border (its candidates at least 12% of the corner and border samples), wherever the declared key's cut clears a leaning border by itself, and wherever the border holds a second key-coloured colour. With the leaning colour: where the key's cut leaves the border's one leaning background. Read together, a sample admitted only through the lean can share the 8-wide bin of a background 2.45.2 already found and move its mean, while leaning samples in a bin of their own that outnumber the background would take the mode. A leaning-green part of the subject on the corners and the border can be taken as the painted colour only where the 2.45.2 rule's candidates make up less than 12% of the samples, the key's cut leaves it and no other key-coloured colour holds 12% of the border, that is, only where the subject crowds the border. A leaning-green patch buried in the subject on such a background is kept. [chroma-alpha](docs/chroma-alpha.md), the 2026-10-21 paragraph.+- **Tests** - `tests/frames/test_chroma_key_relative.py` (the border table with the three leaning greens accepted and a grey-green and a cyan-midpoint green refused; the detector still refuses hot pink, purple, ivory, cyan, (30, 60, 30), teal, sea green and those two; over the whole RGB cube the lean adds nothing for magenta, drops nothing for either key, and adds for green only hues between 90 and 150 degrees; without the lean the candidate field is the old rule colour for colour over the whole RGB cube; the engine and `cutout --key green` key the leaning greens out with the subject byte-identical; `cutout --key auto` routes a leaning green to `extract:green`; a leaning-green patch ((0, 160, 75) or (10, 120, 50)) buried in the subject is kept byte for byte on (8, 162, 24) and keyed with the background on (0, 200, 90); the edge-contact split reads a leaning piece as residual when the frame was keyed from a leaning background and as the subject's when it was keyed from (8, 162, 24); on (0, 200, 64) with a leaning green, (0, 200, 71) in its bin or (0, 200, 90) in a bin of its own, over the top-left corner (20.5% of the samples) or everywhere but a 32 x 32 block of the background (77.3%), the detector returns (0, 200, 64) and the frame keys exactly as from that colour pinned, a teal subject (0, 154, 149) just outside the ball keeping every pixel; a leaning-green border on (0, 200, 90), past the cut, with no 2.45.2 candidate, or with a block of one under 12% of the samples, is found through the lean and keys out; and over every 8-wide bin of green, the floor of the mean of 2.45.2 candidates is one of them; on (0, 210, 80), inside the key's cut, with no 2.45.2 candidate on the border or with 11% of the samples an interior-family green, the detector keeps the declared key and the frame keys exactly as with the key pinned, a teal subject (0, 154, 149) losing no pixel; a leaning-green leaf of the subject along the bottom edge over a leaning background the key clears, a second leaning green in a corner, and a soft rim crossing the cut where the subject meets the side edges each keep the declared key; with 1.5% of the border a step past the cut the key is kept, and with 2.5% the leaning colour is read; (0, 200, 90) is read with a cut of 96 and not with a cut of 110; over a sweep of borders around the cut every answer is the 2.45.2 answer or the answer that reads the lean, and both occur, as do borders where the two differ and the key is kept), `tests/frames/test_key_detect_banded.py` (the whole-image reference now states this rule, and leaning-green borders (past, across and inside the cut, and two leaning greens on one border) join the images the banded detector is checked against), `tests/video/test_canvas_key_normalize.py` (`video-canvas` repaints a leaning-green still to the exact key and accepts `--key green` on it), and `tests/video/test_video_spill.py` (on a leaning green, `--spill auto` reads the reference as `full` with no key material, and the frame keys with no opaque background pixel and no edge contact, the subject byte-identical, with `--decontam off` and `palette`).+- **New: The Breathe layer adds `mode: "smooth"` for large illustrations and video frames.**+ Set per row: `states.<state>.breathe = {"mode": "smooth", "depth": ..., "breaths": ...}`.+ `pixel` stays the default.+ The head and everything above the measured neck line stays in place, byte for byte, in every cell.+ The figure's bottom stays put.+ It reuses the automatic anatomy: rigid row, body axis, torso half width, and basis rows.+ It also uses the neck's width, measured once on the row's first cell.+ The whole row uses that placement.+ The chest breathes from its centre.+ It uses a round (cos^2) weight on the body axis at `chest_y` of the body below the neck.+ The weight is `chest_rx` x torso half width wide, and `chest_ry` x the body below the neck tall.+ The chest centre rises by `depth` x basis rows at the in-breath and puffs out by `depth_x` from P (not from the ellipse centre).+ Two shoulder weights, on either side just below the neck, rise by `shoulder` x the chest's rise.+ They rise `shoulder_lag` of a breath later.+ The neck and the collar beside it hold still.+ Whole rows do not move.+ For a figure whose body axis is pulled to one side (for example by long hair), the chest is not on the axis: `chest_x` moves the chest ellipse's centre off the body axis, in torso half widths (-1 to 1).+ The shoulders stay where they were (relative to the body axis).+ For a turned body: `chest_tilt` (degrees, clockwise on screen) and `chest_dir` (degrees from straight up, negative = up-left).+ `chest_bias` moves the chest weight's peak P along the chest ellipse's long axis, as a share of its horizontal half width (-0.9 to 0.9, negative is the screen's left).+ `chest_bias_y` moves the peak P across the long axis, as a share of the vertical half height (-0.9 to 0.9, positive is down).+ The weight falls from P to the ellipse's rim along the ray from P through each point, so the near side falls off over a short distance and the far side over a long one.+ P must stay inside the ellipse: `chest_bias` and `chest_bias_y` together at most 0.9 of the radii (refused otherwise).+ `chest_flat` is the share of the way from the peak P to the rim that rises in full (0 to 0.9).+ These default to 0; at 0, nothing changes.+ One breath is a bump from rest (in-breath 40 %, out 60 %).+ A cell at phase 0 is the source byte for byte.+ Seams and joins between loops are untouched.+ `breaths` is a whole number.+ `breath_peaks` is a list of cells where each in-breath peaks, for timing the breath from outside (for example to keep the breath's peaks off a big hand movement in the clip).+ The breath count is the number of peaks (`breaths`, if given, must match).+ The first cell stays at rest and the loop closes at rest: breaths are separated by rests at cell 0, between two peaks where the out-breath has taken 60 % of the gap and the next in-breath 40 %, and at the loop's end.+ Refused, never silently clamped: `lag` on smooth (it would move the first cell), a stretch past the per-row strain cap (0.25) or a fold, opaque pixels pushed off the canvas, out-of-range values, `chest_bias` and `chest_bias_y` together past 0.9 of the radii, a peak at cell 0, peaks not increasing or closer than two cells, a last peak within one cell of the loop's end, mismatched `breaths`, and shape keys or `breath_peaks` on a pixel row.+ With the default shape nothing leaves the canvas.+ A figure cut by the frame at its sides or bottom is not refused.+ Defaults: `depth` 0.0085 (about 0.5 % of the frame height on a bust illustration), `depth_x` 0.028, `chest_y` 0.31, `chest_rx` 0.83, `chest_ry` 0.28, `shoulder` 0.5, `shoulder_lag` 0.08, and `chest_tilt`, `chest_bias`, `chest_bias_y`, `chest_dir`, `chest_x`, and `chest_flat` 0.+ Performance is about 0.2 s per 960 px frame.+- **New: `sprite-gen breathe <frames> <out>` lays the Breathe layer over a folder of loop frames outside curation.**+ This lays the Breathe layer (either mode) over a folder of loop frames that is not a curation run, such as a video loop's cells.+ It takes the sidecar's values through the same checks and the same bake: `--mode`, `--depth`, `--depth-x`, `--breaths`, `--breath-peaks` (for example `--breath-peaks 30,102`), `--lag`, and `--rigid-row`.+ It also takes the smooth shape flags: `--chest-y`, `--chest-rx`, `--chest-ry`, `--shoulder`, `--shoulder-lag`, `--chest-tilt`, `--chest-bias`, `--chest-bias-y`, `--chest-dir`, `--chest-x`, and `--chest-flat`.+ The same values give the same bytes as a curation bake.+ It writes the frames under their names and `breathe.json` (config, phases, the anatomy used) into a new folder all at once.+ Before creating or deleting anything, it refuses if `<out>` and `<frames>` are the same folder, if either lies inside the other based on real disk location (following symbolic links and treating two spellings on a case-insensitive disk as the same folder), or if `<out>` already exists and is not empty, while an existing empty folder is accepted.+ It never writes anything into `<frames>`, and it never changes or deletes any frames or other files there.+ It builds the result in a temporary folder of its own next to `<out>`, with a name no other folder has, and moves it into place in one step, deleting only that temporary folder if a run cannot finish while leaving alone folders it did not make, such as a leftover temporary folder of an earlier run.+ When `<out>` is a symbolic link to an empty folder, the result is placed in the folder the link points to, and the link stays.+- **Output change: The curation webview does not preview a smooth row.**+ The live preview mirrors the pixel warp only.+ It shows the original frame with a notice.+ Its row video export refuses.+ Saving keeps a smooth sidecar exactly as written instead of filling pixel defaults.+- **New: The follow-through is now the Sway layer, replacing `video-follow` with `video-sway`.**+ `video-sway` and `video-sway-inspect` replace `video-follow` and `video-follow-inspect`.+ Their Python modules are `sprite_gen.video.sway`, `sway_loop`, `sway_offsets`, and `sprite_gen.video.sway_inspect`.+ `video-follow` and `video-follow-inspect` remain as aliases with the same results and their own name in messages.+ A loop's record is read under `sway` or `follow`.+ Behaviour is unchanged.+- **New: `Anatomy` gains `origin` and `neck_span` values.**+ It does not put these two values in the sidecar or the manifest.+ `origin` records where the measured frame's figure sits.+ `neck_span` records the neck's span on the rigid row.+ Pixel Breathe does not use them.+- **Fix: every command prints on a Windows console or pipe in a legacy code page.** A line a command prints can hold an em dash, Korean or a path in any script; on cp949 (Korean Windows) or cp1252 Python could not encode it, and the command died at the print after its work was done (`background-tile` on Korean Windows). Each command's entry now reopens stdout and stderr as UTF-8 where they are not already (`sprite_gen.util.console.utf8_streams`, called first by every `main()` and by `sprite-gen`); importing sprite_gen leaves a program's streams alone. Test: `tests/util/test_console.py`.+## v2.45.3 - The seam check reads the frames that play when the body anchor spreads a sideways slide; such a cut passes again, as it did in 2.44.0**Upgrading from 2.45.2: Every cut 2.45.2 passed, and every `--anchor motion-auto` run, gives the same bytes as 2.45.2.** Only `--anchor body` cuts that 2.45.2 refused because of the walk sliding sideways before the anchor can now pass, read on the frames that play. Refused cuts print the same error line as before, the report's `producer` field names the new version, and there are no restoration schema changes.diff --cc docs/video-pipeline.mdindex ddd1cf4,c2eea12..1a605cc--- a/docs/video-pipeline.md+++ b/docs/video-pipeline.md@@@ -307,18 -652,47 +307,13 @@@ The still the clip was made from settle`video-set` passes `--spill auto` with each item's `canvas.png` as the reference (overridewith `--spill small|full`), so a green-free character loses the reflections while a-character that *is* green keeps its colour. The decision and its numbers are recorded in-the frames report under `spill`. The correction is the engine's own `despill_color` blend-model (observed = (1−k)·subject + k·key, solved for the subject), so colours without key-tint are untouched. `small` keeps the conservative tint threshold of 40; `full` lowers it to 8.-For `full`, a key hue requires every keyed channel to exceed every non-keyed-channel: `G − max(R, B)` for green, `min(R, B) − G` for magenta. This same-excess selects pixels for correction and drives the `auto` reference check, so yellow/cyan-are not mistaken for green, or red/blue for magenta. The average-channel tint-metric remains unchanged in `small` and the edge matte.--The blend fraction still uses the linear average-channel tint, not hue excess.-Full correction recovers mean brightness but does not amplify colour differences-within the keyed or non-keyed channel group. Otherwise a small red/blue imbalance-can become a strong secondary cast when much of the observed colour is key light.-This is bounded colour recovery, not reconstruction of the original material:-blue or purple already present without the key hue remains unchanged.--The `auto` reference test discounts dark pixels (all channels below 64) in the-matte's 4-pixel edge-unmix band. Such contamination along an antialiased outline-is weak evidence of an intentional material. Bright green/magenta accents still-count even on an edge. The report names the metric, band and dark-only policy.-Genuine key-coloured material above the 0.5% share still keeps the conservative-mode. Tiny accents or dark, edge-only material can fall below that reference test; use `--spill small` when preserving those is essential.--The reference is keyed on its subject window only. A canvas padded for motion room-(`video-canvas`) is mostly key, and the matte's memory grows with every pixel it keys,-so keying the whole canvas made the judgment cost grow with the padding: about 0.14 GiB-per megapixel, past 4 GiB for a 30-megapixel canvas. The window is the box of pixels the-hard cut cannot erase (farther than 96 from the declared key, and not the painted key's-own colour), plus one keyed pixel all round. The painted key is read on the whole still,-and with that ring the window gives exactly the counts the whole still gives, so the-decision does not change. The still itself is only decoded and read a band of rows at-a time. A window over 6 megapixels is keyed on every n-th pixel each way instead, so no-reference costs more than that to judge. The report records `reference_size`,-`reference_window` and `reference_stride` (1 = every pixel of the window).+character that *is* green keeps its colour. Tiny accents or dark, edge-only material can fall below that reference test; use `--spill small` when preserving those is essential.- ### Edges: `--decontam palette`-- `--spill` fixes key colour painted *into* the subject. The strands and outlines at its- edge are a different problem. H.264 4:2:0 has already averaged the key into the chroma of- anything one or two pixels wide, and despilling what is left turns thin red strands- orange. `video-frames --decontam palette` (also `video-set --decontam palette`) re-explains- each edge pixel as a blend of the local key background with one colour the subject owns,- and writes that colour at the pixel's observed luma. The- default `off` keeps frames byte-identical. Method, guards and measurements:- [chroma-alpha.md](chroma-alpha.md#decontam--give-the-edge-the-subjects-own-colour-back).+ ### Edges: `--decontam`++ `--spill` fixes key colour painted into the subject, but strands and outlines at its edge are a different problem: H.264 4:2:0 chroma mixes the key into anything one to three pixels wide, leaving an olive rim on red hair or turning it orange under despill. In this release, `video-frames` and `video-set` default to `--decontam auto` (before: `off`), which re-explains each edge pixel as a blend of the local key background with colours the subject owns and writes that colour at the pixel's observed luma, using the video fit and one palette per clip learned on the first frame. The video fit recovers no coverage on keyed pixels, examining band pixels only; across frames in a clip, near-threshold choices are held, changes of call are blended over frames, and still pixels are settled toward the fit to eliminate edge sparkle. Where `auto` cannot run (a white key or a subject with no interior deeper than 6 px) and under `--alpha-mode brightness`, it leaves frames exactly as keyed and records the reason in the report. On stderr, `video-frames` prints a one-line warning (and `video-set` lists it under `warnings`) when `auto` did not run on any frame, skipped frames, found key-coloured subject material, or triggered the key-coloured part guard.++ Two video guards keep the matte's bytes for edge pixels beside small key-coloured parts and for pixels matching the material right behind them. Pass `--decontam off` to keep the matte as it is and return 2.45.3 bytes exactly. Keying time rises from 1.14 s to 3.36 s a frame on an Intel i5-7500 at 1080x1920, and peak memory rises from about 400 MB to 1155 MB, about 365 MB more than `off` per megapixel of frame. Method, guards and measurements: [chroma-alpha.md](chroma-alpha.md#decontam--give-the-edge-the-subjects-own-colour-back).## 3b. Canvas shape for raised limbs and wide costumesdiff --cc sprite_gen/video/frames.pyindex 8fab9a9,fd2c629..d06e076--- a/sprite_gen/video/frames.py+++ b/sprite_gen/video/frames.py@@@ -440,38 -347,25 +450,41 @@@ def key_framescheck_edges: bool = True,spill: str = "small",allow_subject: bool = False,- decontam: str = "off",+ decontam: str = DECONTAM_DEFAULT,alpha_mode: str = "chroma",) -> dict[str, Any]:+ """Key `raw_files` into `keyed_dir` and read their edges; the report. The frames are keyed in a working folder+ beside it and handed over as `keyed_dir` when the run passes; a run that does not pass leaves them as+ `refused_dir(keyed_dir)` and no `keyed_dir`. A refusal raises `KeyingRefused`, carrying the report."""from . import effectif alpha_mode not in effect.ALPHA_MODES:raise SystemExit(f"video-frames: unknown --alpha-mode {alpha_mode!r}")- if alpha_mode == "brightness" and decontam != "off":- if alpha_mode == "brightness":- if decontam == "palette":- raise SystemExit("video-frames: brightness alpha does not use --decontam")- report = effect.key_frames(raw_files, keyed_dir)- if decontam == "auto":- report["decontam"] = {"mode": "auto", "applied_frames": 0, "reason": BRIGHTNESS_NO_KEY}- return report- if spill not in ("small", "full"):++ if alpha_mode == "brightness" and decontam == "palette":+ raise SystemExit("video-frames: brightness alpha does not use --decontam")+ if alpha_mode == "chroma" and spill not in ("small", "full"):raise SystemExit(f"video-frames: key_frames takes a resolved spill mode (small|full), got {spill!r}")if decontam not in DECONTAM_MODES:raise SystemExit(f"video-frames: unknown --decontam {decontam!r}; expected one of {', '.join(DECONTAM_MODES)}")+ work = _withdraw(keyed_dir)+ try:+ report = (effect.key_frames(raw_files, work) if alpha_mode == "brightness" else+ _key_chroma(raw_files, work, key=key, check_edges=check_edges, spill=spill, allow_subject=allow_subject,+ decontam=decontam))+ except BaseException:+ shutil.rmtree(refused_dir(keyed_dir), ignore_errors=True)+ work.rename(refused_dir(keyed_dir))+ raise++ if alpha_mode == "brightness" and decontam == "auto":++ report["decontam"] = {"mode": "auto", "applied_frames": 0, "reason": BRIGHTNESS_NO_KEY}+ shutil.rmtree(refused_dir(keyed_dir), ignore_errors=True)+ work.rename(keyed_dir)+ return report+++def _key_chroma(raw_files: list[Path], keyed_dir: Path, *, key: str, check_edges: bool, spill: str, allow_subject: bool,+ decontam: str) -> dict[str, Any]:clip_palette: dict[str, Any] | None = None+ clip_history: dict[str, Any] = {} # the last frame's calls, in clip orderdecontam_first: dict[str, Any] | None = Nonedecontam_totals = {name: 0 for name in DECONTAM_STAT_KEYS}decontam_applied = 0@@@ -478,43 -373,10 +492,47 @@@# Full correction lowers the tint threshold as well as lifting the size cap.spill_max = SPILL_FULL_FRACTION if spill == "full" else Nonespill_tint = SPILL_FULL_MIN_TINT if spill == "full" else None- keyed_dir.mkdir(parents=True, exist_ok=True)+ policy = "off" if not check_edges else ("subject-allowed" if allow_subject else "border")+ border: dict[str, Any] | None = Nonerows: list[dict[str, Any]] = []contacts: list[dict[str, Any]] = []- for src in raw_files:+ # What the border does not take, frame by frame, worded as a contact is (`_edge_contact_message`).+ untaken: list[dict[str, Any]] = []++ def summary() -> dict[str, Any]:+ report = {+ "frames": len(rows),+ "alpha_zero_pct_min": min(r["alpha_zero_pct"] for r in rows),+ "alpha_zero_pct_max": max(r["alpha_zero_pct"] for r in rows),+ "specks": {"dropped": sum(r["specks"] for r in rows), "frames": sum(1 for r in rows if r["specks"]),+ "min_fraction": SPECK_MIN_FRACTION, "min_px": SPECK_MIN_PX, "apart": SPECK_APART},+ "edge_contacts": contacts,+ "edge_policy": policy,+ **({"edge_border": border} if policy == "border" else {}),+ "rows": rows,+ }+ if decontam != "off" and decontam_first is not None:+ report["decontam"] = {+ "mode": decontam,+ "fit": DECONTAM_FIT,+ "palette_source": f"clip (learned on {decontam_first['frame']})",+ "palette": decontam_first["palette"],+ "palette_keyfree": decontam_first["palette_keyfree"],+ "key_material_share": decontam_first["key_material_share"],+ "material_spread": decontam_first["material_spread"],+ "edge_band": decontam_first["edge_band"],+ "applied_frames": decontam_applied,+ "totals": decontam_totals,+ }++ if decontam_skipped:++ report["decontam"] |= {"skipped_frames": len(decontam_skipped), "reason": decontam_skipped[0]}+ else:+ report["decontam"] = {"mode": decontam, "applied_frames": 0}++ if decontam_skipped:++ report["decontam"]["reason"] = decontam_skipped[0]+ return report++ for k, src in enumerate(raw_files):dst = keyed_dir / src.namestats = cutout(src, dst, key=key, spill_max_fraction=spill_max, spill_min_tint=spill_tint,spill_require_hue=spill == "full", decontam=decontam, decontam_fit=DECONTAM_FIT,@@@ -540,33 -402,13 +558,34 @@@decontam_applied += 1else:row["decontam"] = {"applied": False, "reason": done.get("reason")}+ decontam_skipped.append(str(done.get("reason")))if check_edges:contact = edge_contact(image)- if any(v > EDGE_MAX_PIXELS for v in contact.values()):+ touched = any(v > EDGE_MAX_PIXELS for v in contact.values())+ pixels = None+ if touched:chroma = stats.get("chroma_key")- contact.update(classify_edge_contact(Image.open(src), image, tuple(chroma) if chroma else None))+ painted = stats.get("chroma_key_painted")+ pixels = _edge_pixels(Image.open(src), image, tuple(chroma) if chroma else None, tuple(painted) if painted else None)+ residual = int(pixels["residual"].sum())+ contact.update(subject=int(pixels["contact"].sum()) - residual, residual=residual, rim=int(pixels["rim"].sum()))contact["key_painted"] = stats.get("chroma_key_painted")+ if policy == "border" and k == 0:+ border = _border(pixels, src.name)+ if border["sides"]:+ print(f"video-frames: the first frame's subject runs off the {_sides(border['sides'])} — read as the "+ "drawing's own border, where contact is accepted in every frame (`edge_border` in the report)",+ file=sys.stderr)+ if touched:+ if policy == "border":+ taken = _taken(pixels, border["sides"])+ off = pixels["contact"] & ~taken+ contact["border"] = int(taken.sum())+ contact["off"] = {side: int((off & pixels["bands"][side]).sum()) for side in SIDES}+ if off.any():+ lone = int((off & pixels["residual"]).sum())+ untaken.append({"frame": src.name, **contact["off"], "subject": int(off.sum()) - lone, "residual": lone,+ "key_painted": contact["key_painted"]})contacts.append({"frame": src.name, **contact})row["edge"] = contactif hist[0] == 0:@@@ -588,11 -456,34 +607,39 @@@return report+def _sides(sides: list[str]) -> str:+ return (f"{sides[0]} edge" if len(sides) == 1 else+ f"{', '.join(sides[:-1])} and {sides[-1]} edges")+++ def decontam_warning(decontam: dict[str, Any]) -> str | None:+ """The line to read when the edge pass did less than the default promises, or met the key's+ own colour: `auto` left frames as the matte keyed them, the subject owns key-coloured material,+ or the guard kept the edge beside a small key-coloured part. None when there is nothing to look+ at (the pass off, or brightness alpha)."""+ mode = decontam.get("mode")+ if mode in (None, "off") or decontam.get("reason") == BRIGHTNESS_NO_KEY:+ return None+ if not decontam.get("applied_frames"):+ return (f"decontam {mode} did not run ({decontam.get('reason')}): the frames are the matte's, "+ "the same as --decontam off")+ notes = []+ if decontam.get("skipped_frames"):+ notes.append(f"it left {decontam['skipped_frames']} frame(s) as the matte keyed them ({decontam['reason']})")+ share = float(decontam.get("key_material_share") or 0.0)+ kept = int((decontam.get("totals") or {}).get("key_part_kept_px") or 0)+ if not decontam.get("palette_keyfree", True):+ notes.append(f"the subject owns key-coloured material ({share:.1%} of its interior), "+ "so an edge may be repainted in the key's colour too")+ elif kept:+ # a few key-hued interior pixels deep inside (codec noise) guard no edge and are not worth a line+ notes.append(f"the subject has small key-coloured parts: {kept} edge pixel(s) beside them kept as the matte "+ "keyed them, and a thin detail of that colour farther out may be repainted")+ if not notes:+ return None+ return f"decontam {mode}: {'; '.join(notes)} — look at those edges; --decontam off keeps the matte as it is"++def _worst(contacts: list[dict[str, Any]]) -> tuple[dict[str, Any], str]:worst = max(contacts, key=lambda c: c["top"] + c["left"] + c["right"])return worst, f"(worst {worst['frame']}: top {worst['top']} / left {worst['left']} / right {worst['right']} px)"