@rig-c/parts 2.38.1 → 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 |
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>
@@ -225,6 +247,7 @@ defaults are the help's too, and none is guessed from the art.
225
247
  | --- | --- |
226
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) |
227
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) |
228
251
  | `depth-apply` | `--parts`, `--manifest`, `--config`, `--rig-config`, `--out` (issue #897; original character config is read-only) |
229
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) |
230
253
  | `sheet` | `--source`, `--layers` (repeatable), `--out`; optional `--cell`, `--cols` |
@@ -442,6 +465,12 @@ every number) are AUTHORING §3's tables, and the loader refuses any other by na
442
465
 
443
466
  ## Files this package writes
444
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
+
445
474
  ### Source cover report
446
475
 
447
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.1",
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.
@@ -3,7 +3,7 @@
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
8
  import { configFileReferences, loadConfigAndAnimations, parseConfig } from './config.ts';
9
9
  import { depthReading, readSourceDepth } from './depthsheets.ts';
@@ -146,7 +146,72 @@ function extendIntegratedHeight(data: Float64Array, art: Raster): Float64Array {
146
146
  }
147
147
  return filled;
148
148
  }
149
- 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 {
150
215
  const recipe = parseDepthRecipe(readJson(input.config)), expected = preparedParts(input.parts, recipe);
151
216
  const supplied = readJson(input.manifest);
152
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');
@@ -154,7 +219,7 @@ export function applyDepth(input: { parts: string; manifest: string; config: str
154
219
  const file = join(dirname(input.manifest), p.input);
155
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');
156
221
  }
157
- 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']; })]);
158
223
  const rawParts = object(readJson(join(input.parts, 'parts.json')), 'parts.json'), file = readParts(join(input.parts, 'parts.json'));
159
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');
160
225
  loadConfigAndAnimations(input.rigConfig);
@@ -168,6 +233,7 @@ export function applyDepth(input: { parts: string; manifest: string; config: str
168
233
  ref.set(relative(resolve(input.out), resolve(dirname(input.rigConfig), ref.value)));
169
234
  }
170
235
  parseConfig(raw);
236
+ const warnings: string[] = [];
171
237
  const writes = new Map<string, Uint8Array>(), rows: Obj[] = [], recs = rawParts.parts as Obj[];
172
238
  // Retain auxiliary art (including alternate sets) and diagnostics byte-for-byte.
173
239
  // Symlink inputs would obscure ownership and can escape this assembled directory.
@@ -194,6 +260,8 @@ export function applyDepth(input: { parts: string; manifest: string; config: str
194
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`);
195
261
  const prepared = expected.manifest.parts.find(row => row.part === name) as PreparedPart;
196
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);
197
265
  const map = registeredMap(numeric, prepared, declaration.frame, name);
198
266
  let values: ArrayLike<number>, normal: ReturnType<typeof integrateNormals> | undefined;
199
267
  if (declaration.source === 'normals') {
@@ -232,5 +300,6 @@ export function applyDepth(input: { parts: string; manifest: string; config: str
232
300
  writeFileSync(join(input.out, 'parts.json'), text(rawParts));
233
301
  writeFileSync(join(input.out, 'config.json'), text(raw));
234
302
  writeFileSync(join(input.out, 'depth-report.json'), text(report));
303
+ for (const warning of warnings) log(warning);
235
304
  return report;
236
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
  }