@rig-c/parts 2.38.0 → 2.39.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/cli.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env bun
2
2
  import { diffComponentsCommand } from './src/diffcomponents.ts';
3
3
  import { applyTakenLayers } from './src/takelayers.ts';
4
- import { applyDepth, prepareDepth } from './src/depthworkflow.ts';
4
+ import { applyDepth, bindDepthMap, prepareDepth } from './src/depthworkflow.ts';
5
5
  /**
6
6
  * rig-parts — one painting and its See-through layers in, Spine-ready parts
7
7
  * and rig specs out, verified through rig-c.
@@ -82,6 +82,10 @@ usage:
82
82
  Write per-part inference PNGs on neutral gray, upscaled and padded as
83
83
  declared, plus a source-hashed manifest. No model is bundled or called.
84
84
 
85
+ rig-parts depth-bind --map <numeric-map.json> --input <prepared.png> --part <name>
86
+ Write <map>.binding.json with both file hashes; never overwrite a receipt.
87
+ Attests the current files, not that inference used this input.
88
+
85
89
  rig-parts depth-apply --parts <assembled-dir> --manifest <manifest.json> --config <depth-recipe.json> --rig-config <config.json> --out <empty-dir>
86
90
  Register floating-point JSON depth or signed normals, normalize inside
87
91
  alpha >=128, apply declared median/relief and group near/zScale/pivot,
@@ -1172,6 +1176,7 @@ function printLayerTable(set: LayerSet): void {
1172
1176
  const TAKES = {
1173
1177
  'check-parts': { valued: ['--parts', '--out'], switches: ['--json'] },
1174
1178
  'diff-components': { valued: ['--stack', '--painting', '--parts', '--figure', '--floor', '--threshold', '--out', '--verify'], switches: [] },
1179
+ 'depth-bind': { valued: ['--map', '--input', '--part'], switches: [] },
1175
1180
  'depth-prepare': { valued: ['--parts', '--config', '--out'], switches: [] },
1176
1181
  'depth-apply': { valued: ['--parts', '--manifest', '--config', '--rig-config', '--out'], switches: [] },
1177
1182
  layers: { valued: ['--export', '--template', '--canvas', '--full', '--source', '--config'], switches: [] },
@@ -2479,6 +2484,17 @@ function cmdDepthPrepare(args: string[]): number {
2479
2484
  } catch (error) { return printRefusal(error); }
2480
2485
  }
2481
2486
 
2487
+ function cmdDepthBind(args: string[]): number {
2488
+ const f = flags(args, 'depth-bind', ['--map', '--input', '--part']);
2489
+ if (typeof f === 'string') return usage(f);
2490
+ try {
2491
+ const result = bindDepthMap({ map: f.get('--map')!, input: f.get('--input')!, part: f.get('--part')! });
2492
+ console.log(`depth-bind: part "${result.part}" mapSha256=${result.mapSha256} inputSha256=${result.inputSha256}; wrote map binding receipt`);
2493
+ console.log('depth-bind: binds these files at invocation; does not prove the map was inferred from this input');
2494
+ return EXIT_OK;
2495
+ } catch (error) { return printRefusal(error); }
2496
+ }
2497
+
2482
2498
  function cmdDepthApply(args: string[]): number {
2483
2499
  const f = flags(args, 'depth-apply', ['--parts', '--manifest', '--config', '--rig-config', '--out']);
2484
2500
  if (typeof f === 'string') return usage(f);
@@ -2503,6 +2519,7 @@ function main(argv: string[]): number | Promise<number> {
2503
2519
  if (command === 'diff-components') return cmdDiffComponents(rest);
2504
2520
  if (command === 'layers') return cmdLayers(rest);
2505
2521
  if (command === 'depth-prepare') return cmdDepthPrepare(rest);
2522
+ if (command === 'depth-bind') return cmdDepthBind(rest);
2506
2523
  if (command === 'depth-apply') return cmdDepthApply(rest);
2507
2524
  if (command === 'sheet') return cmdSheet(rest);
2508
2525
  if (command === 'rig') return cmdRig(rest);
package/docs/AUTHORING.md CHANGED
@@ -1122,6 +1122,23 @@ final-alpha partition and resolve replacement writer IDs through the sidecar's
1122
1122
  receipt-associated; this does not exempt other config shapes or baseline
1123
1123
  inputs from their existing source/receipt checks.
1124
1124
 
1125
+ At admission, `assemble` also prints an `edited part front colour:` measurement
1126
+ line for each receipted part (issue #1290): surviving pixels (`alpha > 8`) that
1127
+ the edit changed or added against the base part (`from_sha256`), where the
1128
+ painting pixel's raw-plan owner (`rawPaintingOwner`, the last `assemble.plan`
1129
+ layer with `alpha >= 128`) is a different part drawn in front and the edited
1130
+ RGB lies within `ERROR_LIMIT` (`40`, max channel) of the painting. A positive
1131
+ count means the edited back part carries the front part's painting colour under
1132
+ that front part (hidden at rest while the front part covers it, exposed as a
1133
+ stain when the front part moves); the line reports the edited part, each front
1134
+ owner, the pixel count and the rig-pixel bounding box `[x, y, w, h]`, or `0 px,
1135
+ front owner none, box none` when none. With no declared limit it is a
1136
+ measurement only, never a pass or a refusal. To clear a positive count, remove
1137
+ the front part's colour from the hidden overlap of the edited PNG in the image
1138
+ editor — keep the base part's pixels there or fill the hidden area with the
1139
+ back part's own surface colour rather than sampling the composite painting —
1140
+ and update the receipt's `sha256`.
1141
+
1125
1142
  All replacement refusals happen before output emission, including when an
1126
1143
  output directory already contains a successful build. The folder and every
1127
1144
  existing file remain unchanged. Each code and its remedy is listed in
@@ -8130,6 +8147,7 @@ is declared, never inferred from a filename or guessed from art.
8130
8147
  ```sh
8131
8148
  rig-parts depth-prepare --parts assembled --config depth.json --out inference
8132
8149
  # A provider reads inference/*.png and writes the declared floating-point maps.
8150
+ rig-parts depth-bind --map face.json --input inference/face.png --part face
8133
8151
  rig-parts depth-apply --parts assembled --manifest inference/manifest.json --config depth.json --rig-config config.json --out mapped
8134
8152
  rig-parts rig --parts mapped --config mapped/config.json --out compiled
8135
8153
  ```
@@ -8156,11 +8174,14 @@ declares `near`, positive `zScale` and `pivot`; optional `unitDepths` explicitly
8156
8174
  replaces that group's rigid depths. `clear` explicitly lists part references to
8157
8175
  remove, including any small units intended to sample the surface. Unselected
8158
8176
  parts retain their artwork and depth references. The output config copies the
8159
- original, sets the declared group pivots/unit depths, and relocates animation,
8160
- requirements and control-skeleton file paths. Built-in skeleton names remain
8161
- names. A selected part whose provenance records `depth.kind: "authored-unit"`
8162
- is refused before output (`DEPTH_AUTHORED_UNIT_CONFLICT`); apply does not invent
8163
- a transition to a transported scalar reference. Unselected authored units keep
8177
+ original, sets the declared group pivots/unit depths, and relocates every file
8178
+ reference `configFileReferences` declares, including `assemble.edited_parts`
8179
+ receipt files, through that reference's `set`
8180
+ ([STABILITY](STABILITY.md#programmatic-config-file-references)). Built-in
8181
+ skeleton names remain names. A selected part whose provenance records
8182
+ `depth.kind: "authored-unit"` is refused before output
8183
+ (`DEPTH_AUTHORED_UNIT_CONFLICT`); apply does not invent a transition
8184
+ to a transported scalar reference. Unselected authored units keep
8164
8185
  their original representation. Roles and draw order stay the author's.
8165
8186
 
8166
8187
  Maps are UTF-8 JSON `{"spec":"rig-parts-map/1","width":2,"height":2,
@@ -8174,6 +8195,33 @@ whole prepared image and crops its declared padding before reduction. Scalar
8174
8195
  maps use float32 BOX reduction. Normal sources require signed image-axis XYZ
8175
8196
  (x right, y down), not an RGB normal preview.
8176
8197
 
8198
+ Each map may carry a parts-owned receipt at `<map filename>.binding.json`
8199
+ (for `face.json`, `face.json.binding.json`). Call `depth-bind --map face.json --input inference/face.png --part face` when
8200
+ the provider produces that map. The writer validates the numeric map and PNG,
8201
+ computes both SHA-256 values itself, and exclusively creates the receipt beside
8202
+ the map; it refuses to overwrite existing evidence. Never bind an old map to
8203
+ a freshly prepared input. The resulting receipt has this shape:
8204
+
8205
+ ```json
8206
+ {"spec":"rig-parts-depth-map-binding/1","part":"face","mapSha256":"<64 lowercase hex digits>","inputSha256":"<64 lowercase hex digits>"}
8207
+ ```
8208
+
8209
+ These are the only receipt fields. `part` must match the selected part;
8210
+ `mapSha256` hashes the numeric JSON file's bytes; `inputSha256` hashes the exact
8211
+ prepared inference PNG, matching the manifest row. Apply validates present
8212
+ receipts before writing anything. A changed map or inference input refuses with
8213
+ `DEPTH_MAP_BINDING`, naming the part, found and required hashes, and the remedy:
8214
+ re-run depth for these inputs, then call
8215
+ `rig-parts depth-bind --map <numeric-map.json> --input <prepared.png> --part <name>`. Malformed
8216
+ present receipts also refuse. Symlinked receipts, including dangling links, are
8217
+ refused; a regular file is required. Preparing again never rebinds a map.
8218
+ Under the compatibility policy dated **2026-11-16**, a missing receipt preserves
8219
+ legacy output bytes and exits, with one `DEPTH_MAP_BINDING_ABSENT` WARN per
8220
+ selected map on stderr. This is unverified inference-input identity, not a
8221
+ binding pass. The provider flow calls the writer when producing a map. The writer binds these
8222
+ files at invocation; it cannot prove the map was inferred from that input.
8223
+ Parts does not run inference or invent provenance.
8224
+
8177
8225
  Apply computes `u=(raw-median(raw))/(p95-p5)` inside original alpha >=128,
8178
8226
  using linear percentiles, then `Z=median+relief*u`. A flat map requires explicit
8179
8227
  relief 0. Encode `Z/zScale` for near white, `1-Z/zScale` for near black, clip to
@@ -8251,6 +8299,8 @@ by `rig`, so their output requires no alternate compiler or dependency pin.
8251
8299
  | <a id="DEPTH_INPUT_JSON"></a>`DEPTH_INPUT_JSON` | malformed numeric or configuration JSON | write valid finite JSON |
8252
8300
  | <a id="DEPTH_PART_RESOLVES"></a>`DEPTH_PART_RESOLVES` | selected or cleared name absent from parts.json | use the assembled part name |
8253
8301
  | <a id="DEPTH_OUTPUT_EMPTY"></a>`DEPTH_OUTPUT_EMPTY` | nonempty output or output containing an input | choose a separate absent or empty directory |
8302
+ | <a id="DEPTH_MAP_BINDING"></a>`DEPTH_MAP_BINDING` | malformed present map receipt, wrong part, map hash or inference-input hash | re-run depth for these inputs, then `rig-parts depth-bind --map <numeric-map.json> --input <prepared.png> --part <name>` |
8303
+ | <a id="DEPTH_MAP_BINDING_ABSENT"></a>`DEPTH_MAP_BINDING_ABSENT` | WARN only: no receipt, compatibility policy dated 2026-11-16 | legacy behavior is retained; re-run depth for these inputs, then `rig-parts depth-bind --map <numeric-map.json> --input <prepared.png> --part <name>` |
8254
8304
  | <a id="DEPTH_INPUT_BINDING"></a>`DEPTH_INPUT_BINDING` | changed recipe, art, part record, crop, padding or inference PNG | prepare again for these exact inputs |
8255
8305
  | <a id="DEPTH_MAP_FORMAT"></a>`DEPTH_MAP_FORMAT` | wrong numeric schema, channels, shape, count, unknown field or nonfinite element | provide the declared float JSON map, not a preview |
8256
8306
  | <a id="DEPTH_MAP_SIZE"></a>`DEPTH_MAP_SIZE` | map dimensions differ from its explicit frame | use the registered part, enlarged art or padded input grid |
@@ -8654,25 +8704,43 @@ Internal `SeamSupport.drawings` never enters check JSON. Named requirement
8654
8704
 
8655
8705
  Import `configFileReferences` and, for annotations, `ConfigFileReference` from
8656
8706
  `@rig-c/parts/src/config.ts` (issue #1134). Pass the JSON-parsed config object before
8657
- loading it. Each result exposes `at`, the dotted field path, `value`, the path
8658
- as declared, and `set(next)`, which writes back to that field. Enumeration
8707
+ loading it. Each result exposes `at`, the dotted field path, `value`, the file
8708
+ path, and `set(next)`, which writes back to that field. Enumeration
8659
8709
  leaves the object unchanged, skips absent, empty and non-string fields, and
8660
8710
  excludes built-in skeleton names. It performs no validation or file reads;
8661
8711
  use the normal loader for diagnostics.
8662
8712
 
8663
8713
  ```ts
8664
8714
  import { configFileReferences } from '@rig-c/parts/src/config.ts';
8665
- import { dirname, resolve } from 'node:path';
8715
+ import { dirname, relative, resolve } from 'node:path';
8666
8716
 
8667
8717
  for (const reference of configFileReferences(raw)) {
8668
- reference.set(resolve(dirname(sourceConfig), reference.value));
8718
+ const target = resolve(dirname(sourceConfig), reference.value);
8719
+ reference.set(relative(dirname(destinationConfig), target).replaceAll('\\', '/'));
8669
8720
  }
8670
8721
  ```
8671
8722
 
8672
- Here `sourceConfig` is the absolute original config filename and `raw` is its
8673
- JSON-parsed object. Serialize that object at the destination after copying any
8674
- referenced files; callers that copy files can instead set their new relative
8675
- paths. The enumerator derives membership from the loader's own declarations.
8723
+ Here `sourceConfig` and `destinationConfig` are absolute config filenames and
8724
+ `raw` is the source's JSON-parsed object. Serialize it at `destinationConfig`;
8725
+ the relative paths keep pointing to the original files. Callers that copy files
8726
+ can instead set paths to the copies, relative to the destination config.
8727
+
8728
+ The declared fields are `requirements`, `motion.animations_from`, non-built-in
8729
+ `generation.control.skeleton`, each `assemble.occluders[i].image` and optional
8730
+ `plate`, and `assemble.edited_parts.receipts[i].file`. Each edited receipt's
8731
+ value joins its shared `dir` and its `file` with POSIX path semantics; the
8732
+ directory itself is not a reference. Its setter uses normalized POSIX segments,
8733
+ independent of the cwd, and reads the live `dir` on each call. When the target is
8734
+ representable under that directory, `dir` and every sibling receipt remain
8735
+ byte-for-byte unchanged. Otherwise it rebases `dir` to the normalized lexical
8736
+ common prefix with the target (`.` for an empty prefix), rewriting sibling files
8737
+ to preserve their original config-relative targets. This also applies to setters
8738
+ from the same enumeration after a rebase; enumerate again to read updated values.
8739
+ Invalid directories and invalid sibling fields remain for the loader to diagnose.
8740
+ Keep edited targets config-relative: an absolute
8741
+ target, including Windows absolute forms, is preserved as an absolute `file`
8742
+ and refused by the loader's existing `CONFIG_FIELD_TYPE`. This does not change
8743
+ the edited-parts reader or its refusals.
8676
8744
 
8677
8745
  `checkFileReferences(raw, configFile, requirements?)` and `CheckFileReference`
8678
8746
  are exported from the same `@rig-c/parts/src/config.ts` subpath (issue #1138).
package/docs/STABILITY.md CHANGED
@@ -29,6 +29,28 @@ below). A build's bytes are not promised across versions. A later version may mo
29
29
  them, and when it does, the change that moves them declares which bytes and why (the
30
30
  winding change of #133 is the example: [MIGRATION.md](MIGRATION.md)).
31
31
 
32
+ ## Provider-map input identity
33
+
34
+ Issue #1284 adds optional parts-owned `<map>.binding.json` receipts, spec
35
+ `rig-parts-depth-map-binding/1`, with exactly `spec`, `part`, `mapSha256` and
36
+ `inputSha256`. The SHA-256 values are lowercase 64-digit hexadecimal hashes of
37
+ the numeric map file and its consumed prepared inference PNG. A present receipt
38
+ must match the selected part, current map bytes and manifest `inputSha256`;
39
+ otherwise `DEPTH_MAP_BINDING` refuses before any output write. A malformed present
40
+ receipt also refuses; symlinked receipts (including dangling links) are refused.
41
+ The depth recipe and prepare manifest are unchanged.
42
+
43
+ Compatibility policy dated **2026-11-16**: an absent receipt retains the shipped
44
+ map behavior, output bytes and success exit, adding one stderr WARN named
45
+ `DEPTH_MAP_BINDING_ABSENT` per selected map. Absence does not establish provenance.
46
+ This follows the stable-item meaning promise above: existing maps remain accepted
47
+ inside the major version. A matching receipt changes no output bytes or report
48
+ keys. Preparing fresh inputs does not create or update a map receipt. Call `depth-bind` when inference produces the map: it computes both hashes and
49
+ exclusively writes the receipt beside the map, refusing to overwrite evidence.
50
+ It binds the files at invocation and cannot prove that inference used that input.
51
+ See
52
+ [Per-part provider maps](AUTHORING.md#per-part-provider-maps-897).
53
+
32
54
  ## Parts-stage integrity report
33
55
 
34
56
  `rig-parts check-parts --parts <assembled-dir> --out <disjoint-report-dir>
@@ -137,9 +159,26 @@ Each reference has `at: string` (a dotted config field), `value: string`
137
159
  on the supplied object. Enumeration itself does not mutate, validate, read files,
138
160
  or resolve paths. Empty and non-string values are omitted; invalid fields remain
139
161
  for the loader to diagnose. Built-in control skeleton names are excluded.
140
- The loader's file-field declarations determine membership; no separate list is
141
- maintained. Resolve `value` against the source config directory when relocating.
142
- Existing deep package paths remain available.
162
+ Declared references are `requirements`, `motion.animations_from`, non-built-in
163
+ `generation.control.skeleton`, each `assemble.occluders[i].image` and optional
164
+ `plate`, then each `assemble.edited_parts.receipts[i].file` (issue #1281).
165
+ An edited receipt's `value` is `posix.join(dir, file)`, relative to the config;
166
+ there is no `edited_parts.dir` reference. Its `set(next)` takes a config-relative
167
+ path and derives `file` from normalized POSIX segments without resolving either
168
+ operand against the process cwd. If the target is representable under the current
169
+ `dir`, that directory and every sibling receipt remain byte-for-byte unchanged.
170
+ Otherwise, `dir` becomes its normalized lexical common prefix with the target
171
+ (`.` for an empty prefix), and sibling files are rewritten to preserve their
172
+ original config-relative targets. Setters read the live directory, including
173
+ after another setter from the same enumeration rebases it. Invalid directories
174
+ and invalid sibling fields remain for the existing loader diagnostics.
175
+ Absolute targets, including Windows absolute forms, remain absolute in `file`
176
+ and are refused by the existing `CONFIG_FIELD_TYPE` check at the next load.
177
+ When relocating a config, resolve each source value, then pass its path relative
178
+ to the destination config directory for edited receipts. Other setters retain
179
+ their existing path contract. Enumeration follows the loader and assemble reader
180
+ declarations; it adds no file reads or validation. Existing deep package paths
181
+ remain available.
143
182
 
144
183
  The same subpath exports `checkFileReferences(raw: unknown, configFile: string,
145
184
  requirements?: RequirementsFile): CheckFileReference[]` and the
@@ -208,6 +247,7 @@ defaults are the help's too, and none is guessed from the art.
208
247
  | --- | --- |
209
248
  | `diff-components` | `--stack`, `--painting`, `--parts`, `--floor`; optional `--threshold`, `--figure`; exactly one of `--out`, `--verify` (issue #1005; exhaustive native error inventory, with byte-bound reader) |
210
249
  | `depth-prepare` | `--parts`, `--config`, `--out` (issue #897; separate numeric-depth recipe) |
250
+ | `depth-bind` | `--map`, `--input`, `--part` (issue #1284; exclusive receipt creation from current file bytes) |
211
251
  | `depth-apply` | `--parts`, `--manifest`, `--config`, `--rig-config`, `--out` (issue #897; original character config is read-only) |
212
252
  | `layers` | one positional path: a wrapper directory, a `layers.json` or a `.psd`; with it, optional `--export` (a directory to write the wrapper form into, issue #359); or `--template` with `--canvas` and no path; or a positional head run with `--full`, `--source`, `--config` together for `PLAN_HEAD_GARMENT_OVERLAP` (issue #826) |
213
253
  | `sheet` | `--source`, `--layers` (repeatable), `--out`; optional `--cell`, `--cols` |
@@ -425,6 +465,12 @@ every number) are AUTHORING §3's tables, and the loader refuses any other by na
425
465
 
426
466
  ## Files this package writes
427
467
 
468
+ `depth-bind` writes `<map>.binding.json` beside the numeric map, spec
469
+ `rig-parts-depth-map-binding/1`, with `spec`, `part`, `mapSha256`, `inputSha256`
470
+ in that order. Hashes are computed from current map and input PNG bytes.
471
+ Exclusive creation refuses an existing receipt and preserves it unchanged.
472
+
473
+
428
474
  ### Source cover report
429
475
 
430
476
  `assemble` and the assemble stage of `build` always write `source_cover.json`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rig-c/parts",
3
- "version": "2.38.0",
3
+ "version": "2.39.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": {
package/src/assemble.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { sourceCoverRun, type SourceCoverReading } from './sourcecover.ts';
2
- import { replaceEditedParts, type EditedPartContext, type VerifiedEditedPart } from './editedparts.ts';
3
- import { paintingReceivers, rawPaintingOwner } from './paintingowner.ts';
2
+ import { replaceEditedParts, type EditedPartContext, type EditedPartFrontColourReading, type VerifiedEditedPart } from './editedparts.ts';
3
+ import { paintingReceivers, rawPaintingOwner, type PaintingOwner } from './paintingowner.ts';
4
4
  import { hiddenExtentProblems, type HiddenExtentDeclaration, type HiddenExtentSource } from './hiddenextent.ts';
5
5
  import { headBoxInside } from './headbox.ts';
6
6
  import { edgePairResiduals, type EdgeResidualReport } from './edgeresidual.ts';
@@ -4858,6 +4858,8 @@ export interface AssembleResult {
4858
4858
  softOcclusion?: SoftOcclusionReading[];
4859
4859
  /** Informational only; never serialized into parts.json. */
