spine-parts 2.36.0 → 2.38.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/docs/AUTHORING.md CHANGED
@@ -162,6 +162,7 @@ read by no CPU stage).
162
162
  | `assemble.keep_under_occluders` | assemble | **authored**, optional array of unique source part names from `assemble.plan`, default `[]` (issue #825). For each named part, keep its own See-through RGBA where the front-most covering part in the final draw stack has alpha greater than 0 and below `CORE_ALPHA` (250), including a cover in the other run. Covers at raw alpha <= 8 are ghosts and are not kept under; a ghost-cleaned sample with final alpha 0 is absent cover and does not trigger restoration. Only original opaque own-layer samples are restored after source projection/closing and protected from later seam re-take; merged/rim, cap, under-fill and authored replacement pixels are excluded. This keeps their existing provenance and makes no holes; fully opaque cover and absent cover keep the old path. Cuts and limb pieces inherit the source part's protection. Unknown names: `CONFIG_NAME_RESOLVES`; duplicates: `CONFIG_PART_UNIQUE`; invalid shape: `CONFIG_FIELD_TYPE`. Inspect the part's own amodal layer first: this handle preserves its existing content and cannot complete a missing pixel — in particular, it does not close a motion opening inside the figure (`figure_openings` / [Openings inside the figure on undeclared layer pairs](#openings-inside-the-figure-on-undeclared-layer-pairs-issue-933)) where the lower layer has no opaque core under an opaque upper layer (measured with every `assemble.plan` part named in `keep_under_occluders`: `0` of `1` pair-animation warnings across `demo`'s eight animations closed, with `hair_back\|handwear_r` on `hop` frame `5` staying at `40` cells over `28` allowed in `38x70` world units at `2.517` world units/cell, while `scarf` reads `CLEAR` (`0` warnings) both with and without `keep_under_occluders`; use `assemble.extend_painting` when the lower part lacks opaque source material under an opaque upper cover). Example: `"keep_under_occluders": ["shin_r"]`. |
163
163
  | `assemble.require_hidden_extent` | assemble, build | **authored**, optional array of unique `{part, occluder}` source-name pairs from `assemble.plan` (issue #1047). The distinct occluder must draw after the part. Before cleanup, projection, underfill, cuts or limb splitting, the original selected source is normalized to the rig grid. Own support is alpha >8. Its enclosed holes are `fillHoles(support) \ support`, using four-connected exterior background. Any hole cell under the resolved front-most named occluder (alpha >8) refuses `ASSEMBLE_HIDDEN_EXTENT_ABSENT`. Zero holes with measurable filled-support overlap passes. No overlap or unavailable original ancestry refuses `ASSEMBLE_HIDDEN_EXTENT_UNMEASURED`. A region take's output (`assemble.take`) counts as the selected source. Cover resolves over `assemble.plan` source families only; cut slots are not resolved as cover, which is a stated limit. Omitted or `[]` adds no reading or output. This is a source-support bar reached by build at assemble. See [Original hidden extent required](#original-hidden-extent-required). |
164
164
  | `assemble.occluders` | assemble, build | **authored**, optional (issues #1230, #1237, #1241, #1246, #1251, #1259): `[{image, sha256, under, over?, plate?, part?, grow?, guard?, rgb_within}]` — an RGBA PNG of what stands in front of the character on the painting's grid (`image`, relative to the config's directory; another size refuses `ASSEMBLE_OCCLUDER_GRID`), its bytes' sha256 (`CONFIG_OCCLUDER_SHA256`), the plan parts it stands over (`under`, `CONFIG_NAME_RESOLVES`), optional distinct plan parts that draw this occluder (`over`, `CONFIG_NAME_RESOLVES`, `CONFIG_PART_UNIQUE`), optional receipted plate directory (`plate`, `ASSEMBLE_OCCLUDER_PLATE_*`), optional part name (`part`, `CONFIG_FIELD_TYPE`, `CONFIG_PART_NAME`, `CONFIG_PART_UNIQUE`, `CONFIG_PART_ATTACHED`), optional non-negative integer rig-px dilation radius (`grow`, `CONFIG_FIELD_TYPE`; absent means `0`), optional non-negative integer rig-px under-keep dilation radius (`guard`, `CONFIG_FIELD_TYPE`; absent means `0`), and an integer 0–255 (`rgb_within`). After any take and before projection, a pixel of an `under` part's selected layer at alpha above 128, where the occluder's alpha is above 0, within `rgb_within` (max channel) of the painting there, is the occluder's colour copied into the layer: `assemble` prints `WARN ASSEMBLE_OCCLUDER_COLOUR_COPIED` with the part, the rig px count and the first pixel. On the rig grid, occluder membership is the boolean core where the occluder image's alpha is strictly above `128` (`COPIED_ALPHA_ABOVE`), dilated by `growMask`'s `(2 * grow + 1)^2` square when `grow > 0` (`parts.json` records top-level `occluder_grow` with `{occluder, image, grow, covered_px_before, covered_px_after}` for each entry with `grow > 0`; the occluder-split take and `occluders[i].plate` do not read `grow`); holding is a front part's alpha at or above `250` (`CORE_ALPHA`). Under `--project visible`, an `under` part's pixels (and every cut piece or limb segment derived from it) inside the under-keep mask — the `alpha > 128` core dilated by `max(grow, guard)` via `growMask`'s `(2 * r + 1)^2` square (`parts.json` records top-level `occluder_guard` with `{occluder, image, guard, guarded_px_before, guarded_px_after}` for each entry with `guard > 0`; `guard` paints nothing, changes neither `occluders[i].part` nor `ASSEMBLE_OCCLUDER_UNHELD`, has no effect when `guard <= grow` though the record is still written, and is not read by the occluder-split take or `occluders[i].plate`) — keep the base run's surface rather than projecting `--source`. When `over` is declared, each `(over, under)` pair in an entry draws `over` in front of `under` regardless of mixed-run depth or two-run role band (`ASSEMBLE_OCCLUDER_DRAW_ORDER` if `assemble.plan` draws `over` behind `under`, `ASSEMBLE_OCCLUDER_DRAW_CYCLE` on contradictory `over`/`under` cycles, `ASSEMBLE_OCCLUDER_OVER_TAKEN` if an `over` part's layer is not taken by `assemble.take`). When `part` is declared, `assemble` emits a `painting:<part>` part (`parts/<part>.png`, placed immediately before the first slot of any `over` part of that entry across `full` and `head`, counting pieces cut from an `over` part — "before the first `over` part" wins when a piece derived from `under` sits after `over`, and when `over` is omitted the part is placed after the last slot derived from `under`) holding `--source` at alpha `255` over the occluder membership (`alpha > 128`, after `grow`) minus the pixels held at `alpha >= 250` (`CORE_ALPHA`) by every part drawn in front of it (`ASSEMBLE_OCCLUDER_EMPTY` if `0` rig px remain); when `part` is omitted and any occluder pixel (`alpha > 128`, after `grow`) is not held at `alpha >= 250` (`CORE_ALPHA`) by a part drawn in front of it, `assemble` prints `WARN ASSEMBLE_OCCLUDER_UNHELD` with the count and first pixel. |
165
+ | `assemble.edited_parts` | assemble, build | **authored**, optional (issue #1278): `{dir, receipts: [{part, file, sha256, from_sha256, editor}]}`. Replaces named base-plan parts with final rig-pixel PNG files after all automatic passes. `dir` is relative to the config; `file` is relative to `dir` and must not be absolute. Keeps names, boxes and draw order. The current assembled PNG must match `from_sha256`; the edited file must match `sha256` and the assembled dimensions. See [Edited rig-space parts](#edited-rig-space-parts-assembleedited_parts-issue-1278). |
165
166
  | `assemble.editor_receipts` | assemble, build | **authored**, optional (issue #946): `{receipts: [{file, sha256, from_sha256, editor}], required?, trace_parts?}`. Each receipt records an image edited in an image editor; `file` (relative to the config's directory) must exist and hash to `sha256`, verified at assemble; `from_sha256` and `editor` are the author's declaration, held only to form. With `required: true`, every author-made layer, hidden-art layer, cut `under` and limb `cap` the build reads, alternate sets' runs included, needs a receipt whose `sha256` is its file's. With `trace_parts: true` (issue #947), every part's pixels must trace to a layer of the split or to a receipted image: the receipts are demanded as under `required`, and every shape the config draws through a part — a cut's `polygon`, `seethrough.arm_split`, a limb's `split.line`, a patch's `box`, a painting extension's `band` — is refused (`ASSEMBLE_PART_SOURCE`). Absent, no file is read and no byte moves. See [Editor receipts](#editor-receipts-assembleeditor_receipts-issue-946) and [Part sources](#part-sources-assembleeditor_receiptstrace_parts-issue-947). |
166
167
  | `limbs` | assemble (the cut and the caps), rig (through `regions`), check (`LIMB_ONE_BONE`) | **proposed** by `propose --keypoints` (issue #349), then checked: `{<limb>: {segments: [{part, from, bone}, {part, from, bone, joint, range?, cap?, edge?, cap_shape?, cut_band?, hybrid?}, …], split?, layout?, front?}}`, the upper segment first. The rule is *Limbs: cut at their joints* below the table. `part` is a new part (`CONFIG_PART_NAME`, `CONFIG_PART_UNIQUE` against the plan, patches, cuts and every other limb part); `from` a plan part or a cut's piece (`CONFIG_NAME_RESOLVES`) — the layer the segment's pixels come from, which is cut into the limb parts and is not itself made: a `meshes` or `regions` entry for it is `CONFIG_NAME_RESOLVES`, and the segments of one limb that take one part are consecutive (`CONFIG_LIMB_FROM_RUN`); `bone` a declared bone, each segment's the child of the one before (`CONFIG_LIMB_BONES_CHAIN`); the upper segment names no `joint`, `range`, `cap`, `edge`, `cap_shape` or `cut_band` (`CONFIG_KEY_KNOWN`), every other names its `joint` (`CONFIG_FIELD_PRESENT`) — the joint is its bone's origin; `range` is `[min, max]` degrees from rest with `min <= 0 <= max` (`CONFIG_LIMB_RANGE`), which `assemble` writes into the lower part's `parts.json` record and `check` poses the joint at — its two ends and its middle — reading the seam there (`SEAM_OVER_RANGE`, issue #360; rig-c needs no rotation limit); `cap` a PNG path relative to the config's directory (`CONFIG_FIELD_TYPE`); `edge` `"feather"` (issue #360), the one value it takes, and `cap_shape` `"disc"` (issue #360) or `"ball"` (issue #579) (`CONFIG_FIELD_TYPE` on any other) — the cut's geometry at that joint, *Limbs: cut at their joints* below; absent, the cut is hard and the cap the layer's half-disc of half the limb's width; `cut_band` a whole number of px, 1 or more (`CONFIG_FIELD_TYPE`), on a segment that takes the segment above's part — between two layers nothing is cut, so a band there is `CONFIG_KEY_KNOWN` — places the cut within that many px of the joint line (issue #360, *Limbs: cut at their joints*); absent, the cut is the joint line. Each limb part is attached like any part — `regions.<part>`, which must be the segment's `bone` (`CONFIG_LIMB_BONE`), or a mesh, which `check` holds to that bone alone (`LIMB_ONE_BONE`). With `limbs`, `assemble` reads `bones` too (`CONFIG_FIELD_PRESENT` without it). Absent, nothing is cut at a joint and no byte of any output moves. Optional `front` (issue #664), `{parts: [<own segment part>, …], after: "<produced part>"}`, gives each named segment a second slot `<part>_front`, empty at setup, placed after `after`'s slot family, for a gesture set to draw on (`CONFIG_FRONT_SCOPE`, `CONFIG_FRONT_NAME`, `CONFIG_FRONT_LAYOUT`; *Front slots (issue #664)* below) |
167
168
  | `bones` | rig; `propose --from-config` | **proposed** by `propose`, then corrected. A single bone `{name, parent, at, tip?}` or a chain `{chain, parent, points, tip, link_inherit?}` whose links are named `<chain>0 … <chain>n`. Parents come before children. In `rig.json` each link is **turned along its chain** — `rotation` is the direction from its origin to the next link's (the last link's to `tip`) and `length` that distance (issue #73), so a physics constraint added downstream finds a lever; under `--idle-keys ctl` the link's `<link>_ctl` carries the turn and the length and the link sits at local rotation 0 beneath it. A single bone with a `tip` is turned the same way, towards its tip, with that distance as its length (issue #239); a tip on the bone's own origin is refused (`RIG_TIP_DISTINCT`). The five face bones `eye_r`, `eye_l`, `brow_r`, `brow_l` and `mouth` (by name, when one has no tip of its own) are turned to the eye line — the line through the origins of `eye_r` and `eye_l` as `bones` writes them, read image-left to image-right, drawn when parts.json holds both an `eyewhite-r` and an `eyewhite-l` part — so the blink's `scaley` squashes across the eye line on a tilted head; move an eye bone and the line moves with it. With one eyewhite or none, or an eye bone missing, the rig stage's `face axis:` line says so and they keep the page's axes. A bone under a face bone keeps the face's axis. With the line, `rig.json` also declares `invariants.axes` — one entry, `"face"`, through `eye_r` and `eye_l`, holding the turned face bones (and their controls) — so rig-c's gate holds the build to the line; the line is the one rigc draws through the same two bones, so the tolerance is only the float floor — the largest gap the emitted (float32) bones have to it, rounded up to 6 places plus one 6-place unit — and the `face axis:` line prints it. With the line the rig stage also adds `head_up` (issue #250): a slotless bone under `head`, at head's origin, turned to the eye line + 90 degrees and as long as the eye midpoint lies from head's origin along that axis — the head's frame, which a rule that needs it reads; `head` keeps its own frame, so no key on it or under it changes meaning, and a config bone of that name is refused (`RIG_HEAD_UP_NAME_FREE`). A face bone with its own `tip` is held too (issue #258), in a second entry, `"face_tips"`, when its tip lies along the line within whole-pixel rounding — a tip written in whole pixels sits at most sqrt(2)/2 px off the point of the line it stands for, so its direction may sit up to asin((sqrt(2)/2) / length) degrees off — with its tolerance measured the same way; a tip further off is the bone's own axis, and the `face axis:` line names it with its gap and that bound. A failure is rig-c's `A51_BONES_LIE_ALONG_THEIR_DECLARED_AXIS` line, which names the bone and the fix (rig-c's `docs/AUTHORING.md` §3.7 and §5.2); with no line no entry is written and A51 reports SKIP. Every region on a turned bone is turned back, so the setup pose does not move. Any other single bone keeps world rotation 0; one whose parent is a link is turned back upright. A single bone may declare `inherit` (issue #348): what it takes from its parent's transform, one of rig-c's own mode names exactly as rig-c's table spells them — `normal`, `onlyTranslation`, `noRotationOrReflection`, `noScale`, `noScaleOrReflection` (rig-c's `RigBone.inherit`) — written to that bone in `rig.json` as declared; any other spelling, `"NoScale"` included (the runtime would fold its first letter; nothing here folds or maps), is refused (`CONFIG_BONE_INHERIT`), and a chain takes no `inherit` (`CONFIG_KEY_KNOWN`). A chain may instead declare `link_inherit` (issue #369), an object mapping its own expanded link names to those same modes, for example `"link_inherit": {"leg_r1": "noScale"}`. Only the named link changes; omitted links inherit normally. A key outside this chain is `CONFIG_NAME_RESOLVES`, with this chain's valid link names in the detail; a non-object or non-string mode is `CONFIG_FIELD_TYPE`, and another mode spelling is `CONFIG_BONE_INHERIT`. The mode is forwarded to the expanded link, or to its control under `--idle-keys ctl`, by the same rule as a single bone. This is an authored opt-in: `propose` does not add it. Its setup rotation is the turn from where rig-c's own poser puts the bone with no rotation of its own under that mode, so it still stands upright (or along its tip) at the setup pose. Where the idle gives the bone a `<bone>_ctl`, the mode goes on the control: the control is the bone the parent's rotation reaches, and the bone under it inherits normally, so the idle's keys moved onto the control still turn it. A foot that does not take its shin's rotation (`noRotationOrReflection` or `onlyTranslation`) keeps its shoe level while the leg is posed (`FEET_STAY_LEVEL`, §7); which mode is the author's. `noScale` keeps a shin or shoe's shape under a scaled parent but still takes the parent's rotation: a shoe that must also stay level needs a separate rotation constraint, for example a transform constraint from an unrotated bone. This does not change the proposed feet's existing inheritance or `FEET_STAY_LEVEL` default. An automatic mesh weighted through a bone with a mode other than `normal` gets no derived amplitude (its row names the bone) and no residual envelope (rig-c's `SKINNING_RANGE_UNSUPPORTED`). Absent, `rig.json` carries no `inherit` and no byte moves |
@@ -1049,6 +1050,92 @@ receipt is demanded, and a run with no author-made or hidden-art layer, no
1049
1050
  `under` and no `cap` demands none either. Absent the block, no file is read and
1050
1051
  every output is byte-identical to a build without it.
1051
1052
 
1053
+ ### Edited rig-space parts (`assemble.edited_parts`, issue #1278)
1054
+
1055
+ Use this block for a PNG edited at the exact crop and scale written by
1056
+ `assemble`, such as an alpha edge retouch. Author-made run-space layers and
1057
+ `assemble.editor_receipts` keep their existing behavior; a receipt ledger
1058
+ alone does not apply a replacement.
1059
+
1060
+ ```json
1061
+ "edited_parts": {
1062
+ "dir": "retouched",
1063
+ "receipts": [{
1064
+ "part": "sleeve_r",
1065
+ "file": "sleeve_r.png",
1066
+ "sha256": "<sha256 of the edited PNG file bytes>",
1067
+ "from_sha256": "<sha256 of this config's unedited assembled part PNG>",
1068
+ "editor": "<the image editor used>"
1069
+ }]
1070
+ }
1071
+ ```
1072
+
1073
+ The block belongs in `assemble`. Both fields are required; `receipts` may be
1074
+ empty. Every receipt takes all five fields. `part` must name an existing part
1075
+ in the base plan, once only. `dir` resolves relative to the config's directory;
1076
+ `file` resolves relative to that directory and must be a relative path.
1077
+ Hashes are lowercase SHA-256 of encoded file bytes, including PNG metadata;
1078
+ `from_sha256` is checked against the PNG the normal assemble would write for
1079
+ this config, rather than merely accepted as a declaration. `editor` remains
1080
+ the author's non-empty declaration; the tool cannot verify which editor was
1081
+ used. The decoded width and height must equal the assembled part's box.
1082
+ A changed crop, scale, name or order needs a plan or cut change instead.
1083
+
1084
+ Replacement occurs after projection, drift checks, seam override, ghost
1085
+ cleanup, paintingEdge and final region restoration. No automatic pass runs
1086
+ on the replacement afterward. The output part PNG is the verified file's
1087
+ original bytes, not a decoded and re-encoded copy. Every other base part
1088
+ keeps its bytes, name and box. Recomposite and final output measurements are
1089
+ calculated from the replaced images in their recorded order and boxes.
1090
+ Reports describing upstream source coverage or allocation retain their
1091
+ upstream-stage meaning; a receipt does not turn them into final edit attribution.
1092
+ Alternate sets build their own declared art without this base-only block;
1093
+ assets they inherit from the base use the edited base image.
1094
+
1095
+ Prepare cut fill masks before recording rig-space edits. Mask preparation
1096
+ removes cut `under` inputs, so its baseline may differ from normal assemble;
1097
+ a receipt made for the normal build can then be refused by
1098
+ `ASSEMBLE_EDITED_PART_BASELINE`.
1099
+
1100
+ The part keeps its original `from` source identity. Its optional
1101
+ `provenance.edited_part` records `edit: "edited_parts[i]"`, `dir`, the complete
1102
+ `receipt` (`part`, `file`, both hashes and `editor`) and these exact RGBA-position
1103
+ counts relative to the normal assembled PNG:
1104
+
1105
+ | field | population |
1106
+ | --- | --- |
1107
+ | `changed_px` | Every position with any differing RGBA channel, including transparent RGB changes and deleted pixels. |
1108
+ | `changed_counted_px` | Changed positions whose final alpha is above 8. |
1109
+ | `changed_excluded_px` | Changed positions whose final alpha is at most 8, including deletions. Together with `changed_counted_px`, sums to `changed_px`. |
1110
+ | `removed_opaque_px` | Positions whose baseline alpha was above 8 and final alpha is at most 8; a subset of `changed_excluded_px`. |
1111
+
1112
+ The existing value partition is preserved:
1113
+ `unchanged_layer_px + hand_px + automatic_px = opaque_px`. `hand_px` counts
1114
+ surviving counted pixels attributed to hand edits; it is not `changed_px`.
1115
+ Raw-value equality takes precedence, and unchanged RGBA retains its previous
1116
+ writer. Hand-attributed replacement entries use `edited_parts[i]` in
1117
+ `provenance.edits`. The whole-file receipt covers unchanged and transparent
1118
+ positions separately from that partition. With `assemble.stage_map`, the
1119
+ replaced sidecar entry also carries `edited_part`; its runs keep the normal
1120
+ final-alpha partition and resolve replacement writer IDs through the sidecar's
1121
+ `edits` list. With `editor_receipts.trace_parts`, the complete edited file is
1122
+ receipt-associated; this does not exempt other config shapes or baseline
1123
+ inputs from their existing source/receipt checks.
1124
+
1125
+ All replacement refusals happen before output emission, including when an
1126
+ output directory already contains a successful build. The folder and every
1127
+ existing file remain unchanged. Each code and its remedy is listed in
1128
+ [CHECKS](https://github.com/rig-c/parts/blob/main/docs/CHECKS.md#edited-rig-space-parts).
1129
+ Absent the block, no edited file is read, no new metadata is written and the
1130
+ default output retains its bytes.
1131
+
1132
+ Replacement does not relax rig-c's gate or `check`'s existing seam bars.
1133
+ For the public-example edit control, report raw setup-pose-versus-recomposite
1134
+ mean and any-difference pixel count beside the same no-block build: both
1135
+ edited figures must be no worse than baseline. A baseline of zero mean and
1136
+ zero differing pixels therefore requires zero for both edited figures too.
1137
+ Rounded `check.json` seam figures alone do not establish those raw values.
1138
+
1052
1139
  ### Part sources (`assemble.editor_receipts.trace_parts`, issue #947)
1053
1140
 
1054
1141
  A part carved out of a layer along a line the author drew is not a part the
@@ -5575,6 +5662,13 @@ recorded transform. The record fields and sampling formula are specified in
5575
5662
  | <a id="ASSEMBLE_TAKE_UNIQUE"></a>`ASSEMBLE_TAKE_UNIQUE` | repeated donor for one target tag at runtime | declare each target run/tag once |
5576
5663
  | <a id="CONFIG_TAKE_UNIQUE"></a>`CONFIG_TAKE_UNIQUE` | config selects the same target run/tag more than once | retain one donor per target tag |
5577
5664
  | <a id="ASSEMBLE_PART_SOURCE"></a>`ASSEMBLE_PART_SOURCE` | `assemble.editor_receipts.trace_parts` is `true` and a part's pixels are decided by a shape drawn in the config — an `assemble.cuts` (or an alternate set's `cuts`) `polygon`, `seethrough.arm_split`, a limb's `split.line`, an `assemble.patches` `box`, an `assemble.extend_painting` `band`; the object names the part and where the shape is declared, the detail the shape found (issue #947) | `config.json`: remove that entry and paint the piece as an author layer (`author:<label>`) in an image editor with its receipt in `assemble.editor_receipts.receipts`, or take the part whole from a layer of the split (a limb split may use `"edge": "painting"`) |
5665
+ | <a id="ASSEMBLE_EDITED_PART_UNKNOWN"></a>`ASSEMBLE_EDITED_PART_UNKNOWN` | A receipt names a part outside the base plan. | Use the existing base-plan part name; a new name needs a plan change. |
5666
+ | <a id="ASSEMBLE_EDITED_PART_FILE"></a>`ASSEMBLE_EDITED_PART_FILE` | The receipt file does not exist at dir/file. | Correct the config-relative dir or the directory-relative file, or supply that file. |
5667
+ | <a id="ASSEMBLE_EDITED_PART_SHA256"></a>`ASSEMBLE_EDITED_PART_SHA256` | The edited file bytes do not match sha256. | Use the intended edited file and record its exact file hash. |
5668
+ | <a id="ASSEMBLE_EDITED_PART_BASELINE"></a>`ASSEMBLE_EDITED_PART_BASELINE` | The current normal assembled part PNG does not match from_sha256. | Rebase the edit on this config's current assembled part and record that original file hash. |
5669
+ | <a id="ASSEMBLE_EDITED_PART_SIZE"></a>`ASSEMBLE_EDITED_PART_SIZE` | The edited PNG width or height differs from the assembled box. | Edit at the original crop and rig-pixel size; use a plan change for a new box. |
5670
+ | <a id="ASSEMBLE_EDITED_PART_DUPLICATE"></a>`ASSEMBLE_EDITED_PART_DUPLICATE` | More than one receipt names the same part. | Keep exactly one receipt for that part. |
5671
+ | <a id="ASSEMBLE_EDITED_PART_DECODES"></a>`ASSEMBLE_EDITED_PART_DECODES` | The verified file cannot be decoded as a PNG. | Supply a valid PNG and update its receipt hash. |
5578
5672
  | <a id="ASSEMBLE_EDITOR_RECEIPT_MISSING"></a>`ASSEMBLE_EDITOR_RECEIPT_MISSING` | `assemble.editor_receipts.required` (or `trace_parts`, issue #947) is `true` and an edited image the build reads — an author-made or hidden-art layer of a base or alternate run, a cut `under`, a limb `cap` — has no receipt whose `sha256` is its file's; the detail gives the path and the sha256 found (issue #946) | edit the image in an image editor and add its receipt to `config.assemble.editor_receipts.receipts`; never generate or patch it in code |
5579
5673
  | <a id="ASSEMBLE_EDITOR_RECEIPT_SHA256"></a>`ASSEMBLE_EDITOR_RECEIPT_SHA256` | a receipt's file hashes to another sha256 than the receipt records; the detail gives both | the receipt's `sha256`, or the file: it changed after the receipt was written, or the receipt names another file |
5580
5674
  | <a id="ASSEMBLE_EDITOR_RECEIPT_FILE"></a>`ASSEMBLE_EDITOR_RECEIPT_FILE` | a receipt's `file` names no file, relative to the config's directory | that receipt's `file` |
@@ -5608,6 +5702,12 @@ recorded transform. The record fields and sampling formula are specified in
5608
5702
  | <a id="ASSEMBLE_OCCLUDER_UNHELD"></a>`ASSEMBLE_OCCLUDER_UNHELD` (WARN) | `assemble.occluders[i].part` is omitted, and pixels of the declared occluder core (`alpha > 128`, `COPIED_ALPHA_ABOVE`, after any `grow`) are not held at `alpha >= 250` (`CORE_ALPHA`) by any part drawn in front of it; gives the unheld rig px count and first pixel | declare `part` on `config.assemble.occluders[i]` (and attach it in `regions`) to hold the remaining occluder pixels from `--source`, or take the missing front layer in `over` |
5609
5703
  | <a id="ASSEMBLE_TAKE_SPLIT_OCCLUDER"></a><a id="ASSEMBLE_TAKE_SPLIT_EMPTY"></a>`ASSEMBLE_TAKE_SPLIT_OCCLUDER`, `ASSEMBLE_TAKE_SPLIT_EMPTY` | an occluder-split `assemble.take` entry whose `occluder` index does not exist in `config.assemble.occluders`, whose `part` is not in that entry's `under`, or whose `part` is in its `over`; a split take whose `covered_px` (base layer at `alpha > 8` where occluder `alpha > 128`) or `visible_px` (donor layer at `alpha > 8` where occluder `alpha <= 128`) is `0` | point `occluder` at the `config.assemble.occluders` entry that lists `part` in `under` (and not in `over`); use a base run with opaque material under the occluder and a donor run with opaque material outside it |
5610
5704
  | <a id="CONFIG_HIDDEN_EXTENT_ORDER"></a>`CONFIG_HIDDEN_EXTENT_ORDER` | `assemble.require_hidden_extent` names the same source as part and occluder, or names an occluder drawn before the part | declare distinct source parts with the occluder after the part in `assemble.plan` |
5705
+ | <a id="PARTS_PAINTING_REFERENCE_INPUT"></a>`PARTS_PAINTING_REFERENCE_INPUT` | A named input is unreadable, unsealed, a symlink or invalid JSON/PNG | Restore the explicit frozen regular input |
5706
+ | <a id="PARTS_PAINTING_REFERENCE_HASH"></a>`PARTS_PAINTING_REFERENCE_HASH` | A named input differs from its expected SHA-256 | Restore its sealed bytes |
5707
+ | <a id="PARTS_PAINTING_REFERENCE_FRAME"></a>`PARTS_PAINTING_REFERENCE_FRAME` | The recorded run mode, padding or frame conflicts with the sealed source/config | Supply the matching original source/config and recorded producer manifest |
5708
+ | <a id="PARTS_PAINTING_REFERENCE_SCHEMA"></a>`PARTS_PAINTING_REFERENCE_SCHEMA` | The named declaration breaks its six-key grammar | Restore the producer sidecar |
5709
+ | <a id="PARTS_PAINTING_REFERENCE_OUTPUT"></a>`PARTS_PAINTING_REFERENCE_OUTPUT` | A named output conflicts or is unreadable | Preserve its bytes and resolve the collision |
5710
+ | <a id="PARTS_PAINTING_REFERENCE_WRITE"></a>`PARTS_PAINTING_REFERENCE_WRITE` | Reference publication failed | Preserve existing files and retry with the same sealed inputs |
5611
5711
  | <a id="DIFF_COMPONENTS_INPUT"></a>`DIFF_COMPONENTS_INPUT` | `diff-components` needs readable PNG stack/painting/part images, a writable `--out` target when writing, explicit parts, positive integer floor, a finite threshold in [0,255], matching native dimensions and valid coverage/domain inputs; flags must be unique and known, with nonempty values | Supply the named missing or invalid input; no resampling or inferred figure is performed |
5612
5712
  | <a id="DIFF_COMPONENTS_BINDING"></a>`DIFF_COMPONENTS_BINDING` | The shipped report reader found a stack or painting SHA-256 different from the supplied bytes; found and required digests are printed | Regenerate against the bytes being reviewed |
5613
5713
  | <a id="DIFF_COMPONENTS_REPORT"></a>`DIFF_COMPONENTS_REPORT` | Invalid report JSON/spec, or its exhaustive inventory, definition, paths, domain or coverage differs from remeasurement; capped inventories are refused | Regenerate the complete versioned report against the same input paths, bytes, parts and figure domain |
package/docs/STABILITY.md CHANGED
@@ -314,7 +314,7 @@ part name, `[i]` an entry of a list):
314
314
  - **generation.control.skeleton**, the pose file it names when it is no built-in — required: `width`, `height`, `points`
315
315
  - **seethrough** — required: `resolution`, `steps`, `seed`, `offload`; optional: `head_box`, `arm_split`
316
316
  - **seethrough.arm_split** — required: `order`, and one of `x` or `line` (issue #439)
317
- - **assemble** — required: `rig_scale`, `plan` (from plain `assemble` on); optional: `seam`, `project`, `ground`, `extend_below_crop`, `patches`, `cuts`, `alternates`, `head_face_underfill`, `yield_refused`, `stage_map`, `keep_under_occluders`, `require_hidden_extent`, `extend_painting`, `edge_splits`, `take`, `editor_receipts`, `occluders`
317
+ - **assemble** — required: `rig_scale`, `plan` (from plain `assemble` on); optional: `seam`, `project`, `ground`, `extend_below_crop`, `patches`, `cuts`, `alternates`, `head_face_underfill`, `yield_refused`, `stage_map`, `keep_under_occluders`, `require_hidden_extent`, `extend_painting`, `edge_splits`, `take`, `editor_receipts`, `edited_parts`, `occluders`
318
318
  - **assemble.edge_splits[i]** — required: `over`, `under`, `band`
319
319
  - **assemble.require_hidden_extent[i]** — required: `part`, `occluder`
320
320
  - **assemble.occluders[i]** — required: `image`, `sha256`, `under`, `rgb_within`; optional: `over`, `plate`, `part`, `grow`, `guard` (issues #1230, #1237, #1241, #1246, #1251, #1259)
@@ -326,6 +326,8 @@ part name, `[i]` an entry of a list):
326
326
  - **assemble.take[i].reference** — required: `sha256`; optional: `source`, `painting` (issue #1031). Exactly one of `source: true` or a config-relative `painting` PNG is required. The reference governs colour only and geometry follows `--source`. A region take requires an opaque `--source` because its donor must match the run input and the inputs command refuses see-through paintings, so flatten the plate first.
327
327
  - **assemble.editor_receipts** — required: `receipts`; optional: `required` (issue #946, additive), `trace_parts` (issue #947, additive)
328
328
  - **assemble.editor_receipts.receipts[i]** — required: `file`, `sha256`, `from_sha256`, `editor` (issue #946)
329
+ - **assemble.edited_parts** — required: `dir`, `receipts` (issue #1278; directory relative to the config)
330
+ - **assemble.edited_parts.receipts[i]** — required: `part`, `file`, `sha256`, `from_sha256`, `editor` (issue #1278; file relative to the edited-parts directory)
329
331
  - **assemble.patches[i]** — required: `name`, `box`, `alpha`, `draw`
330
332
  - **assemble.patches[i].draw**, when an object — required: `before`
331
333
  - **assemble.cuts[i]** — required: `from`, `into`, `polygon`, `draw`, `overlap`; optional: `under`, `under_fill` (issue #1230: `under` is a path string or an object)
@@ -547,6 +549,91 @@ their existing whole-file parts.json identity contract; regenerate them.
547
549
  Check's setup-painting comparison still flattens over its backdrop at source
548
550
  resolution before resizing; it can differ for non-opaque paintings.
549
551
 
552
+
553
+ ### Painting reference writer
554
+
555
+ `@rig-c/parts/src/painting-reference.ts` exports
556
+ `writePaintingReference({ manifest, source, config })`. Each input is a
557
+ `{ path, sha256 }` seal with an explicit expected lowercase SHA-256. The manifest
558
+ is the existing `parts.json`. The writer checks the recorded positive safe-integer
559
+ `rig_size` and scale against the sealed source/config through the existing frame
560
+ helpers, then calls `sourceInRig` and the existing PNG codec. It writes no parts,
561
+ meshes, measurements or manifest changes.
562
+
563
+ The two added files are `painting_in_rig.png` and `painting_in_rig.json` beside
564
+ that manifest. The JSON has exactly these keys in order:
565
+
566
+ ```json
567
+ {
568
+ "schema": "rig-parts-painting-reference/1",
569
+ "manifest_sha256": "<sha256 of exact parts.json bytes>",
570
+ "path": "painting_in_rig.png",
571
+ "sha256": "<sha256 of exact PNG bytes>",
572
+ "resample": "lanczos3-rgb-opaque",
573
+ "rig_size": [1920, 1080]
574
+ }
575
+ ```
576
+
577
+ `rig_size` is the recorded `[W,H]` tuple, with positive safe integers. `path` is a
578
+ literal portable relative path from the sidecar directory, which is the loaded
579
+ manifest directory. `parsePaintingReference(value)` validates the six-key grammar.
580
+ Consumer admission validates manifest SHA, package containment, PNG hash, RGBA8,
581
+ opaque alpha and exact dimensions. The consumer selects an inline
582
+ `parts.json.painting_in_rig` declaration first and uses this adjacent fallback
583
+ only when the inline key is absent. Existing manifest image roles are unchanged.
584
+
585
+ This is a public Bun/TypeScript API subpath. The package ships `src` and has no
586
+ `exports` map restricting it. A consumer with a package containing this module
587
+ can invoke the normal producer writer directly:
588
+
589
+ ```ts
590
+ import { writePaintingReference } from '@rig-c/parts/src/painting-reference.ts';
591
+
592
+ const receipt = writePaintingReference({
593
+ manifest: { path: 'accepted/parts.json', sha256: expectedManifestHash },
594
+ source: { path: 'inputs/painting.png', sha256: expectedSourceHash },
595
+ config: { path: 'accepted/config.json', sha256: expectedConfigHash },
596
+ });
597
+ ```
598
+
599
+ Run the consumer with Bun and retain `receipt` outside the inspected package.
600
+ An approved source consumption must resolve this updated source package. An
601
+ older installed package that lacks the module requires that source consumption
602
+ or a release carrying the module. The API does not register a project record.
603
+
604
+ The writer validates all input seals and destination collisions before staging.
605
+ Run mode comes from the manifest's `ghost_px` census: assemble records every
606
+ full/head layer, including zero ghost counts, and only single-run assembly omits
607
+ the head census. A full census is required. A resolution-square single run has
608
+ no `single_run_pad`; that absence does not imply two runs. A non-square single
609
+ run requires its recorded pad, whose `file_size` and `side` must match the sealed
610
+ source/config. Head-run census still requires a head box, even with an all-full
611
+ plan. Contradictory run, part, plan or padding evidence refuses under
612
+ `PARTS_PAINTING_REFERENCE_FRAME` before writing. The writer derives no missing
613
+ run-mode field from an image guess.
614
+ It publishes complete files with no-replace links, PNG first and sidecar last.
615
+ The sidecar is the declaration commit point. A partial I/O failure can leave a
616
+ complete unreferenced PNG. An exact retry verifies it and finishes the declaration.
617
+ Concurrent exact writers return the same seals. Conflicting destination bytes,
618
+ symlinks and moved inputs refuse. The caller keeps independent input writers
619
+ frozen during the operation. Only this invocation's staging directory is removed.
620
+
621
+ The returned `rig-parts-painting-reference-write/1` receipt carries the three
622
+ input seals and both output seals. Retain it with the execution/source receipt
623
+ outside the inspected package. It describes this derivation from sealed inputs.
624
+ All original manifest, texture, depth and revision bytes retain their identities.
625
+ The accepted-file inventory gains the two declared additions. No producer
626
+ execution in historical evidence is inferred from a current export.
627
+
628
+ | Refusal | Meaning and remedy |
629
+ | --- | --- |
630
+ | `PARTS_PAINTING_REFERENCE_INPUT` | A named input is unreadable, unsealed, a symlink or invalid JSON/PNG; restore the explicit frozen regular input. |
631
+ | `PARTS_PAINTING_REFERENCE_HASH` | A named input differs from its expected SHA-256; restore its sealed bytes. |
632
+ | `PARTS_PAINTING_REFERENCE_FRAME` | The manifest frame differs from sealed source/config geometry; supply the original source/config and recorded frame. |
633
+ | `PARTS_PAINTING_REFERENCE_SCHEMA` | The named declaration breaks its six-key grammar; restore the producer sidecar. |
634
+ | `PARTS_PAINTING_REFERENCE_OUTPUT` | A named output conflicts or is unreadable; preserve its bytes and resolve the collision. |
635
+ | `PARTS_PAINTING_REFERENCE_WRITE` | Publication failed; preserve existing files and retry with the same sealed inputs. |
636
+
550
637
  | file | written by | what is stable |
551
638
  | --- | --- | --- |
552
639
  | `stage-map.json` | `assemble`, `build`, under `assemble.stage_map: true` | `rig-parts-stage-map/1`, cropped last-writer and pre-seam RLE maps with writer dictionaries and excluded counts. See [Per-pixel stage map](AUTHORING.md#per-pixel-stage-map). |
@@ -1056,6 +1143,37 @@ painting extension's `band`) is refused (`ASSEMBLE_PART_SOURCE`) before
1056
1143
  anything is assembled. Absent or `false`, nothing more is demanded and no byte
1057
1144
  moves.
1058
1145
 
1146
+ ### Edited rig-space parts
1147
+
1148
+ The optional `assemble.edited_parts` block (issue #1278, additive) replaces
1149
+ existing base-plan parts with verified rig-pixel PNG files after all automatic
1150
+ passes and final restoration. It preserves boxes, names, draw order and
1151
+ original `from` identities. The encoded edited file bytes are emitted intact;
1152
+ recomposite and final accounting consume its decoded pixels. Both the edited
1153
+ file hash and the current normal assembled part's `from_sha256` are verified.
1154
+ The block does not change author-layer projection or editor receipt semantics.
1155
+ Alternate sets retain their own declared art; inherited base assets use the
1156
+ edited base image. No new flag bypasses rig-c or existing check bars.
1157
+
1158
+ Receipt association is additive `provenance.edited_part` metadata: the complete
1159
+ receipt and `dir`, `edit: "edited_parts[i]"`, `changed_px`,
1160
+ `changed_counted_px`, `changed_excluded_px` and `removed_opaque_px`.
1161
+ The four counts describe exact baseline-to-edited RGBA differences;
1162
+ `hand_px` keeps its existing final-alpha-above-8 partition meaning.
1163
+ The receipt covers the whole file, including unchanged and transparent
1164
+ positions; stage-map entries retain that association separately from writer
1165
+ runs. The strict parts reader rejects malformed associations and inconsistent
1166
+ counts. [AUTHORING](AUTHORING.md#edited-rig-space-parts-assembleedited_parts-issue-1278)
1167
+ defines paths, counts and the base-only scope.
1168
+
1169
+ An unknown part, missing file, edited hash mismatch, stale baseline hash,
1170
+ dimension mismatch or duplicate part is refused by its dedicated
1171
+ `ASSEMBLE_EDITED_PART_*` code before any output write. A non-decodable PNG is
1172
+ also refused before writes. A preexisting successful output remains unchanged.
1173
+ The [refusal table](https://github.com/rig-c/parts/blob/main/docs/CHECKS.md#edited-rig-space-parts)
1174
+ names each code. Without the block, existing outputs and metadata stay
1175
+ byte-identical; an empty receipt list applies no replacement.
1176
+
1059
1177
  ## Provider-map depth stages (#897)
1060
1178
 
1061
1179
  The opt-in `depth-prepare` and `depth-apply` commands accept the separate
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "spine-parts",
3
- "version": "2.36.0",
3
+ "version": "2.38.0",
4
4
  "description": "AI-authored 2D character parts from one anime painting and its See-through layer decomposition: measured parts, weighted-mesh rig specs, verified through rig-c before anything is written. A CLI for agents that cannot see the image.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -68,7 +68,7 @@
68
68
  },
69
69
  "dependencies": {
70
70
  "ag-psd": "^31.0.2",
71
- "@rig-c/core": "3.6.0"
71
+ "@rig-c/core": "3.7.0"
72
72
  },
73
73
  "devDependencies": {
74
74
  "@esotericsoftware/spine-core": "4.3.13",
package/src/assemble.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { sourceCoverRun, type SourceCoverReading } from './sourcecover.ts';
2
+ import { replaceEditedParts, type EditedPartContext, type VerifiedEditedPart } from './editedparts.ts';
2
3
  import { paintingReceivers, rawPaintingOwner } from './paintingowner.ts';
3
4
  import { hiddenExtentProblems, type HiddenExtentDeclaration, type HiddenExtentSource } from './hiddenextent.ts';
4
5
  import { headBoxInside } from './headbox.ts';
@@ -324,6 +325,8 @@ export function singleRunPadRecord(single: boolean, sourceW: number, sourceH: nu
324
325
  }
325
326
 
326
327
  export interface AssembleInput {
328
+ /** Verified whole-file base-part edits, placed after all normal raster passes. */
329
+ editedParts?: readonly VerifiedEditedPart[];
327
330
  /** Observe allocation decisions after guarding and restoration. */
328
331
  allocationEvent?: (event: PaintingAllocationEvent) => void;
329
332
  /** Counterfactual before seeded takes, with whole-layer takes already applied. */
@@ -2864,6 +2867,8 @@ export function groundWarning(share: number, ground: Ground | undefined, rule: P
2864
2867
  }
2865
2868
 
2866
2869
  export interface PlacedPart {
2870
+ /** Verified edited PNG bytes; emit verbatim rather than encoding image again. */
2871
+ encodedBytes?: Uint8Array;
2867
2872
  depthImage?: Raster;
2868
2873
  record: PartRecord;
2869
2874
  image: Raster;
@@ -5097,16 +5102,26 @@ export function retainRegionNeighbours(placed: PlacedPart[], before: readonly Pl
5097
5102
  * after this returned writes only after green.
5098
5103
  */
5099
5104
  export function assemble(input: AssembleInput): AssembleResult {
5100
- if (input.regionTake === undefined) return assembleParts(input);
5105
+ const contexts = (input.editedParts?.length ?? 0) === 0 ? undefined : new Map<PlacedPart, EditedPartContext>();
5106
+ // The internal map preserves classifications across region restoration even
5107
+ // when the caller does not request the report-only sidecar.
5108
+ const working = contexts === undefined ? input : { ...input, stageMap: true };
5109
+ if (input.regionTake === undefined) {
5110
+ const result = assembleParts(working, undefined, null, undefined, contexts);
5111
+ if (contexts !== undefined && input.stageMap !== true) delete result.stageMap;
5112
+ return result;
5113
+ }
5101
5114
  const targets = regionTakeTargets(input.regionTake.targets, input.cuts, input.limbs);
5102
5115
  const counterfactual = input.projectRule === 'core' ? { cleanup: new Map<string, RunLayer[]>(), seam: new Map<string, Uint8Array>() } : undefined;
5103
- const before = assembleParts({ ...input, full: input.regionTake.full, head: input.regionTake.head, regionTake: undefined, requireHiddenExtent: undefined }, targets, null, counterfactual);
5104
- return assembleParts(input, targets, before, counterfactual);
5116
+ const before = assembleParts({ ...working, editedParts: undefined, full: input.regionTake.full, head: input.regionTake.head, regionTake: undefined, requireHiddenExtent: undefined }, targets, null, counterfactual, contexts);
5117
+ const result = assembleParts(working, targets, before, counterfactual, contexts);
5118
+ if (contexts !== undefined && input.stageMap !== true) delete result.stageMap;
5119
+ return result;
5105
5120
  }
5106
5121
 
5107
5122
  /** The counterfactual is internal and is never emitted. Empty taken targets
5108
5123
  * may be recovered by a take, so only that counterfactual permits them. */
5109
- function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, beforeTake: AssembleResult | null = null, counterfactual?: { cleanup: Map<string, RunLayer[]>; seam: Map<string, Uint8Array> }): AssembleResult {
5124
+ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, beforeTake: AssembleResult | null = null, counterfactual?: { cleanup: Map<string, RunLayer[]>; seam: Map<string, Uint8Array> }, editContexts?: Map<PlacedPart, EditedPartContext>): AssembleResult {
5110
5125
  const emptyTargets = beforeTake === null ? targets : undefined;
5111
5126
  const { source, extend, patches, seamRule, projectRule } = input;
5112
5127
  const authoredDepths = input.depth === undefined ? new Map<string, AuthoredUnitDepth>() : authoredUnitDepths(input);
@@ -6400,7 +6415,7 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
6400
6415
  const upperIndex = limb === undefined ? -1 : lim.parts.findIndex(q => q.record.name === limb.name && q.record.segment === limb.segment - 1);
6401
6416
  const capSource = limbIndex < 0 ? null : lim.capFrom[limbIndex];
6402
6417
  const authoredDepth = authoredDepths.get(name);
6403
- const scalar = authoredDepth === undefined ? transportPartDepth(record, image, registeredDepth, {
6418
+ const scalarFor = (art: Raster) => authoredDepth === undefined ? transportPartDepth(record, art, registeredDepth, {
6404
6419
  map: run => runMap(frame, run), width: W, extend: extendKeys, owner: trace.from,
6405
6420
  ring: trace.ring.data, region: region?.data ?? null,
6406
6421
  copiedSource: (x, y) => {
@@ -6412,6 +6427,7 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
6412
6427
  },
6413
6428
  ...((limb?.cap?.image_px ?? 0) > 0 || (limb?.cap?.lower_px ?? 0) > 0 ? { unsupported: `cap copies ${(limb?.cap?.image_px ?? 0) + (limb?.cap?.lower_px ?? 0)} pixels from a separate cap image whose scalar grid is undeclared` } : {}),
6414
6429
  }) : undefined;
6430
+ const scalar = scalarFor(image);
6415
6431
  if (capSource !== null && upperIndex >= 0 && capSource.codes.some(code => code === CAP_FROM_UPPER)) {
6416
6432
  const upper = limbPieces[upperIndex];
6417
6433
  const keys = [upper.key, ...upper.extendKeys.filter((_, i) => upper.trace.from.some(v => v === i))];
@@ -6423,7 +6439,9 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
6423
6439
  }
6424
6440
  if (scalar !== undefined) record.depth = scalar.reference;
6425
6441
  if (scalar !== undefined && scalar.clampedSamples > 0) depthClamps.push({ part: name, samples: scalar.clampedSamples });
6426
- set({ record, image, ...(scalar === undefined ? {} : { depthImage: scalar.image }) });
6442
+ const placedPart = { record, image, ...(scalar === undefined ? {} : { depthImage: scalar.image }) };
6443
+ if (editContexts !== undefined) editContexts.set(placedPart, { baseline: null, visible, projected, paintingGain, ...(scalar === undefined ? {} : { depthForEdit: scalarFor }) });
6444
+ set(placedPart);
6427
6445
  });
6428
6446
  refuseIfAny(empty);
6429
6447
  const placed: PlacedPart[] = order.map((d) => ('plan' in d ? planned[d.plan] : 'cut' in d ? cutPlaced[d.cut] : 'limb' in d ? limbPlaced[d.limb] : cut[d.patch]) as PlacedPart);
@@ -6490,6 +6508,7 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
6490
6508
  excluded_px: 0, runs: [] as Array<[number, number]>, pre_seam_writer_runs: [] as Array<[number, number]>,
6491
6509
  };
6492
6510
  p.record.provenance = pixelProvenance(p.image, p.record.x, p.record.y, W, writersInOrder[i], editNames, 0, valueBaselines.get(p.record.from) ?? null, map, preSeamWriters?.get(i));
6511
+ if (editContexts?.has(p)) editContexts.get(p)!.baseline = valueBaselines.get(p.record.from) ?? null;
6493
6512
  if (map !== undefined) stageMap!.parts.push(map);
6494
6513
  const depth = authoredDepths.get(p.record.name);
6495
6514
  if (depth !== undefined) p.record.provenance.depth = depth;
@@ -6510,6 +6529,14 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
6510
6529
  return { ...original, runs: original.runs.map(remap), pre_seam_writer_runs: original.pre_seam_writer_runs.map(remap) };
6511
6530
  });
6512
6531
  }
6532
+ if ((input.editedParts?.length ?? 0) > 0) replaceEditedParts(placed, input.editedParts!, new Set(input.plan.map(([name]) => name)), stageMap!, editContexts!);
6533
+ if (editContexts !== undefined) for (const p of placed) {
6534
+ const samples = editContexts.get(p)?.depthClampedSamples;
6535
+ if (samples === undefined) continue;
6536
+ const previous = depthClamps.findIndex(row => row.part === p.record.name);
6537
+ if (previous >= 0) depthClamps.splice(previous, 1);
6538
+ if (samples > 0) depthClamps.push({ part: p.record.name, samples });
6539
+ }
6513
6540
  // Provenance is now numbers/labels only. No later raster/figure operation
6514
6541
  // reads report buffers; release all aliases before recomposite/error work.
6515
6542
  valueBaselines.clear();
package/src/build.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { readEditedParts } from './editedparts.ts';
1
2
  import { SOURCE_COVER_FILE, sourceCoverReport, type SourceCoverSet } from './sourcecover.ts';
2
3
  import { STAGE_MAP_FILE } from './provenance.ts';
3
4
  import { withoutCheckRows } from './checkrow.ts';
@@ -173,6 +174,8 @@ export interface AlternateCliInput {
173
174
  }
174
175
 
175
176
  export interface AssembleStageInput {
177
+ /** Internal build protocol: reset owned outputs only after assembly is green. */
178
+ resetBuildOutput?: boolean;
176
179
  /** A null set identifies the primary assembly evaluation. */
177
180
  allocationEvent?: (event: PaintingAllocationEvent, set: string | null) => void;
178
181
  /** Write source-edge evidence only when cut_material is explicitly declared. */
@@ -394,12 +397,14 @@ export function emitFillMasksStage(input: EmitFillMasksInput, log: Log): Array<{
394
397
  const read = readRuns(input.full, input.head);
395
398
  const takenRuns = applyTakenLayers(read, src, cfg, input.config);
396
399
  const receipts = readEditorReceipts(cfg.assemble.editor_receipts, input.config);
400
+ const editedParts = readEditedParts(cfg.assemble.edited_parts, input.config, cfg.assemble.plan ?? []);
397
401
  const runs = applyTakenRegions(takenRuns, src, cfg, input.config, undefined, receipts, input.source);
398
402
  const fields = stageFields(cfg, runs.single ? { w: src.width, h: src.height } : null);
399
403
  const strippedCuts = fields.cuts.map((q) => ({ from: q.from, into: q.into, polygon: q.polygon, draw: q.draw, overlap: q.overlap }));
400
404
  const caps = fields.limbs === undefined ? undefined : readCaps(input.config, fields.limbs);
401
405
  const occluders = cfg.assemble.occluders === undefined ? undefined : readOccluderInputs(cfg.assemble.occluders, input.config, src);
402
406
  const result = assemble({
407
+ editedParts,
403
408
  source: src,
404
409
  full: runs.full,
405
410
  head: runs.head,
@@ -514,6 +519,7 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
514
519
  const read = readRuns(input.full, input.head);
515
520
  // Issue #946: every declared receipt is held to its file, and under `required` every edited image needs one, before anything is assembled.
516
521
  const receipts = readEditorReceipts(cfg.assemble.editor_receipts, input.config);
522
+ const editedParts = readEditedParts(cfg.assemble.edited_parts, input.config, cfg.assemble.plan ?? []);
517
523
  // Issue #947: under `trace_parts`, a shape drawn in the config through a part's pixels is refused with them.
518
524
  refuseIfAny([...receipts.problems, ...missingReceipts(receipts, [...editedRunImages(read), ...editedConfigImages(input.config, cfg.assemble.cuts ?? [], cfg.limbs)]), ...untracedPartSources(cfg)]);
519
525
  const takenRuns = applyTakenLayers(read, src, cfg, input.config);
@@ -530,7 +536,7 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
530
536
  const under = readUnders(input.config, fields.cuts, { sourcePath: input.source, rigSize, platesOut: underPlates });
531
537
  const caps = fields.limbs === undefined ? undefined : readCaps(input.config, fields.limbs);
532
538
  const occluders = cfg.assemble.occluders === undefined ? undefined : readOccluderInputs(cfg.assemble.occluders, input.config, src);
533
- const result = assemble({ allocationEvent: input.allocationEvent === undefined ? undefined : event => input.allocationEvent!(event, null), source: src, full: runs.full, head: runs.head, depth: cfg.depth, depthBase: dirname(resolve(input.config)), ...fields, under, ...(declaredFigure === undefined ? {} : { declaredFigure }),
539
+ const result = assemble({ editedParts, allocationEvent: input.allocationEvent === undefined ? undefined : event => input.allocationEvent!(event, null), source: src, full: runs.full, head: runs.head, depth: cfg.depth, depthBase: dirname(resolve(input.config)), ...fields, under, ...(declaredFigure === undefined ? {} : { declaredFigure }),
534
540
  ...((cfg.assemble.take ?? []).some(t => 'seed' in t) ? { regionTake: { full: takenRuns.full, head: takenRuns.head, targets: (cfg.assemble.take ?? []).flatMap(t => 'seed' in t ? [t.part] : []) } } : {}), ...(caps === undefined ? {} : { caps }), ...(occluders === undefined ? {} : { occluders }), seamRule: seam, projectRule: project });
535
541
  refuseIfAny(verifyUnderPlateMasks(result, fields.cuts, underPlates));
536
542
 
@@ -1082,6 +1088,7 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
1082
1088
  }
1083
1089
 
1084
1090
  // Emit only after green: every refusal above has already thrown.
1091
+ if (input.resetBuildOutput === true) resetBuildOutput(dirname(outs.partsJson));
1085
1092
  mkdirSync(outs.partsDir, { recursive: true });
1086
1093
  mkdirSync(dirname(outs.partsJson), { recursive: true });
1087
1094
  mkdirSync(dirname(outs.recomposite), { recursive: true });
@@ -1118,8 +1125,9 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
1118
1125
  log(`${PAINTING_EDGE_COVERAGE_TRANSFER}: set "${report.set}" ${count} native rig px; membership in ${file}`);
1119
1126
  }
1120
1127
  }
1121
- for (const { record, image, depthImage } of result.images) {
1122
- writePng(join(outs.partsDir, `${record.name}.png`), image);
1128
+ for (const { record, image, depthImage, encodedBytes } of result.images) {
1129
+ if (encodedBytes === undefined) writePng(join(outs.partsDir, `${record.name}.png`), image);
1130
+ else writeFileSync(join(outs.partsDir, `${record.name}.png`), encodedBytes);
1123
1131
  if (depthImage !== undefined && record.depth !== undefined) writePng(join(outs.partsDir, record.depth.image), depthImage);
1124
1132
  }
1125
1133
  for (const row of result.depthReadings ?? []) log(` depth reading ${row.from}: ${row.reading.relation}; ordering median ${row.reading.orderingMedian}, source-sheet median ${row.reading.sheetMedian} (half-level quantization; reading only, polarity declared)`);
@@ -2738,6 +2746,21 @@ export interface BuildRunners {
2738
2746
  /** Every path `build` writes under `--out`, relative — and so every path it clears first. */
2739
2747
  export const BUILD_OWNS: readonly string[] = ['parts', 'parts.json', SOURCE_COVER_FILE, PAINTING_IN_RIG_FILE, 'recomposite_rig.png', ERROR_MAP_FILE, 'rig', 'check', 'idle.gif', 'idle.png', 'idle-indexed.png'];
2740
2748
 
2749
+ function resetBuildOutput(out: string): void {
2750
+ mkdirSync(out, { recursive: true });
2751
+ for (const p of BUILD_OWNS) rmSync(join(out, p), { recursive: true, force: true });
2752
+ for (const p of [CUT_MATERIAL_SOURCES, EDGE_RESIDUAL_FILE, SUPPORT_DOMAINS_FILE, FIGURE_MASK_FILE]) rmSync(join(out, p), { force: true });
2753
+ }
2754
+
2755
+ /** Only selects when cleanup occurs; the real config loader still decides validity. */
2756
+ function declaresEditedParts(path: string): boolean {
2757
+ try {
2758
+ const raw: unknown = JSON.parse(readFileSync(path, 'utf8'));
2759
+ return raw !== null && typeof raw === 'object' && 'assemble' in raw &&
2760
+ raw.assemble !== null && typeof raw.assemble === 'object' && 'edited_parts' in raw.assemble;
2761
+ } catch { return false; }
2762
+ }
2763
+
2741
2764
  export type BuildStage = 'assemble' | 'rig' | 'check' | 'loop' | 'artifact';
2742
2765
 
2743
2766
  export interface BuildResult {
@@ -2797,14 +2820,8 @@ export function build(input: BuildInput, run: BuildRunners, log: Log): BuildResu
2797
2820
  return { stoppedAt: stage, check, artifact: [] };
2798
2821
  };
2799
2822
  const out = input.out;
2800
- mkdirSync(out, { recursive: true });
2801
- for (const p of BUILD_OWNS) rmSync(join(out, p), { recursive: true, force: true });
2802
- // Optional source evidence is cleared separately; BUILD_OWNS is the legacy complete output tree.
2803
- rmSync(join(out, CUT_MATERIAL_SOURCES), { force: true });
2804
- rmSync(join(out, EDGE_RESIDUAL_FILE), { force: true });
2805
- rmSync(join(out, SUPPORT_DOMAINS_FILE), { force: true });
2806
- // Issue #242: the figure mask is written only under config.scene; one left by an earlier scene build is not this build's.
2807
- rmSync(join(out, FIGURE_MASK_FILE), { force: true });
2823
+ const deferReset = declaresEditedParts(input.config);
2824
+ if (!deferReset) resetBuildOutput(out);
2808
2825
  // The idle-keys value is named only when it is not the default, so a build without the flag, or with the default, prints the line it printed before issue #95.
2809
2826
  const idleKeys = input.idleKeys ?? DEFAULT_IDLE_KEYS;
2810
2827
 
@@ -2834,7 +2851,7 @@ export function build(input: BuildInput, run: BuildRunners, log: Log): BuildResu
2834
2851
  // And the steady-wind band spec (issue #590), as check reads it.
2835
2852
  if (input.windBand !== undefined) readWindBand(input.windBand);
2836
2853
  const assembled = stages.assemble(
2837
- { source: input.source, full: input.full, head: input.head, config: input.config, seam, project, ...(req === null ? {} : { requirements: req.read }), ...(input.alts === undefined ? {} : { alts: input.alts }) },
2854
+ { source: input.source, full: input.full, head: input.head, config: input.config, seam, project, ...(deferReset ? { resetBuildOutput: true } : {}), ...(req === null ? {} : { requirements: req.read }), ...(input.alts === undefined ? {} : { alts: input.alts }) },
2838
2855
  { partsJson: join(out, 'parts.json'), partsDir: join(out, 'parts'), recomposite: join(out, 'recomposite_rig.png'), errorMap: join(out, ERROR_MAP_FILE) },
2839
2856
  prefixed('assemble'),
2840
2857
  );
package/src/config.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { EditedParts } from './editedparts.ts';
1
2
  import { hiddenExtentNameProblems, type HiddenExtentDeclaration } from './hiddenextent.ts';
2
3
  import { occluderFileProblems, occluderNameProblems, type OccluderDeclaration } from './occluders.ts';
3
4
  import { SEAM_RULES, type SeamRule } from './seamrule.ts';
@@ -94,7 +95,7 @@ import type { DepthConfig } from './depthsheets.ts';
94
95
  * the field is a non-empty string.
95
96
  */
96
97
  import { existsSync, readFileSync, statSync } from 'node:fs';
97
- import { dirname, relative, resolve } from 'node:path';
98
+ import { dirname, isAbsolute, relative, resolve } from 'node:path';
98
99
  import { RIG_BONE_INHERIT, RIG_SKIN_CONSTRAINT_KEYS, type RigBoneInherit, type RigConstraint, type RigSkinConstraintKey, type RigStop } from '@rig-c/core/rig';
99
100
  import { pyRound } from './round.ts';
100
101
  import { motionSeamProblems, type MotionSeamDeclaration } from './motionseams.ts';
@@ -331,6 +332,8 @@ export interface Assemble {
331
332
  take?: TakeDeclaration[];
332
333
  /** Issue #946: receipts for images edited in an image editor; absent, no file is read and no byte moves. */
333
334
  editor_receipts?: EditorReceipts;
335
+ /** Whole-file rig-space edits; config-relative directory, directory-relative files. */
336
+ edited_parts?: EditedParts;
334
337
  /** Rig pixels per source pixel. */
335
338
  rig_scale: number;
336
339
  plan: PlanEntry[];
@@ -1729,7 +1732,7 @@ export interface EarlyConfig {
1729
1732
  depth?: DepthConfig;
1730
1733
  key: string;
1731
1734
  seethrough: SeeThrough;
1732
- assemble: { rig_scale: number; seam?: SeamRule; project?: ProjectRule; ground?: Ground; take?: TakeDeclaration[]; editor_receipts?: EditorReceipts; head_face_underfill?: boolean; yield_refused?: boolean; stage_map?: boolean; keep_under_occluders?: string[]; require_hidden_extent?: HiddenExtentDeclaration[]; extend_painting?: PaintingExtension[]; occluders?: OccluderDeclaration[]; edge_splits?: EdgeSplit[] };
1735
+ assemble: { rig_scale: number; seam?: SeamRule; project?: ProjectRule; ground?: Ground; take?: TakeDeclaration[]; editor_receipts?: EditorReceipts; edited_parts?: EditedParts; head_face_underfill?: boolean; yield_refused?: boolean; stage_map?: boolean; keep_under_occluders?: string[]; require_hidden_extent?: HiddenExtentDeclaration[]; extend_painting?: PaintingExtension[]; occluders?: OccluderDeclaration[]; edge_splits?: EdgeSplit[] };
1733
1736
  }
1734
1737
 
1735
1738
  /** What plain `assemble` reads: the early config plus the plan `--propose-plan` printed. */
@@ -1807,7 +1810,7 @@ function parseEarlyConfigFrom(raw: Json, door: EarlyDoor, base: string | null, p
1807
1810
  if (door === 'layers') {
1808
1811
  if ('seethrough' in t) checkSeeThrough(c, t.seethrough);
1809
1812
  if ('assemble' in t) {
1810
- const a = c.object('config.assemble', t.assemble, sectionRequired(door, 'assemble'), ['plan', 'extend_below_crop', 'patches', 'cuts', 'alternates', 'head_face_underfill', 'yield_refused', 'stage_map', 'keep_under_occluders', 'require_hidden_extent', 'extend_painting', 'edge_splits', 'take', 'seam', 'project', 'ground', 'editor_receipts', 'occluders']);
1813
+ const a = c.object('config.assemble', t.assemble, sectionRequired(door, 'assemble'), ['plan', 'extend_below_crop', 'patches', 'cuts', 'alternates', 'head_face_underfill', 'yield_refused', 'stage_map', 'keep_under_occluders', 'require_hidden_extent', 'extend_painting', 'edge_splits', 'take', 'seam', 'project', 'ground', 'editor_receipts', 'edited_parts', 'occluders']);
1811
1814
  if (a !== null) {
1812
1815
  checkAssembleRules(c, a);
1813
1816
  if ('rig_scale' in a) c.number('config.assemble.rig_scale', a.rig_scale, 'positive');
@@ -1824,6 +1827,7 @@ function parseEarlyConfigFrom(raw: Json, door: EarlyDoor, base: string | null, p
1824
1827
  if ('edge_splits' in a) checkEdgeSplits(c, a.edge_splits, Array.isArray(a.plan) ? new Set(a.plan.filter((r): r is Json[] => Array.isArray(r) && typeof r[0] === 'string').map(r => r[0] as string)) : null);
1825
1828
  if ('take' in a) checkTakeLayers(c, a.take, null, a);
1826
1829
  if ('editor_receipts' in a) checkEditorReceipts(c, a.editor_receipts);
1830
+ if ('edited_parts' in a) checkEditedParts(c, a.edited_parts, a.plan);
1827
1831
  if ('yield_refused' in a && typeof a.yield_refused !== 'boolean') {
1828
1832
  c.fail('CONFIG_FIELD_TYPE', 'config.assemble.yield_refused', `is ${show(a.yield_refused)}; true or false is required`);
1829
1833
  }
@@ -2770,13 +2774,35 @@ export function editorReceiptProblems(value: unknown, at: string): Problem[] {
2770
2774
  return c.problems;
2771
2775
  }
2772
2776
 
2773
- /**
2774
- * `config.assemble.editor_receipts` (issue #946): `{receipts, required?, trace_parts?}` (`trace_parts`, issue #947).
2775
- * Shape refusals are the loader's own; a receipt whose `from_sha256` equals
2776
- * its `sha256` (no edit), or a `file` receipted twice, is `CONFIG_EDITOR_RECEIPT`.
2777
- * Whether the file exists and hashes to `sha256` is read at assemble
2778
- * (`src/editreceipt.ts`), where the file is.
2779
- */
2777
+ /** Whole-file rig-space receipts; file/baseline verification is at assemble. */
2778
+ function checkEditedParts(c: Check, value: Json, plan: Json | undefined): void {
2779
+ const at = 'config.assemble.edited_parts';
2780
+ const absolute = (path: string): boolean => isAbsolute(path) || /^(?:[\\/]|[A-Za-z]:[\\/])/.test(path);
2781
+ const o = c.object(at, value, ['dir', 'receipts'], []);
2782
+ if (o === null) return;
2783
+ if (typeof o.dir === 'string' && o.dir.trim().length === 0 && o.dir !== '') c.fail('CONFIG_FIELD_TYPE', at + '.dir', 'is blank; a non-empty directory is required');
2784
+ if ('dir' in o && c.string(at + '.dir', o.dir) && absolute(o.dir as string)) c.fail('CONFIG_FIELD_TYPE', at + '.dir', 'is absolute; a directory relative to the config is required');
2785
+ if (!('receipts' in o) || !c.array(at + '.receipts', o.receipts, false)) return;
2786
+ const names = Array.isArray(plan) ? new Set(plan.filter((r): r is Json[] => Array.isArray(r) && typeof r[0] === 'string').map(r => r[0] as string)) : null;
2787
+ const seen = new Map<string, number>();
2788
+ (o.receipts as Json[]).forEach((value, i) => {
2789
+ const p = at + '.receipts[' + i + ']';
2790
+ const r = c.object(p, value, ['part', 'file', 'sha256', 'from_sha256', 'editor'], []);
2791
+ if (r === null) return;
2792
+ if ('part' in r && c.string(p + '.part', r.part)) {
2793
+ const part = r.part as string;
2794
+ if (seen.has(part)) c.fail('ASSEMBLE_EDITED_PART_DUPLICATE', p + '.part', `names "${part}" again (first at receipts[${seen.get(part)}]); one receipt per part is required`);
2795
+ else seen.set(part, i);
2796
+ if (names !== null && !names.has(part)) c.fail('ASSEMBLE_EDITED_PART_UNKNOWN', p + '.part', `names "${part}"; an existing assemble.plan part is required`);
2797
+ }
2798
+ if ('file' in r && c.string(p + '.file', r.file) && absolute(r.file as string)) c.fail('CONFIG_FIELD_TYPE', p + '.file', 'is absolute; a PNG path relative to edited_parts.dir is required');
2799
+ if ('editor' in r) c.string(p + '.editor', r.editor);
2800
+ for (const key of ['part', 'file', 'editor'] as const) if (typeof r[key] === 'string' && (r[key] as string).trim().length === 0 && r[key] !== '') c.fail('CONFIG_FIELD_TYPE', p + '.' + key, 'is blank; a non-empty value is required');
2801
+ for (const key of ['sha256', 'from_sha256'] as const) if (key in r && (typeof r[key] !== 'string' || !SHA256_PATTERN.test(r[key] as string))) c.fail('CONFIG_FIELD_TYPE', p + '.' + key, `is ${show(r[key])}; ${SHA256_RULE} is required`);
2802
+ });
2803
+ }
2804
+
2805
+ /** Existing source-image receipts keep their own config-relative file contract. */
2780
2806
  function checkEditorReceipts(c: Check, value: Json, at = 'config.assemble.editor_receipts'): void {
2781
2807
  const o = c.object(at, value, ['receipts'], ['required', 'trace_parts']);
2782
2808
  if (o === null) return;
@@ -2816,7 +2842,7 @@ function checkAssembleRules(c: Check, a: Record<string, Json>): void {
2816
2842
 
2817
2843
  function checkAssemble(c: Check, v: Json, door: 'assemble' | 'full'): { parts: string[]; patches: string[]; cuts: string[] } {
2818
2844
  const required = sectionRequired(door, 'assemble');
2819
- const a = c.object('config.assemble', v, required.filter((k) => k !== 'plan'), ['plan', 'extend_below_crop', 'patches', 'cuts', 'alternates', 'head_face_underfill', 'yield_refused', 'stage_map', 'keep_under_occluders', 'require_hidden_extent', 'extend_painting', 'edge_splits', 'take', 'seam', 'project', 'ground', 'editor_receipts', 'occluders']);
2845
+ const a = c.object('config.assemble', v, required.filter((k) => k !== 'plan'), ['plan', 'extend_below_crop', 'patches', 'cuts', 'alternates', 'head_face_underfill', 'yield_refused', 'stage_map', 'keep_under_occluders', 'require_hidden_extent', 'extend_painting', 'edge_splits', 'take', 'seam', 'project', 'ground', 'editor_receipts', 'edited_parts', 'occluders']);
2820
2846
  if (a === null) return { parts: [], patches: [], cuts: [] };
2821
2847
  checkAssembleRules(c, a);
2822
2848
  if (required.includes('plan') && !('plan' in a)) {
@@ -2861,6 +2887,7 @@ function checkAssemble(c: Check, v: Json, door: 'assemble' | 'full'): { parts: s
2861
2887
  if ('edge_splits' in a) checkEdgeSplits(c, a.edge_splits, new Set(parts));
2862
2888
  if ('take' in a) checkTakeLayers(c, a.take, parts, a);
2863
2889
  if ('editor_receipts' in a) checkEditorReceipts(c, a.editor_receipts);
2890
+ if ('edited_parts' in a) checkEditedParts(c, a.edited_parts, a.plan);
2864
2891
  if ('extend_below_crop' in a && c.array(`${p}.extend_below_crop`, a.extend_below_crop, false)) {
2865
2892
  (a.extend_below_crop as Json[]).forEach((entry, i) => {
2866
2893
  const at = `${p}.extend_below_crop[${i}]`;
@@ -0,0 +1,168 @@
1
+ /** Rig-space whole-file replacements, applied after the last normal raster pass. */
2
+ import { createHash } from 'node:crypto';
3
+ import { readFileSync } from 'node:fs';
4
+ import { dirname, resolve } from 'node:path';
5
+ import type { EditorReceipt } from './editreceipt.ts';
6
+ import { refuseIfAny, type Problem } from './errors.ts';
7
+ import { OPAQUE_ALPHA_ABOVE } from './layers.ts';
8
+ import { AUTOMATIC_WRITERS, EXCLUDED_PIXEL, NOT_OVERRIDDEN_PIXEL, rgbaEqual, type AutomaticWriter, type PartStageMap, type PixelProvenance, type StageMap, type ValueBaseline } from './provenance.ts';
9
+ import { decodePngBytes, encodePngBytes } from './raster/png.ts';
10
+ import type { Mask, Raster } from './raster/types.ts';
11
+ import type { PlacedPart } from './assemble.ts';
12
+ import type { PartDepthReference } from './depthsheets.ts';
13
+
14
+ export interface EditedPartReceipt extends EditorReceipt { part: string }
15
+ export interface EditedParts { dir: string; receipts: EditedPartReceipt[] }
16
+ export interface VerifiedEditedPart {
17
+ index: number;
18
+ dir: string;
19
+ receipt: EditedPartReceipt;
20
+ bytes: Uint8Array;
21
+ image: Raster;
22
+ }
23
+ export interface EditedPartProvenance {
24
+ edit: string;
25
+ dir: string;
26
+ receipt: EditedPartReceipt;
27
+ changed_px: number;
28
+ changed_counted_px: number;
29
+ changed_excluded_px: number;
30
+ removed_opaque_px: number;
31
+ }
32
+ /** Only held for an edited build, including its region-take counterfactual. */
33
+ export interface EditedPartContext {
34
+ baseline: ValueBaseline | null;
35
+ visible?: Mask;
36
+ projected?: Mask;
37
+ paintingGain?: Mask;
38
+ /** Validate newly visible material against declared scalar sources. */
39
+ depthForEdit?: (image: Raster) => { reference: PartDepthReference; image: Raster; clampedSamples: number } | undefined;
40
+ depthClampedSamples?: number;
41
+ }
42
+ const AT = 'config.assemble.edited_parts';
43
+ const sha = (bytes: Uint8Array): string => createHash('sha256').update(bytes).digest('hex');
44
+
45
+ /** Read once: validation, decoding and final emission all use these exact bytes. */
46
+ export function readEditedParts(spec: EditedParts | undefined, configPath: string, plan: ReadonlyArray<readonly [string, string, string]>): VerifiedEditedPart[] {
47
+ if (spec === undefined) return [];
48
+ const out: VerifiedEditedPart[] = [], problems: Problem[] = [];
49
+ const names = new Set(plan.map(([name]) => name)), seen = new Set<string>();
50
+ for (const [index, receipt] of spec.receipts.entries()) {
51
+ const object = `${AT}.receipts[${index}] (part "${receipt.part}")`;
52
+ if (seen.has(receipt.part)) problems.push({ code: 'ASSEMBLE_EDITED_PART_DUPLICATE', object, detail: 'names the same part twice; one receipt per plan part is required' });
53
+ seen.add(receipt.part);
54
+ if (!names.has(receipt.part)) problems.push({ code: 'ASSEMBLE_EDITED_PART_UNKNOWN', object, detail: `names "${receipt.part}"; an existing assemble.plan part is required` });
55
+ const path = resolve(dirname(resolve(configPath)), spec.dir, receipt.file);
56
+ let bytes: Uint8Array;
57
+ try { bytes = new Uint8Array(readFileSync(path)); }
58
+ catch { problems.push({ code: 'ASSEMBLE_EDITED_PART_FILE', object, detail: `file "${receipt.file}" in dir "${spec.dir}" is not readable; a PNG relative to edited_parts.dir is required` }); continue; }
59
+ const found = sha(bytes);
60
+ if (found !== receipt.sha256) {
61
+ problems.push({ code: 'ASSEMBLE_EDITED_PART_SHA256', object, detail: `file sha256 is ${found}; receipt sha256 ${receipt.sha256} is required` });
62
+ continue;
63
+ }
64
+ try { out.push({ index, dir: spec.dir, receipt, bytes, image: decodePngBytes(bytes, receipt.file) }); }
65
+ catch (error) { problems.push({ code: 'ASSEMBLE_EDITED_PART_DECODES', object, detail: `file "${receipt.file}" is not a decodable PNG: ${(error as Error).message.split('\n')[0]}` }); }
66
+ }
67
+ refuseIfAny(problems);
68
+ return out;
69
+ }
70
+
71
+ function append(runs: Array<[number, number]>, id: number): void {
72
+ const last = runs[runs.length - 1];
73
+ if (last?.[0] === id) last[1]++;
74
+ else runs.push([id, 1]);
75
+ }
76
+ function reader(runs: ReadonlyArray<readonly [number, number]>): () => number {
77
+ let at = 0, used = 0;
78
+ return () => {
79
+ const [id, length] = runs[at];
80
+ if (++used === length) { at++; used = 0; }
81
+ return id;
82
+ };
83
+ }
84
+
85
+ /** Validate every baseline before replacing any image. No output writes here. */
86
+ export function replaceEditedParts(placed: PlacedPart[], edits: readonly VerifiedEditedPart[], plan: ReadonlySet<string>, map: StageMap, contexts: ReadonlyMap<PlacedPart, EditedPartContext>): void {
87
+ const problems: Problem[] = [], seen = new Set<string>();
88
+ for (const edit of edits) {
89
+ const { receipt, image } = edit, part = placed.find(p => p.record.name === receipt.part);
90
+ const object = `${AT}.receipts[${edit.index}] (part "${receipt.part}")`;
91
+ if (seen.has(receipt.part)) problems.push({ code: 'ASSEMBLE_EDITED_PART_DUPLICATE', object, detail: 'names the same part twice; one receipt per plan part is required' });
92
+ seen.add(receipt.part);
93
+ if (!plan.has(receipt.part) || part === undefined) {
94
+ problems.push({ code: 'ASSEMBLE_EDITED_PART_UNKNOWN', object, detail: 'requires an existing plan part emitted under the same name; a part consumed by limb splitting is not a final plan part' });
95
+ continue;
96
+ }
97
+ const found = sha(encodePngBytes(part.image));
98
+ if (found !== receipt.from_sha256) problems.push({ code: 'ASSEMBLE_EDITED_PART_BASELINE', object, detail: `the current assembled PNG sha256 is ${found}; receipt from_sha256 ${receipt.from_sha256} is required` });
99
+ if (image.width !== part.record.w || image.height !== part.record.h) problems.push({ code: 'ASSEMBLE_EDITED_PART_SIZE', object, detail: `edited PNG is ${image.width}x${image.height}; assembled box ${part.record.w}x${part.record.h} is required` });
100
+ const actual = sha(edit.bytes);
101
+ if (actual !== receipt.sha256) problems.push({ code: 'ASSEMBLE_EDITED_PART_SHA256', object, detail: `edited bytes sha256 is ${actual}; receipt sha256 ${receipt.sha256} is required` });
102
+ }
103
+ refuseIfAny(problems);
104
+ for (const edit of edits) {
105
+ const part = placed.find(p => p.record.name === edit.receipt.part)!;
106
+ const old = part.image, record = part.record, context = contexts.get(part)!;
107
+ const stage = map.parts.find(p => p.name === record.name)!;
108
+ const previous = reader(stage.runs), preSeam = reader(stage.pre_seam_writer_runs);
109
+ const name = `edited_parts[${edit.index}]`;
110
+ let id = map.edits.indexOf(name) + 1;
111
+ if (id === 0) { map.edits.push(name); id = map.edits.length; }
112
+ const metadata: EditedPartProvenance = { edit: name, dir: edit.dir,
113
+ receipt: { part: edit.receipt.part, file: edit.receipt.file, sha256: edit.receipt.sha256, from_sha256: edit.receipt.from_sha256, editor: edit.receipt.editor },
114
+ changed_px: 0, changed_counted_px: 0, changed_excluded_px: 0, removed_opaque_px: 0 };
115
+ const next: PartStageMap = { name: stage.name, x: stage.x, y: stage.y, w: stage.w, h: stage.h,
116
+ excluded_px: 0, runs: [], pre_seam_writer_runs: [], edited_part: metadata };
117
+ const provenance: PixelProvenance = { unchanged_layer_px: 0, hand_px: 0, automatic_px: 0, edits: [], automatic: [],
118
+ ...(record.provenance?.depth === undefined ? {} : { depth: record.provenance.depth }), edited_part: metadata };
119
+ const counts = new Map<number, number>();
120
+ let opaque = 0, visible = 0, projected = 0, paintingGain = 0;
121
+ const baseline = context.baseline;
122
+ for (let p = 0; p < old.width * old.height; p++) {
123
+ const offset = p * 4, prior = previous(), priorSeam = preSeam();
124
+ const changed = !rgbaEqual(old.data, offset, edit.image.data, offset);
125
+ const counted = edit.image.data[offset + 3] > OPAQUE_ALPHA_ABOVE;
126
+ if (changed) {
127
+ metadata.changed_px++;
128
+ if (counted) metadata.changed_counted_px++; else metadata.changed_excluded_px++;
129
+ }
130
+ if (old.data[offset + 3] > OPAQUE_ALPHA_ABOVE && !counted) metadata.removed_opaque_px++;
131
+ if (!counted) { next.excluded_px++; append(next.runs, EXCLUDED_PIXEL); append(next.pre_seam_writer_runs, EXCLUDED_PIXEL); continue; }
132
+ opaque++;
133
+ const x = record.x + p % record.w, y = record.y + Math.floor(p / record.w);
134
+ const q = y * map.rig_size[0] + x;
135
+ if (context.visible?.data[q] === 1) visible++;
136
+ if (context.visible?.data[q] === 1 && context.projected?.data[q] === 1) projected++;
137
+ if (context.paintingGain?.data[q] === 1) paintingGain++;
138
+ const u = x - (baseline?.x ?? 0), v = y - (baseline?.y ?? 0);
139
+ const sameRaw = baseline !== null && u >= 0 && v >= 0 && u < baseline.image.width && v < baseline.image.height &&
140
+ rgbaEqual(edit.image.data, offset, baseline.image.data, (v * baseline.image.width + u) * 4);
141
+ const writer = changed ? sameRaw ? 0 : id : prior;
142
+ append(next.runs, writer);
143
+ append(next.pre_seam_writer_runs, !changed && writer === AUTOMATIC_WRITERS.seamOverride ? priorSeam : NOT_OVERRIDDEN_PIXEL);
144
+ if (writer === 0) provenance.unchanged_layer_px++;
145
+ else if (writer > 0) provenance.hand_px++;
146
+ else provenance.automatic_px++;
147
+ counts.set(writer, (counts.get(writer) ?? 0) + 1);
148
+ }
149
+ provenance.edits = map.edits.flatMap((edit, i) => counts.has(i + 1) ? [{ edit, px: counts.get(i + 1)! }] : []);
150
+ provenance.automatic = (Object.keys(AUTOMATIC_WRITERS) as AutomaticWriter[]).flatMap(stage => counts.has(AUTOMATIC_WRITERS[stage]) ? [{ stage, px: counts.get(AUTOMATIC_WRITERS[stage])! }] : []);
151
+ record.opaque_px = opaque;
152
+ // Visibility/projection masks describe the normal source passes. Intersect
153
+ // them with final alpha; newly painted pixels outside those masks are occluded.
154
+ record.visible_px = visible; record.occluded_px = opaque - visible;
155
+ record.visible_not_projected_px = visible - projected;
156
+ if (record.painting_extension_px !== undefined) record.painting_extension_px = paintingGain;
157
+ record.provenance = provenance;
158
+ const scalar = context.depthForEdit?.(edit.image);
159
+ if (scalar !== undefined) {
160
+ record.depth = scalar.reference;
161
+ part.depthImage = scalar.image;
162
+ context.depthClampedSamples = scalar.clampedSamples;
163
+ }
164
+ part.image = edit.image;
165
+ part.encodedBytes = edit.bytes;
166
+ map.parts[map.parts.indexOf(stage)] = next;
167
+ }
168
+ }
@@ -0,0 +1,210 @@
1
+ /** A source-bound painting reference for an existing, immutable parts manifest. */
2
+ import fs from 'node:fs';
3
+ import { createHash } from 'node:crypto';
4
+ import { basename, dirname, join, resolve } from 'node:path';
5
+ import { checkGeometry, sourceInRig, stageFields } from './assemble.ts';
6
+ import { parseEarlyConfig } from './config.ts';
7
+ import { PartsError } from './errors.ts';
8
+ import { PAINTING_IN_RIG_FILE, readParts } from './parts.ts';
9
+ import { decodePngBytes, encodePngBytes } from './raster/png.ts';
10
+
11
+ export const PAINTING_REFERENCE_SCHEMA = 'rig-parts-painting-reference/1';
12
+ export const PAINTING_REFERENCE_FILE = 'painting_in_rig.json';
13
+
14
+ export interface PaintingReference {
15
+ schema: typeof PAINTING_REFERENCE_SCHEMA;
16
+ manifest_sha256: string;
17
+ path: string;
18
+ sha256: string;
19
+ resample: 'lanczos3-rgb-opaque';
20
+ rig_size: [number, number];
21
+ }
22
+
23
+ export interface PaintingReferenceSeal { path: string; sha256: string }
24
+ export interface PaintingReferenceInput {
25
+ manifest: PaintingReferenceSeal;
26
+ source: PaintingReferenceSeal;
27
+ config: PaintingReferenceSeal;
28
+ }
29
+
30
+ /** The caller retains this execution trace outside the inspected package. */
31
+ export interface PaintingReferenceReceipt {
32
+ schema: 'rig-parts-painting-reference-write/1';
33
+ inputs: PaintingReferenceInput;
34
+ outputs: { declaration: PaintingReferenceSeal; image: PaintingReferenceSeal };
35
+ }
36
+
37
+ const hash = (bytes: Uint8Array): string => createHash('sha256').update(bytes).digest('hex');
38
+ const hex = (value: unknown): value is string => typeof value === 'string' && /^[a-f0-9]{64}$/.test(value);
39
+ const record = (value: unknown): value is Record<string, unknown> => value !== null && typeof value === 'object' && !Array.isArray(value);
40
+
41
+ function fail(code: string, object: string, detail: string): never {
42
+ throw new PartsError([{ code, object, detail }]);
43
+ }
44
+
45
+ function portable(value: unknown): value is string {
46
+ return typeof value === 'string' && value.trim().length > 0 && !/[:\\%?#\x00-\x1f]/.test(value)
47
+ && value.split('/').every(part => part !== '' && part !== '.' && part !== '..');
48
+ }
49
+
50
+ /** The six-key public sidecar grammar. Package/PNG binding is checked by its reader. */
51
+ export function parsePaintingReference(value: unknown, label = PAINTING_REFERENCE_FILE): PaintingReference {
52
+ const keys = ['schema', 'manifest_sha256', 'path', 'sha256', 'resample', 'rig_size'];
53
+ if (!record(value) || Object.keys(value).length !== keys.length || keys.some(key => !Object.hasOwn(value, key))
54
+ || value.schema !== PAINTING_REFERENCE_SCHEMA || !hex(value.manifest_sha256) || !portable(value.path)
55
+ || !hex(value.sha256) || value.resample !== 'lanczos3-rgb-opaque' || !Array.isArray(value.rig_size)
56
+ || value.rig_size.length !== 2
57
+ || !Number.isSafeInteger(value.rig_size[0]) || value.rig_size[0] <= 0
58
+ || !Number.isSafeInteger(value.rig_size[1]) || value.rig_size[1] <= 0) {
59
+ return fail('PARTS_PAINTING_REFERENCE_SCHEMA', label, 'requires exactly schema, manifest_sha256, portable path, sha256, resample and positive safe-integer rig_size [W,H]; restore the producer declaration');
60
+ }
61
+ return { schema: PAINTING_REFERENCE_SCHEMA, manifest_sha256: value.manifest_sha256,
62
+ path: value.path, sha256: value.sha256, resample: value.resample, rig_size: [value.rig_size[0], value.rig_size[1]] };
63
+ }
64
+
65
+ function readSealed(input: PaintingReferenceSeal, label: string): Buffer {
66
+ if (!record(input) || typeof input.path !== 'string' || !input.path.trim() || !hex(input.sha256)) {
67
+ return fail('PARTS_PAINTING_REFERENCE_INPUT', label, 'requires an explicit file path and expected lowercase SHA-256; supply the frozen input seal');
68
+ }
69
+ let bytes: Buffer;
70
+ try {
71
+ if (!fs.lstatSync(input.path).isFile()) throw new Error('requires a regular file without a symlink');
72
+ const descriptor = fs.openSync(input.path, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
73
+ try {
74
+ if (!fs.fstatSync(descriptor).isFile()) throw new Error('requires a regular file');
75
+ bytes = fs.readFileSync(descriptor);
76
+ } finally { fs.closeSync(descriptor); }
77
+ } catch (error) {
78
+ return fail('PARTS_PAINTING_REFERENCE_INPUT', input.path, `${label} is unreadable (${String(error)}); restore the sealed regular input`);
79
+ }
80
+ if (hash(bytes) !== input.sha256) return fail('PARTS_PAINTING_REFERENCE_HASH', input.path, `${label} differs from expected SHA-256 ${input.sha256}; restore the frozen input`);
81
+ return bytes;
82
+ }
83
+
84
+ function readJson(bytes: Uint8Array, label: string): unknown {
85
+ try { return JSON.parse(Buffer.from(bytes).toString('utf8')); }
86
+ catch { return fail('PARTS_PAINTING_REFERENCE_INPUT', label, 'requires readable JSON; restore the sealed manifest or config'); }
87
+ }
88
+
89
+ /** Existing output is usable only when it is a regular file with identical bytes. */
90
+ function existingOutput(path: string, expected: Uint8Array): boolean {
91
+ let descriptor: number | undefined;
92
+ try {
93
+ if (!fs.lstatSync(path).isFile()) fail('PARTS_PAINTING_REFERENCE_OUTPUT', path, 'is not a regular file; preserve it and resolve the output collision');
94
+ descriptor = fs.openSync(path, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
95
+ if (!fs.fstatSync(descriptor).isFile() || !fs.readFileSync(descriptor).equals(Buffer.from(expected))) {
96
+ fail('PARTS_PAINTING_REFERENCE_OUTPUT', path, 'already exists with different bytes; preserve the existing file and resolve the collision before retrying');
97
+ }
98
+ return true;
99
+ }
100
+ catch (error) {
101
+ if (error instanceof PartsError) throw error;
102
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false;
103
+ return fail('PARTS_PAINTING_REFERENCE_OUTPUT', path, `cannot inspect the destination (${String(error)}); restore its directory permissions`);
104
+ } finally {
105
+ if (descriptor !== undefined) fs.closeSync(descriptor);
106
+ }
107
+ }
108
+
109
+ /** Publish complete bytes with a no-replace link, including a concurrent exact retry. */
110
+ function publishFile(staged: string, target: string, bytes: Uint8Array): void {
111
+ try { fs.linkSync(staged, target); }
112
+ catch (error) {
113
+ if ((error as NodeJS.ErrnoException).code === 'EEXIST' && existingOutput(target, bytes)) return;
114
+ throw error;
115
+ }
116
+ }
117
+
118
+ /**
119
+ * Add the reference PNG and adjacent sidecar after validating all sealed inputs.
120
+ * The sidecar is the commit point. An interrupted writer can leave an unreferenced
121
+ * complete PNG; an exact retry verifies it and finishes the declaration. Each
122
+ * destination is published without replacement, so concurrent writers cannot
123
+ * overwrite accepted files. The caller holds independent input writers frozen.
124
+ */
125
+ export function writePaintingReference(input: PaintingReferenceInput): PaintingReferenceReceipt {
126
+ const manifestBytes = readSealed(input.manifest, 'manifest');
127
+ const sourceBytes = readSealed(input.source, 'source');
128
+ const configBytes = readSealed(input.config, 'config');
129
+ if (basename(input.manifest.path) !== 'parts.json') {
130
+ return fail('PARTS_PAINTING_REFERENCE_INPUT', input.manifest.path, 'requires the exact parts.json file; select the frozen parts manifest');
131
+ }
132
+ const directory = fs.realpathSync(dirname(resolve(input.manifest.path)));
133
+ const manifest = readParts(input.manifest.path);
134
+ const size = manifest.rig_size;
135
+ if (size.length !== 2 || !size.every(n => Number.isSafeInteger(n) && n > 0)) {
136
+ return fail('PARTS_PAINTING_REFERENCE_FRAME', input.manifest.path, 'rig_size must contain two positive safe integers; restore the recorded producer frame');
137
+ }
138
+ const config = parseEarlyConfig(readJson(configBytes, input.config.path), 'assemble');
139
+ let source: ReturnType<typeof decodePngBytes>;
140
+ try { source = decodePngBytes(sourceBytes, input.source.path); }
141
+ catch (error) { return fail('PARTS_PAINTING_REFERENCE_INPUT', input.source.path, `source PNG cannot be decoded (${String(error)}); restore the sealed original painting`); }
142
+ // Assemble records every run layer in ghost_px, including zero counts.
143
+ // A resolution-square single run has this census but no padding record.
144
+ const runKeys = Object.keys(manifest.ghost_px);
145
+ const hasHeadRun = runKeys.some(key => key.startsWith('head:'));
146
+ if (!runKeys.some(key => key.startsWith('full:'))) {
147
+ return fail('PARTS_PAINTING_REFERENCE_FRAME', input.manifest.path, 'ghost_px has no full-run census to bind the run mode; restore the original producer manifest');
148
+ }
149
+ const pad = manifest.single_run_pad;
150
+ if (hasHeadRun && pad !== undefined) {
151
+ return fail('PARTS_PAINTING_REFERENCE_FRAME', input.manifest.path, 'head-run census conflicts with single_run_pad; restore the original producer manifest');
152
+ }
153
+ if (!hasHeadRun) {
154
+ if (manifest.parts.some(part => part.from.startsWith('head:')) || config.assemble.plan.some(([, run]) => run === 'head')
155
+ || (config.assemble.extend_below_crop?.length ?? 0) > 0) {
156
+ return fail('PARTS_PAINTING_REFERENCE_FRAME', input.manifest.path, 'full-only run census conflicts with head-run part, plan or crop-extension references; supply the matching original config and manifest');
157
+ }
158
+ if (pad === undefined && (source.width !== config.seethrough.resolution || source.height !== config.seethrough.resolution)) {
159
+ return fail('PARTS_PAINTING_REFERENCE_FRAME', input.manifest.path, 'single-run source is not the resolution square and has no single_run_pad; restore its recorded producer padding');
160
+ }
161
+ if (pad !== undefined && (pad.file_size[0] !== source.width || pad.file_size[1] !== source.height || pad.side !== config.seethrough.resolution)) {
162
+ return fail('PARTS_PAINTING_REFERENCE_FRAME', input.manifest.path, 'single_run_pad file_size or side differs from sealed source/config; supply the original source and config');
163
+ }
164
+ }
165
+ const single = hasHeadRun ? null : { w: source.width, h: source.height };
166
+ const fields = stageFields(config, single);
167
+ const frame = checkGeometry({ sourceW: source.width, sourceH: source.height, ...fields });
168
+ if (frame.W !== size[0] || frame.H !== size[1] || frame.S !== manifest.scale_rig_per_source) {
169
+ return fail('PARTS_PAINTING_REFERENCE_FRAME', input.manifest.path, `recorded ${size.join('x')} at scale ${manifest.scale_rig_per_source} differs from the sealed source/config frame ${frame.W}x${frame.H} at scale ${frame.S}; supply the original source and config`);
170
+ }
171
+ const imageBytes = encodePngBytes(sourceInRig(source, size[0], size[1]));
172
+ const declaration = parsePaintingReference({ schema: PAINTING_REFERENCE_SCHEMA,
173
+ manifest_sha256: hash(manifestBytes), path: PAINTING_IN_RIG_FILE, sha256: hash(imageBytes),
174
+ resample: 'lanczos3-rgb-opaque', rig_size: size });
175
+ const declarationBytes = Buffer.from(JSON.stringify(declaration, null, 2) + '\n');
176
+ const imagePath = join(directory, PAINTING_IN_RIG_FILE);
177
+ const declarationPath = join(directory, PAINTING_REFERENCE_FILE);
178
+ const unchanged = (): void => {
179
+ readSealed(input.manifest, 'manifest');
180
+ readSealed(input.source, 'source');
181
+ readSealed(input.config, 'config');
182
+ if (fs.realpathSync(dirname(resolve(input.manifest.path))) !== directory) {
183
+ fail('PARTS_PAINTING_REFERENCE_INPUT', input.manifest.path, 'manifest directory moved; restore the frozen package location');
184
+ }
185
+ };
186
+ const receipt: PaintingReferenceReceipt = { schema: 'rig-parts-painting-reference-write/1',
187
+ inputs: { manifest: { ...input.manifest }, source: { ...input.source }, config: { ...input.config } },
188
+ outputs: { declaration: { path: declarationPath, sha256: hash(declarationBytes) }, image: { path: imagePath, sha256: hash(imageBytes) } } };
189
+ const imageExists = existingOutput(imagePath, imageBytes);
190
+ const declarationExists = existingOutput(declarationPath, declarationBytes);
191
+ unchanged();
192
+ if (imageExists && declarationExists) return receipt;
193
+ let stage: string | undefined;
194
+ try {
195
+ stage = fs.mkdtempSync(join(directory, '.painting-reference-'));
196
+ const stagedImage = join(stage, PAINTING_IN_RIG_FILE), stagedDeclaration = join(stage, PAINTING_REFERENCE_FILE);
197
+ fs.writeFileSync(stagedImage, imageBytes, { flag: 'wx' });
198
+ fs.writeFileSync(stagedDeclaration, declarationBytes, { flag: 'wx' });
199
+ unchanged();
200
+ publishFile(stagedImage, imagePath, imageBytes);
201
+ unchanged();
202
+ publishFile(stagedDeclaration, declarationPath, declarationBytes);
203
+ return receipt;
204
+ } catch (error) {
205
+ if (error instanceof PartsError) throw error;
206
+ return fail('PARTS_PAINTING_REFERENCE_WRITE', declarationPath, `publication failed (${String(error)}); preserve existing files and retry with the same input seals`);
207
+ } finally {
208
+ if (stage !== undefined) fs.rmSync(stage, { recursive: true, force: true });
209
+ }
210
+ }
package/src/parts.ts CHANGED
@@ -592,7 +592,14 @@ function checkOwnership(raw: unknown, object: string, fail: (code: string, objec
592
592
  function orderedProvenance(p: PixelProvenance): PixelProvenance {
593
593
  return { unchanged_layer_px: p.unchanged_layer_px, hand_px: p.hand_px, automatic_px: p.automatic_px,
594
594
  edits: p.edits.map(e => ({ edit: e.edit, px: e.px })), automatic: p.automatic.map(e => ({ stage: e.stage, px: e.px })),
595
- ...(p.depth === undefined ? {} : { depth: { kind: p.depth.kind, values: p.depth.values.map(v => ({ group: v.group, ...(v.bone === undefined ? {} : { bone: v.bone }), value: v.value })) } }) };
595
+ ...(p.depth === undefined ? {} : { depth: { kind: p.depth.kind, values: p.depth.values.map(v => ({ group: v.group, ...(v.bone === undefined ? {} : { bone: v.bone }), value: v.value })) } }),
596
+ ...(p.edited_part === undefined ? {} : { edited_part: {
597
+ edit: p.edited_part.edit, dir: p.edited_part.dir,
598
+ receipt: { part: p.edited_part.receipt.part, file: p.edited_part.receipt.file,
599
+ sha256: p.edited_part.receipt.sha256, from_sha256: p.edited_part.receipt.from_sha256, editor: p.edited_part.receipt.editor },
600
+ changed_px: p.edited_part.changed_px, changed_counted_px: p.edited_part.changed_counted_px,
601
+ changed_excluded_px: p.edited_part.changed_excluded_px, removed_opaque_px: p.edited_part.removed_opaque_px,
602
+ } }) };
596
603
  }
597
604
 
598
605
  function orderedTakenSource(source: TakenLayerSource): TakenLayerSource {
@@ -783,13 +790,14 @@ function show(v: unknown): string {
783
790
  }
784
791
 
785
792
  /** The same optional measurement contract for base and alternate records. */
786
- function checkProvenance(raw: unknown, opaque: unknown, object: string, fail: (code: string, object: string, detail: string) => void, hasScalar = false): void {
793
+ function checkProvenance(raw: unknown, opaque: unknown, object: string, fail: (code: string, object: string, detail: string) => void, hasScalar = false, identity?: { name: unknown; w: unknown; h: unknown }): void {
787
794
  const v = raw as PixelProvenance | null;
788
795
  const count = (n: unknown): boolean => Number.isSafeInteger(n) && (n as number) >= 0;
789
796
  const edit = (name: string): boolean => /^(cuts\[\d+\]|patches\[\d+\])$/.test(name) ||
797
+ (/^edited_parts\[\d+\]$/.test(name) && name === v?.edited_part?.edit) ||
790
798
  (/^(full|head):author:/.test(name) && readFrom(name) !== null);
791
799
  const shape = v !== null && typeof v === 'object' && !Array.isArray(v) &&
792
- Object.keys(v).filter(k => k !== 'depth').sort().join(',') === 'automatic,automatic_px,edits,hand_px,unchanged_layer_px' &&
800
+ Object.keys(v).filter(k => k !== 'depth' && k !== 'edited_part').sort().join(',') === 'automatic,automatic_px,edits,hand_px,unchanged_layer_px' &&
793
801
  [v.unchanged_layer_px, v.hand_px, v.automatic_px].every(count) && Array.isArray(v.edits) && Array.isArray(v.automatic) &&
794
802
  v.edits.every(e => e !== null && typeof e === 'object' && Object.keys(e).sort().join(',') === 'edit,px' && typeof e.edit === 'string' && edit(e.edit) && count(e.px) && e.px > 0) &&
795
803
  v.automatic.every(e => e !== null && typeof e === 'object' && Object.keys(e).sort().join(',') === 'px,stage' && typeof e.stage === 'string' && Object.hasOwn(AUTOMATIC_WRITERS, e.stage) && count(e.px) && e.px > 0) &&
@@ -804,6 +812,28 @@ function checkProvenance(raw: unknown, opaque: unknown, object: string, fail: (c
804
812
  const hand = p.edits.reduce((n, e) => n + e.px, 0), automatic = p.automatic.reduce((n, e) => n + e.px, 0);
805
813
  fail('PARTS_COUNTS_ADD_UP', object, `unchanged_layer_px ${p.unchanged_layer_px} + hand_px ${p.hand_px} + automatic_px ${p.automatic_px} = ${total}; opaque_px ${opaque} is required; edit subtotal ${hand} (hand_px ${p.hand_px} required), stage subtotal ${automatic} (automatic_px ${p.automatic_px} required)`);
806
814
  }
815
+ if (v !== null && typeof v === 'object' && 'edited_part' in v) {
816
+ const e = v.edited_part;
817
+ const keys = 'changed_counted_px,changed_excluded_px,changed_px,dir,edit,receipt,removed_opaque_px';
818
+ const nonempty = (value: unknown): value is string => typeof value === 'string' && value.trim().length > 0;
819
+ const relativePath = (value: unknown): boolean => nonempty(value) && !/^(?:[\\/]|[A-Za-z]:[\\/])/.test(value);
820
+ const valid = e !== null && e !== undefined && typeof e === 'object' && !Array.isArray(e) && Object.keys(e).sort().join(',') === keys &&
821
+ typeof e.edit === 'string' && /^edited_parts\[\d+\]$/.test(e.edit) && relativePath(e.dir) &&
822
+ [e.changed_px, e.changed_counted_px, e.changed_excluded_px, e.removed_opaque_px].every(count) &&
823
+ e.receipt !== null && typeof e.receipt === 'object' && !Array.isArray(e.receipt) &&
824
+ Object.keys(e.receipt).sort().join(',') === 'editor,file,from_sha256,part,sha256' &&
825
+ nonempty(e.receipt.part) && e.receipt.part === identity?.name && relativePath(e.receipt.file) && nonempty(e.receipt.editor) &&
826
+ [e.receipt.sha256, e.receipt.from_sha256].every(s => typeof s === 'string' && /^[a-f0-9]{64}$/.test(s));
827
+ if (!valid) fail('PARTS_FIELD_TYPE', object + ' edited_part', 'requires edited_parts[i], a config-relative dir, a receipt with the enclosing part name, dir-relative file, two lowercase sha256 hashes and editor, and four nonnegative safe integer change counts');
828
+ else {
829
+ const area = typeof identity?.w === 'number' && typeof identity.h === 'number' ? identity.w * identity.h : NaN;
830
+ if (!Number.isSafeInteger(area) || !count(opaque) || e.changed_px !== e.changed_counted_px + e.changed_excluded_px ||
831
+ e.changed_px > area || e.changed_counted_px > (opaque as number) || e.changed_excluded_px > area - (opaque as number) ||
832
+ e.removed_opaque_px > e.changed_excluded_px) {
833
+ fail('PARTS_COUNTS_ADD_UP', object + ' edited_part', `changed_px ${e.changed_px} must equal counted ${e.changed_counted_px} + excluded ${e.changed_excluded_px}; counted must fit opaque_px ${show(opaque)}, excluded must fit the remaining box pixels (area ${area}), and removed_opaque_px ${e.removed_opaque_px} must be at most changed_excluded_px`);
834
+ }
835
+ }
836
+ }
807
837
  if (v !== null && typeof v === 'object' && 'depth' in v) {
808
838
  const d = v.depth;
809
839
  const valid = !hasScalar && d !== null && typeof d === 'object' && !Array.isArray(d) &&
@@ -890,7 +920,7 @@ function checkParts(raw: unknown, path: string): PartsFile {
890
920
  if (k in r && !(Number.isInteger(r[k]) && (r[k] as number) >= 0)) fail('PARTS_FIELD_TYPE', `${label} field "${k}"`, `is ${show(r[k])}; a non-negative integer is required`);
891
921
  }
892
922
  const count = (k: string): number | null => (Number.isInteger(r[k]) && (r[k] as number) >= 0 ? (r[k] as number) : null);
893
- if ('provenance' in r) checkProvenance(r.provenance, r.opaque_px, label + ' provenance', fail, 'depth' in r);
923
+ if ('provenance' in r) checkProvenance(r.provenance, r.opaque_px, label + ' provenance', fail, 'depth' in r, { name: r.name, w: r.w, h: r.h });
894
924
  checkPaintingExtensionCount(r, label, fail);
895
925
  const [op, vis, occ, vnp] = ['opaque_px', 'visible_px', 'occluded_px', 'visible_not_projected_px'].map(count);
896
926
  if (held.length === VISIBILITY_KEYS.length && op !== null && vis !== null && occ !== null && vnp !== null) {
@@ -1126,7 +1156,7 @@ function checkParts(raw: unknown, path: string): PartsFile {
1126
1156
  if (!isPartName(r.name)) fail('PARTS_FIELD_TYPE', `${recordAt} field "name"`, `is ${show(r.name)}; a file-name-safe part name is required`);
1127
1157
  if ('depth' in r) problems.push(...partDepthProblems(r.depth, `${recordAt} depth`));
1128
1158
  const part817 = typeof r.name === 'string' ? `part "${r.name}"` : `records[${j}]`;
1129
- if ('provenance' in r) checkProvenance(r.provenance, r.opaque_px, `${at} ${part817} provenance`, fail, 'depth' in r);
1159
+ if ('provenance' in r) checkProvenance(r.provenance, r.opaque_px, `${at} ${part817} provenance`, fail, 'depth' in r, { name: r.name, w: r.w, h: r.h });
1130
1160
  checkPaintingExtensionCount(r, `${at} ${part817}`, fail);
1131
1161
  const l = r[LIMB_KEY];
1132
1162
  if (typeof l !== 'object' || l === null || Array.isArray(l) || !('cap' in l)) return;
package/src/provenance.ts CHANGED
@@ -3,6 +3,7 @@ import { OPAQUE_ALPHA_ABOVE } from './layers.ts';
3
3
  import type { PartRecord } from './parts.ts';
4
4
  import type { AuthoredUnitDepth } from './authoredunit.ts';
5
5
  import { crop, type Raster } from './raster/index.ts';
6
+ import type { EditedPartProvenance } from './editedparts.ts';
6
7
 
7
8
  /** Negative IDs distinguish automatic writes from positive, config-indexed hand edits. */
8
9
  export const AUTOMATIC_WRITERS = {
@@ -16,6 +17,8 @@ export const EXCLUDED_PIXEL = -2147483648;
16
17
  export const NOT_OVERRIDDEN_PIXEL = -2147483647;
17
18
  export const STAGE_MAP_FILE = 'stage-map.json';
18
19
  export interface PartStageMap {
20
+ /** Whole-file receipt, independent of the final-opaque writer partition. */
21
+ edited_part?: EditedPartProvenance;
19
22
  name: string;
20
23
  x: number;
21
24
  y: number;
@@ -38,6 +41,8 @@ export interface StageMap {
38
41
  }
39
42
 
40
43
  export interface PixelProvenance {
44
+ /** Receipt covers unchanged and transparent pixels as well as changed ones. */
45
+ edited_part?: EditedPartProvenance;
41
46
  /** Scalar transport omitted only for fully explicit unit consumers (#877). */
42
47
  depth?: AuthoredUnitDepth;
43
48
  unchanged_layer_px: number;