4860
4860
  cropClipped?: string[];
4861
+ /** Report-only front-part painting colour carried by an edited part (#1290). */
4862
+ editedPartFrontColours?: EditedPartFrontColourReading[];
4861
4863
  parts: PartsFile;
4862
4864
  /** In plan order, each cropped to its record's box. */
4863
4865
  images: PlacedPart[];
@@ -6158,16 +6160,35 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
6158
6160
  }
6159
6161
  return whole;
6160
6162
  };
6163
+ const rawPaintingOwnerForPlan = (): PaintingOwner => {
6164
+ let keepByPlanPart: ReadonlyMap<string, Mask> = occluderUnderKeepByPlanPart;
6165
+ if (projectRule !== 'visible' && occluderEntries.length > 0) {
6166
+ const localKeep = new Map<string, Mask>();
6167
+ for (const { declaration, guardMask } of occluderEntries) {
6168
+ for (const u of declaration.under) {
6169
+ let m = localKeep.get(u);
6170
+ if (m === undefined) {
6171
+ m = newMask(W, H);
6172
+ localKeep.set(u, m);
6173
+ }
6174
+ for (let p = 0; p < W * H; p++) if (guardMask.data[p] === 1) m.data[p] = 1;
6175
+ }
6176
+ }
6177
+ keepByPlanPart = localKeep;
6178
+ }
6179
+ const rawPlan = input.plan.map(([name, run, tag]) => {
6180
+ const layer = (run === 'full' ? fullPadded : depthHeadInput).layers.find(l => l.name === tag)!;
6181
+ return { name, raster: layerToRigSplit(layer, input.resolution, frame, run, occluderCoreMasks), keep: keepByPlanPart.get(name) ?? null };
6182
+ });
6183
+ if ((input.edgeSplits?.length ?? 0) > 0) applyEdgeSplits(input.edgeSplits!, new Map(rawPlan.map(p => [p.name, p.raster])), srcr);
6184
+ return rawPaintingOwner(rawPlan, W * H);
6185
+ };
6186
+ let paintingOwner: PaintingOwner | undefined;
6161
6187
  if (projectRule === 'visible') {
6162
6188
  // paintingEdges reads every image as the whole rig canvas. A plan part's image already is one; a patch is its cut,
6163
6189
  // placed at record.x / record.y, so it is placed on a canvas here. The step never writes a patch, so a copy is enough.
6164
6190
  const canvases = stack.map(onRig);
6165
- const rawPlan = input.plan.map(([name, run, tag]) => {
6166
- const layer = input[run].layers.find(l => l.name === tag)!;
6167
- return { name, raster: layerToRigSplit(layer, input.resolution, frame, run, occluderCoreMasks), keep: occluderUnderKeepByPlanPart.get(name) ?? null };
6168
- });
6169
- if ((input.edgeSplits?.length ?? 0) > 0) applyEdgeSplits(input.edgeSplits!, new Map(rawPlan.map(p => [p.name, p.raster])), srcr);
6170
- const owner = rawPaintingOwner(rawPlan, W * H);
6191
+ const owner = (paintingOwner = rawPaintingOwnerForPlan());
6171
6192
  const lineage: Array<[string, string]> = [
6172
6193
  ...input.cuts.map(c => [c.from, c.into] as [string, string]),
6173
6194
  ...Object.values(input.limbs ?? {}).flatMap(l => l.segments.flatMap(segment => [
@@ -6529,7 +6550,9 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
6529
6550
  return { ...original, runs: original.runs.map(remap), pre_seam_writer_runs: original.pre_seam_writer_runs.map(remap) };
6530
6551
  });
6531
6552
  }
6532
- if ((input.editedParts?.length ?? 0) > 0) replaceEditedParts(placed, input.editedParts!, new Set(input.plan.map(([name]) => name)), stageMap!, editContexts!);
6553
+ const editedPartFrontColours = (input.editedParts?.length ?? 0) > 0
6554
+ ? replaceEditedParts(placed, input.editedParts!, new Set(input.plan.map(([name]) => name)), stageMap!, editContexts!, srcr, paintingOwner ?? rawPaintingOwnerForPlan(), ERROR_LIMIT)
6555
+ : [];
6533
6556
  if (editContexts !== undefined) for (const p of placed) {
6534
6557
  const samples = editContexts.get(p)?.depthClampedSamples;
6535
6558
  if (samples === undefined) continue;
@@ -6579,6 +6602,7 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
6579
6602
  sourceCover,
6580
6603
  ...(softOcclusion.length === 0 ? {} : { softOcclusion }),
6581
6604
  ...(!single ? { cropClipped: cropClippedLines(plan, extend, (run, tag) => rig.get(`${run}:${tag}`) ?? null, frame) } : {}),
6605
+ ...(editedPartFrontColours.length === 0 ? {} : { editedPartFrontColours }),
6582
6606
  paintingInRig: srcr,
6583
6607
  ...(stageMap === undefined ? {} : { stageMap }),
6584
6608
  parts: {
package/src/build.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { readEditedParts } from './editedparts.ts';
1
+ import { editedPartFrontColourLines, readEditedParts } from './editedparts.ts';
2
2
  import { SOURCE_COVER_FILE, sourceCoverReport, type SourceCoverSet } from './sourcecover.ts';
3
3
  import { STAGE_MAP_FILE } from './provenance.ts';
4
4
  import { withoutCheckRows } from './checkrow.ts';
@@ -69,7 +69,7 @@ import { createHash } from 'node:crypto';
69
69
  import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
70
70
  import { basename, dirname, join, relative, resolve, sep } from 'node:path';
71
71
  import { type AnimFrame, EncodeError, encodeApng, encodeIndexedApng, INDEXED_DEFAULTS } from './apng.ts';
72
- import { assemble, type AssembleResult, boxOf, cutLines, edgeSplitLines, type ExcludedCount, excludedLines, setExclusions, islandLines, setIslandSources, type IslandCount, hiddenLines, SINGLE_RUN_FACE_TAGS, singleRunHeadBox, softOcclusionLine, driftLine, limbLines, FIGURE_MASK_FILE, figuresLine, groundWarning, holeKindsLine, holeLines, measurePinholes, measureRecomposite, pinholeProblems, pinholesLine, type ProjectRule, recomposite, recompositeRecord, scenePhrase, type SeamRule, sourceInRig, stageFields, uncoveredLine, underBox } from './assemble.ts';
72
+ import { assemble, type AssembleResult, boxOf, cutLines, edgeSplitLines, ERROR_LIMIT, type ExcludedCount, excludedLines, setExclusions, islandLines, setIslandSources, type IslandCount, hiddenLines, SINGLE_RUN_FACE_TAGS, singleRunHeadBox, softOcclusionLine, driftLine, limbLines, FIGURE_MASK_FILE, figuresLine, groundWarning, holeKindsLine, holeLines, measurePinholes, measureRecomposite, pinholeProblems, pinholesLine, type ProjectRule, recomposite, recompositeRecord, scenePhrase, type SeamRule, sourceInRig, stageFields, uncoveredLine, underBox } from './assemble.ts';
73
73
  import { allocationClause, type Reducer, stageBClause, unboundedClause } from './automesh.ts';
74
74
  import { residualClause } from './autoenvelope.ts';
75
75
  import { type AutoMotionCase, failingRows, idleSchedule, localRow, motionClause, motionDeformation, motionDocument, motionInput, motionRowText, motionStimulus, motionVerdict, noStimulusProblem, prepareComparison, type ReplayCandidate, runComparison, runPreparedComparison, sourceSelfFailure, stimulusMotion, withStimulus } from './automotion.ts';
@@ -1182,6 +1182,7 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
1182
1182
  );
1183
1183
  }
1184
1184
  for (const line of provenanceLines(result.parts.parts)) log(line);
1185
+ for (const line of editedPartFrontColourLines(result.editedPartFrontColours ?? [], ERROR_LIMIT)) log(line);
1185
1186
  for (const line of ownershipLines(result.parts.cut_ownership ?? [])) log(line);
1186
1187
  for (const alt of altBuilt) for (const line of [...provenanceLines(alt.record.records), ...ownershipLines(alt.record.cut_ownership ?? [])]) log(` set "${alt.record.name}" ${line.trimStart()}`);
1187
1188
  // Issue #256: one line per part from an author-made layer, so it never reads as See-through's. None without one.
package/src/config.ts CHANGED
@@ -95,7 +95,7 @@ import type { DepthConfig } from './depthsheets.ts';
95
95
  * the field is a non-empty string.
96
96
  */
97
97
  import { existsSync, readFileSync, statSync } from 'node:fs';
98
- import { dirname, isAbsolute, relative, resolve } from 'node:path';
98
+ import { dirname, isAbsolute, posix, relative, resolve } from 'node:path';
99
99
  import { RIG_BONE_INHERIT, RIG_SKIN_CONSTRAINT_KEYS, type RigBoneInherit, type RigConstraint, type RigSkinConstraintKey, type RigStop } from '@rig-c/core/rig';
100
100
  import { pyRound } from './round.ts';
101
101
  import { motionSeamProblems, type MotionSeamDeclaration } from './motionseams.ts';
@@ -1481,7 +1481,30 @@ export interface ConfigFileReference {
1481
1481
  set: (value: string) => void;
1482
1482
  }
1483
1483
 
1484
- /** Enumerate the same file fields that the loader resolves, preserving invalid fields for its diagnostics. */
1484
+ /** Normalized POSIX segments; neither operand is resolved against the cwd. */
1485
+ function editedPathSegments(path: string): string[] {
1486
+ return posix.normalize(path).split('/').filter(p => p !== '' && p !== '.');
1487
+ }
1488
+
1489
+ function editedPathPrefix(from: readonly string[], to: readonly string[]): number {
1490
+ let common = 0;
1491
+ while (common < from.length && common < to.length && from[common] === to[common]) common++;
1492
+ return common;
1493
+ }
1494
+
1495
+ /** Same absolute forms the relative-only loader refuses, including Windows forms. */
1496
+ function editedPathAbsolute(path: string): boolean {
1497
+ return isAbsolute(path) || /^(?:[\\/]|[A-Za-z]:[\\/])/.test(path);
1498
+ }
1499
+
1500
+ /** Relative segments for a target representable under dir, including rebased siblings. */
1501
+ function relativeEditedFile(dir: string, next: string): string {
1502
+ const from = editedPathSegments(dir), to = editedPathSegments(next);
1503
+ const common = editedPathPrefix(from, to);
1504
+ return [...from.slice(common).map(() => '..'), ...to.slice(common)].join('/');
1505
+ }
1506
+
1507
+ /** Enumerate loader and assemble file references, preserving invalid fields for their diagnostics. */
1485
1508
  export function configFileReferences(raw: unknown): ConfigFileReference[] {
1486
1509
  const out: ConfigFileReference[] = [];
1487
1510
  for (const field of Object.values(CONFIG_FILE_FIELDS)) {
@@ -1506,6 +1529,36 @@ export function configFileReferences(raw: unknown): ConfigFileReference[] {
1506
1529
  out.push({ at: `assemble.occluders[${i}].plate`, value: entry.plate, set: (next) => { entry.plate = next; } });
1507
1530
  }
1508
1531
  });
1532
+ // Issue #1281: receipt files cover this directory without declaring a directory input.
1533
+ const edited = isPlainObject(assemble) ? assemble.edited_parts : undefined;
1534
+ if (isPlainObject(edited) && typeof edited.dir === 'string' && edited.dir !== '' && Array.isArray(edited.receipts)) {
1535
+ const enumerationDir = edited.dir, receipts = edited.receipts;
1536
+ receipts.forEach((entry: unknown, i: number) => {
1537
+ if (!isPlainObject(entry) || typeof entry.file !== 'string' || entry.file === '') return;
1538
+ out.push({ at: `assemble.edited_parts.receipts[${i}].file`, value: posix.join(enumerationDir, entry.file), set: (next) => {
1539
+ // Preserve invalid absolute targets for the existing relative-only loader refusal.
1540
+ if (editedPathAbsolute(next)) { entry.file = next; return; }
1541
+ // A previous setter from this enumeration may have rebased the shared dir.
1542
+ const liveDir = edited.dir;
1543
+ if (typeof liveDir !== 'string' || liveDir.trim() === '' || editedPathAbsolute(liveDir)) {
1544
+ entry.file = next;
1545
+ return; // Do not repair invalid dirs or hide their existing loader diagnostics.
1546
+ }
1547
+ let dir: string = liveDir;
1548
+ const from = editedPathSegments(dir), to = editedPathSegments(next);
1549
+ if (from.filter(p => p === '..').length > to.filter(p => p === '..').length) {
1550
+ const rebased = from.slice(0, editedPathPrefix(from, to)).join('/') || '.';
1551
+ for (const sibling of receipts) {
1552
+ if (!isPlainObject(sibling) || typeof sibling.file !== 'string' || sibling.file.trim() === '' || editedPathAbsolute(sibling.file)) continue;
1553
+ sibling.file = relativeEditedFile(rebased, posix.join(dir, sibling.file));
1554
+ }
1555
+ edited.dir = rebased;
1556
+ dir = rebased;
1557
+ }
1558
+ entry.file = relativeEditedFile(dir, next);
1559
+ } });
1560
+ });
1561
+ }
1509
1562
  return out;
1510
1563
  }
1511
1564
 
@@ -3,9 +3,9 @@
3
3
  * the first output is emitted; output directories must be absent or empty.
4
4
  */
5
5
  import { createHash } from 'node:crypto';
6
- import { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, statSync, writeFileSync } from 'node:fs';
6
+ import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, statSync, writeFileSync } from 'node:fs';
7
7
  import { basename, dirname, join, relative, resolve, sep } from 'node:path';
8
- import { loadConfigAndAnimations, parseConfig } from './config.ts';
8
+ import { configFileReferences, loadConfigAndAnimations, parseConfig } from './config.ts';
9
9
  import { depthReading, readSourceDepth } from './depthsheets.ts';
10
10
  import { alphaSupport, depthMapFail as fail, floatBox, integrateNormals, mapToSheet, readNumericMap, type NumericMap } from './depthmaps.ts';
11
11
  import { depthImageReference, partImageReference, readParts } from './parts.ts';
@@ -13,7 +13,6 @@ import { readPartSet } from './propose.ts';
13
13
  import { decodePngBytes, encodePngBytes } from './raster/png.ts';
14
14
  import { resize } from './raster/resize.ts';
15
15
  import { connectedComponents } from './raster/components.ts';
16
- import { isSkeletonName } from './skeleton.ts';
17
16
  import { newRaster, type Raster } from './raster/types.ts';
18
17
 
19
18
  type Obj = Record<string, unknown>;
@@ -147,7 +146,72 @@ function extendIntegratedHeight(data: Float64Array, art: Raster): Float64Array {
147
146
  }
148
147
  return filled;
149
148
  }
150
- export function applyDepth(input: { parts: string; manifest: string; config: string; rigConfig: string; out: string }): Obj {
149
+ const MAP_BINDING_ABSENT = 'DEPTH_MAP_BINDING_ABSENT';
150
+ const BINDING_REMEDY = 're-run depth for these inputs, then rig-parts depth-bind --map <numeric-map.json> --input <prepared.png> --part <name>';
151
+ /** Bound diagnostic values; never echo a receipt payload. */
152
+ function bindingFound(value: unknown): string {
153
+ if (value === undefined) return 'absent';
154
+ if (value === null) return 'null';
155
+ if (Array.isArray(value)) return 'array';
156
+ if (typeof value === 'object') return 'object';
157
+ return JSON.stringify(value)?.slice(0, 96) ?? String(value);
158
+ }
159
+
160
+ /** Attest the two files available now, not the unobserved inference execution. */
161
+ export function bindDepthMap(input: { map: string; input: string; part: string }): Obj {
162
+ if (!input.part || input.part.startsWith('.') || /[\\/]/.test(input.part) || input.part.includes('\0')) {
163
+ fail('DEPTH_MAP_BINDING', 'depth-bind --part', `found ${bindingFound(input.part)}; required a nonempty plain part filename; ${BINDING_REMEDY}`);
164
+ }
165
+ const read = (file: string): Uint8Array => {
166
+ if (!existsSync(file) || !statSync(file).isFile()) return fail('DEPTH_INPUT_PRESENT', file, 'is missing or not a file; restore the declared input');
167
+ return readFileSync(file);
168
+ };
169
+ const mapBytes = read(input.map), inputBytes = read(input.input);
170
+ readNumericMap(readJson(input.map), input.part);
171
+ decodePngBytes(inputBytes, input.part);
172
+ const receipt = { spec: 'rig-parts-depth-map-binding/1', part: input.part, mapSha256: hash(mapBytes), inputSha256: hash(inputBytes) };
173
+ const target = input.map + '.binding.json';
174
+ // Exclusive creation preserves a previous attestation; all readers run first.
175
+ try { writeFileSync(target, text(receipt), { flag: 'wx' }); }
176
+ catch (error) {
177
+ const code = error !== null && typeof error === 'object' && 'code' in error ? String(error.code) : 'UNKNOWN';
178
+ const reason = code === 'EEXIST' ? 'already exists (EEXIST)' : `write failed (${code})`;
179
+ return fail('DEPTH_MAP_BINDING', `part "${input.part}"`, `receipt ${JSON.stringify(target)} ${reason}; required an absent receipt in a writable directory; keep existing evidence and use a new map filename; ${BINDING_REMEDY}`);
180
+ }
181
+ return receipt;
182
+ }
183
+
184
+ // existsSync follows symlinks; a dangling receipt is present malformed evidence.
185
+ function isReceiptLink(path: string): boolean {
186
+ try { return lstatSync(path).isSymbolicLink(); } catch { return false; }
187
+ }
188
+
189
+ /** Parts-owned provenance beside the numeric map; never inferred from a new prepare. */
190
+ function mapBinding(mapPath: string, bytes: Uint8Array, part: PreparedPart): string | undefined {
191
+ const receiptPath = mapPath + '.binding.json';
192
+ if (!existsSync(receiptPath) && !isReceiptLink(receiptPath)) return `WARN ${MAP_BINDING_ABSENT}: part "${part.part}" — no map binding receipt (compatibility policy dated 2026-11-16); applying legacy map without inference-input identity; ${BINDING_REMEDY}`;
193
+ const remedy = BINDING_REMEDY;
194
+ const refuse = (detail: string): never => fail('DEPTH_MAP_BINDING', `part "${part.part}"`, `${detail}; ${remedy}`);
195
+ if (!lstatSync(receiptPath).isFile()) return refuse('receipt found a symlink or nonregular file; required a regular file');
196
+ let raw: unknown;
197
+ try { raw = JSON.parse(readFileSync(receiptPath, 'utf8')) as unknown; }
198
+ catch { return refuse('receipt found unreadable or invalid JSON; required a readable JSON object'); }
199
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return refuse(`receipt found ${bindingFound(raw)}; required an object`);
200
+ const r = raw as Obj;
201
+ const sha = (v: unknown): v is string => typeof v === 'string' && /^[0-9a-f]{64}$/.test(v);
202
+ const unknown = Object.keys(r).filter(k => !['spec', 'part', 'mapSha256', 'inputSha256'].includes(k));
203
+ if (unknown.length) return refuse(`receipt found unknown key ${bindingFound(unknown[0])}; required only spec, part, mapSha256, inputSha256`);
204
+ if (r.spec !== 'rig-parts-depth-map-binding/1') return refuse(`receipt spec found ${bindingFound(r.spec)}; required "rig-parts-depth-map-binding/1"`);
205
+ if (r.part !== part.part) return refuse(`receipt part found ${bindingFound(r.part)}; required ${JSON.stringify(part.part)}`);
206
+ for (const key of ['mapSha256', 'inputSha256'] as const) {
207
+ if (!sha(r[key])) return refuse(`receipt ${key} found ${bindingFound(r[key])}; required 64 lowercase hexadecimal digits`);
208
+ }
209
+ const mapSha = hash(bytes);
210
+ if (r.mapSha256 !== mapSha) return refuse(`map sha found ${r.mapSha256}; required ${mapSha}`);
211
+ if (r.inputSha256 !== part.inputSha256) return refuse(`inference input sha found ${r.inputSha256}; required ${part.inputSha256}`);
212
+ return undefined;
213
+ }
214
+ export function applyDepth(input: { parts: string; manifest: string; config: string; rigConfig: string; out: string }, log: (line: string) => void = console.warn): Obj {
151
215
  const recipe = parseDepthRecipe(readJson(input.config)), expected = preparedParts(input.parts, recipe);
152
216
  const supplied = readJson(input.manifest);
153
217
  if (text(supplied) !== text(expected.manifest)) fail('DEPTH_INPUT_BINDING', input.manifest, 'does not match the recipe, parts.json, art hashes, crop or padding; run depth-prepare again for these exact inputs');
@@ -155,7 +219,7 @@ export function applyDepth(input: { parts: string; manifest: string; config: str
155
219
  const file = join(dirname(input.manifest), p.input);
156
220
  if (!existsSync(file) || hash(readFileSync(file)) !== p.inputSha256) fail('DEPTH_INPUT_BINDING', p.part, 'prepared inference PNG is missing or changed; restore its exact bytes or prepare again');
157
221
  }
158
- emptyOutput(input.out, [input.parts, input.config, input.manifest, input.rigConfig, ...Object.values(recipe.parts).map(p => resolve(dirname(input.config), p.map))]);
222
+ emptyOutput(input.out, [input.parts, input.config, input.manifest, input.rigConfig, ...Object.values(recipe.parts).flatMap(p => { const map = resolve(dirname(input.config), p.map); return [map, map + '.binding.json']; })]);
159
223
  const rawParts = object(readJson(join(input.parts, 'parts.json')), 'parts.json'), file = readParts(join(input.parts, 'parts.json'));
160
224
  for (const p of file.parts) if (Object.hasOwn(recipe.parts, p.name) && p.provenance?.depth?.kind === 'authored-unit') fail('DEPTH_AUTHORED_UNIT_CONFLICT', `part "${p.name}"`, 'has provenance.depth.kind "authored-unit"; a transported scalar reference cannot coexist with authored unit depth — retain the unit declaration or supply an explicitly reassembled scalar-compatible input; no automatic transition is made');
161
225
  loadConfigAndAnimations(input.rigConfig);
@@ -165,12 +229,11 @@ export function applyDepth(input: { parts: string; manifest: string; config: str
165
229
  if (group.unitDepths !== undefined) target.unitDepths = group.unitDepths;
166
230
  }
167
231
  // Keep relative paths portable when relocating the output directory with its inputs.
168
- const motion = raw.motion as Obj | undefined;
169
- if (typeof motion?.animations_from === 'string') motion.animations_from = relative(resolve(input.out), resolve(dirname(input.rigConfig), motion.animations_from));
170
- const control = (raw.generation as Obj | undefined)?.control as Obj | undefined;
171
- if (typeof control?.skeleton === 'string' && !isSkeletonName(control.skeleton)) control.skeleton = relative(resolve(input.out), resolve(dirname(input.rigConfig), control.skeleton));
172
- if (typeof raw.requirements === 'string') raw.requirements = relative(resolve(input.out), resolve(dirname(input.rigConfig), raw.requirements));
232
+ for (const ref of configFileReferences(raw)) {
233
+ ref.set(relative(resolve(input.out), resolve(dirname(input.rigConfig), ref.value)));
234
+ }
173
235
  parseConfig(raw);
236
+ const warnings: string[] = [];
174
237
  const writes = new Map<string, Uint8Array>(), rows: Obj[] = [], recs = rawParts.parts as Obj[];
175
238
  // Retain auxiliary art (including alternate sets) and diagnostics byte-for-byte.
176
239
  // Symlink inputs would obscure ownership and can escape this assembled directory.
@@ -197,6 +260,8 @@ export function applyDepth(input: { parts: string; manifest: string; config: str
197
260
  if (!Object.hasOwn(object(target.roles, `config.turn.${declaration.group}.roles`), name)) fail('DEPTH_GROUP_BINDING', name, `declared group ${declaration.group} does not name this part in its roles; register it explicitly`);
198
261
  const prepared = expected.manifest.parts.find(row => row.part === name) as PreparedPart;
199
262
  const mapPath = resolve(dirname(input.config), declaration.map), numeric = readNumericMap(readJson(mapPath), name), mapBytes = readFileSync(mapPath);
263
+ const warning = mapBinding(mapPath, mapBytes, prepared);
264
+ if (warning !== undefined) warnings.push(warning);
200
265
  const map = registeredMap(numeric, prepared, declaration.frame, name);
201
266
  let values: ArrayLike<number>, normal: ReturnType<typeof integrateNormals> | undefined;
202
267
  if (declaration.source === 'normals') {
@@ -235,5 +300,6 @@ export function applyDepth(input: { parts: string; manifest: string; config: str
235
300
  writeFileSync(join(input.out, 'parts.json'), text(rawParts));
236
301
  writeFileSync(join(input.out, 'config.json'), text(raw));
237
302
  writeFileSync(join(input.out, 'depth-report.json'), text(report));
303
+ for (const warning of warnings) log(warning);
238
304
  return report;
239
305
  }
@@ -10,6 +10,7 @@ import { decodePngBytes, encodePngBytes } from './raster/png.ts';
10
10
  import type { Mask, Raster } from './raster/types.ts';
11
11
  import type { PlacedPart } from './assemble.ts';
12
12
  import type { PartDepthReference } from './depthsheets.ts';
13
+ import type { PaintingOwner } from './paintingowner.ts';
13
14
 
14
15
  export interface EditedPartReceipt extends EditorReceipt { part: string }
15
16
  export interface EditedParts { dir: string; receipts: EditedPartReceipt[] }
@@ -29,6 +30,20 @@ export interface EditedPartProvenance {
29
30
  changed_excluded_px: number;
30
31
  removed_opaque_px: number;
31
32
  }
33
+ export interface EditedPartFrontColourOwner {
34
+ owner: string;
35
+ px: number;
36
+ /** Rig-pixel bounding box [x, y, w, h] of changed/added pixels under this front owner within ERROR_LIMIT of the painting. */
37
+ box: [number, number, number, number];
38
+ }
39
+ export interface EditedPartFrontColourReading {
40
+ edit: string;
41
+ part: string;
42
+ px: number;
43
+ /** Rig-pixel bounding box [x, y, w, h] across all front owners, or null when px === 0. */
44
+ box: [number, number, number, number] | null;
45
+ owners: EditedPartFrontColourOwner[];
46
+ }
32
47
  /** Only held for an edited build, including its region-take counterfactual. */
33
48
  export interface EditedPartContext {
34
49
  baseline: ValueBaseline | null;
@@ -83,7 +98,16 @@ function reader(runs: ReadonlyArray<readonly [number, number]>): () => number {
83
98
  }
84
99
 
85
100
  /** 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 {
101
+ export function replaceEditedParts(
102
+ placed: PlacedPart[],
103
+ edits: readonly VerifiedEditedPart[],
104
+ plan: ReadonlySet<string>,
105
+ map: StageMap,
106
+ contexts: ReadonlyMap<PlacedPart, EditedPartContext>,
107
+ painting: Raster,
108
+ owner: PaintingOwner,
109
+ errorLimit: number,
110
+ ): EditedPartFrontColourReading[] {
87
111
  const problems: Problem[] = [], seen = new Set<string>();
88
112
  for (const edit of edits) {
89
113
  const { receipt, image } = edit, part = placed.find(p => p.record.name === receipt.part);
@@ -101,6 +125,7 @@ export function replaceEditedParts(placed: PlacedPart[], edits: readonly Verifie
101
125
  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
126
  }
103
127
  refuseIfAny(problems);
128
+ const readings: EditedPartFrontColourReading[] = [];
104
129
  for (const edit of edits) {
105
130
  const part = placed.find(p => p.record.name === edit.receipt.part)!;
106
131
  const old = part.image, record = part.record, context = contexts.get(part)!;
@@ -118,6 +143,9 @@ export function replaceEditedParts(placed: PlacedPart[], edits: readonly Verifie
118
143
  ...(record.provenance?.depth === undefined ? {} : { depth: record.provenance.depth }), edited_part: metadata };
119
144
  const counts = new Map<number, number>();
120
145
  let opaque = 0, visible = 0, projected = 0, paintingGain = 0;
146
+ const partOwnerIndex = owner.names.indexOf(record.name);
147
+ const byOwner = new Map<number, { px: number; left: number; top: number; right: number; bottom: number }>();
148
+ let frontColourPx = 0, fcLeft = map.rig_size[0], fcTop = map.rig_size[1], fcRight = 0, fcBottom = 0;
121
149
  const baseline = context.baseline;
122
150
  for (let p = 0; p < old.width * old.height; p++) {
123
151
  const offset = p * 4, prior = previous(), priorSeam = preSeam();
@@ -132,6 +160,34 @@ export function replaceEditedParts(placed: PlacedPart[], edits: readonly Verifie
132
160
  opaque++;
133
161
  const x = record.x + p % record.w, y = record.y + Math.floor(p / record.w);
134
162
  const q = y * map.rig_size[0] + x;
163
+ if (changed && partOwnerIndex >= 0) {
164
+ const ownerIndex = owner.pixels[q];
165
+ if (ownerIndex > partOwnerIndex) {
166
+ const qOffset = q * 4;
167
+ const dMax = Math.max(
168
+ Math.abs(edit.image.data[offset] - painting.data[qOffset]),
169
+ Math.abs(edit.image.data[offset + 1] - painting.data[qOffset + 1]),
170
+ Math.abs(edit.image.data[offset + 2] - painting.data[qOffset + 2]),
171
+ );
172
+ if (dMax <= errorLimit) {
173
+ frontColourPx++;
174
+ if (x < fcLeft) fcLeft = x;
175
+ if (y < fcTop) fcTop = y;
176
+ if (x + 1 > fcRight) fcRight = x + 1;
177
+ if (y + 1 > fcBottom) fcBottom = y + 1;
178
+ const prev = byOwner.get(ownerIndex);
179
+ if (prev === undefined) {
180
+ byOwner.set(ownerIndex, { px: 1, left: x, top: y, right: x + 1, bottom: y + 1 });
181
+ } else {
182
+ prev.px++;
183
+ if (x < prev.left) prev.left = x;
184
+ if (y < prev.top) prev.top = y;
185
+ if (x + 1 > prev.right) prev.right = x + 1;
186
+ if (y + 1 > prev.bottom) prev.bottom = y + 1;
187
+ }
188
+ }
189
+ }
190
+ }
135
191
  if (context.visible?.data[q] === 1) visible++;
136
192
  if (context.visible?.data[q] === 1 && context.projected?.data[q] === 1) projected++;
137
193
  if (context.paintingGain?.data[q] === 1) paintingGain++;
@@ -164,5 +220,29 @@ export function replaceEditedParts(placed: PlacedPart[], edits: readonly Verifie
164
220
  part.image = edit.image;
165
221
  part.encodedBytes = edit.bytes;
166
222
  map.parts[map.parts.indexOf(stage)] = next;
223
+ const owners: EditedPartFrontColourOwner[] = [...byOwner.entries()]
224
+ .sort(([a], [b]) => a - b)
225
+ .map(([ownerIndex, b]) => ({
226
+ owner: owner.names[ownerIndex],
227
+ px: b.px,
228
+ box: [b.left, b.top, b.right - b.left, b.bottom - b.top],
229
+ }));
230
+ readings.push({
231
+ edit: name,
232
+ part: record.name,
233
+ px: frontColourPx,
234
+ box: frontColourPx === 0 ? null : [fcLeft, fcTop, fcRight - fcLeft, fcBottom - fcTop],
235
+ owners,
236
+ });
167
237
  }
238
+ return readings;
239
+ }
240
+
241
+ /** Measurement-only lines for front-part painting colour carried by an edited part (#1290). */
242
+ export function editedPartFrontColourLines(readings: readonly EditedPartFrontColourReading[], errorLimit: number): string[] {
243
+ return readings.flatMap(r =>
244
+ r.owners.length === 0
245
+ ? [` edited part front colour: part "${r.part}" (${r.edit}) 0 px, front owner none, box none (within ${errorLimit} of painting; measurement, no declared limit)`]
246
+ : r.owners.map(o => ` edited part front colour: part "${r.part}" (${r.edit}) front owner "${o.owner}" ${o.px} px, box [${o.box.join(', ')}] (within ${errorLimit} of painting; measurement, no declared limit)`),
247
+ );
168
248
  }
package/src/meshdraft.ts CHANGED
@@ -60,7 +60,7 @@
60
60
  * but the process is injected, exactly as `src/check.ts` and `src/build.ts` take it.
61
61
  */
62
62
  import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
63
- import { dirname, isAbsolute, join, resolve } from 'node:path';
63
+ import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
64
64
  import type { AlphaMask, MeasureRow, MeshQualityReport, MotionSchedule } from '@rig-c/core/mesh';
65
65
  import { compareMeshesInMotion, type MotionComparisonInput } from '@rig-c/core/meshcompare';
66
66
  import { MeshReductionError } from '@rig-c/core/mesh';
@@ -728,13 +728,17 @@ export function relativeConfigPaths(_configDir: string, o: Json): RelativeConfig
728
728
 
729
729
  /**
730
730
  * A config the stage builds, written as `<dir>/config.json`: `text` (the author's config at `configPath`) with
731
- * `meshes.<part>` replaced for every part in `meshes`, and each of its {@link relativeConfigPaths} made absolute, so
732
- * it resolves to the file the author's config names. `remesh` (issue #495) builds through the same door.
731
+ * `meshes.<part>` replaced for every part in `meshes`, and each of its {@link relativeConfigPaths} rebased to
732
+ * the file the author's config names. Edited receipt files stay relative to the destination config directory;
733
+ * other references become absolute. `remesh` (issue #495) builds through the same door.
733
734
  */
734
735
  export function scratchConfig(configPath: string, text: string, dir: string, meshes: ReadonlyMap<string, unknown>): string {
735
736
  const configDir = dirname(resolve(configPath));
736
737
  const o = JSON.parse(text) as Json;
737
- for (const r of relativeConfigPaths(configDir, o)) r.set(resolve(configDir, r.value));
738
+ for (const r of relativeConfigPaths(configDir, o)) {
739
+ const target = resolve(configDir, r.value);
740
+ r.set(r.at.startsWith('assemble.edited_parts.receipts[') ? relative(resolve(dir), target).replaceAll('\\', '/') : target);
741
+ }
738
742
  o.meshes = { ...(o.meshes as Json), ...Object.fromEntries(meshes) };
739
743
  mkdirSync(dir, { recursive: true });
740
744
  writeFileSync(join(dir, 'config.json'), `${JSON.stringify(o, null, 2)}\n`);