rig-review 1.8.0 → 1.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/docs/DESIGN.md CHANGED
@@ -155,17 +155,40 @@ not create pipeline stages or sign-offs. Opening or switching never submits a
155
155
  verdict, applies an edit or starts a producer job. Interview and Direction name
156
156
  their missing consumer contracts; no tools are fabricated for them.
157
157
 
158
- Stage 1 on compiled sessions embeds the existing **atlas inspection, read only**.
159
- Its atlas is always the **inspected input package**, never a subsequently applied
160
- scratch revision. The parent keeps pending edits and applied builds untouched;
161
- applied-scratch atlas inspection is unavailable. Data reads revalidate the full
162
- inspection binding. The initial atlas cache resolves only after post-load Review and Parts binding
163
- checks. Indexed image reads validate the pinned model and requested
164
- page hash through the same opened file, without rehashing unrelated reference
165
- video bytes. Pre-rig parts, mesh sign-off and draft corrections are not
166
- available in this embedding. Use the existing `parts` command for pre-rig parts
167
- and its separate explicit sign-off. Missing model/atlas inputs name the missing
168
- capability. No sibling package is guessed.
158
+ Stage 1 in a single compiled inspection with a producer handoff shows the
159
+ handoff's **separated parts and draft meshes**, labelled **Draft rig · structure
160
+ evidence only**. It proves each part's original raster crop against the rig image
161
+ and binds its exact skin/slot/attachment, dimensions, UVs and triangle indices to
162
+ the compiled mesh. UV values compare as exact float32 values, including the
163
+ compiler's shortest round-trip decimal representation; no numeric tolerance is
164
+ used. A name alone is insufficient. This is structure inspection, never final
165
+ rigging approval or evidence of unmeasured compiler gates.
166
+
167
+ Choose **Chest regions**, **Mesh parameters** or **Edit Mesh** on the selected
168
+ part to open the existing Setup precision instrument. The part and exact
169
+ `rig-parts remesh --mesh` or `rig-parts remesh --delta` operation remain visible.
170
+ Apply/Rebuild and Reset are the existing producer-backed actions. Return with
171
+ **1 Parts + mesh** to inspect the revision actually drawn by the parent, including
172
+ a checked scratch revision. Each entry reloads against that explicit build ID;
173
+ a pending candidate or the server's unrelated latest build is never substituted.
174
+ Reset returns to the inspected revision. New scratch reads and made-mesh feedback
175
+ submissions recheck pinned producer inputs, revision files and compiled files.
176
+ A changed scratch input cannot inherit clean checked evidence.
177
+
178
+ The embedding is read-only: original verdicts and comments are never copied onto
179
+ scratch geometry or saved by navigating. Use the standalone `parts` command for
180
+ its separate explicit original-parts sign-off. Parts-only inputs remain
181
+ inspectable and name `STAGE_DRAFT_UNAVAILABLE` for direct correction. A missing
182
+ handoff keeps the inspected atlas available where supplied. Compare retains its
183
+ read-only, side-specific inspected atlas. Neither flow guesses a sibling draft.
184
+
185
+ Named draft boundaries are `STAGE_DRAFT_UNAVAILABLE`, `STAGE_DRAFT_MISMATCH`,
186
+ `STAGE_DRAFT_STALE`, `STAGE_DRAFT_CHANGED`, `STAGE_DRAFT_UNCHECKED` and
187
+ `STAGE_DRAFT_OPERATION`. Producer discovery and its named missing/old-producer
188
+ refusals are unchanged; Review never installs a producer. Correction-record
189
+ export remains unavailable pending review#369 and create#91. Existing reviewer
190
+ requests remain verbatim in their existing feedback/comment contracts; there
191
+ is no fake Apply for art repair.
169
192
 
170
193
  Only Stage 3 shows the legacy Setup, Animate and Compare switch; its existing
171
194
  instruments, DOM and mode IDs are retained. In Stage 1 a compare session keeps
@@ -173,8 +196,9 @@ the A/B source picker usable and shows the selected side's cached atlas frame.
173
196
  **Open setup mesh instruments** returns from the atlas to Setup; it does not
174
197
  rebuild. Existing bookmarks, Apply/Reset provenance, selected slot, compare side,
175
198
  time, pending edits and applied build stay owned by those original tools. Stage
176
- changes retain both the original workspace and each side's atlas controller in
177
- the document. Language changes update retained frames without reloading them.
199
+ changes retain the original workspace and each compare side's atlas controller.
200
+ Single draft frames are rebound on revision changes. Language changes update retained
201
+ frames without applying or submitting.
178
202
  The parts-only entry retains its part selection, geometry and pending verdict
179
203
  while visiting unavailable stages; it needs no compiled model.
180
204
 
@@ -190,7 +214,7 @@ mesh painting. The optional protected `--painting` input supplies the real refer
190
214
  A/B and adjustable-opacity Overlay share the original painting
191
215
  transform from declared rig/source canvas geometry, with exact fractional placement. This is a visual
192
216
  comparison using browser interpolation, not native pixel parity with the producer's resampled raster.
193
- Difference waits for the producer-declared rig-space painting artifact (#390).
217
+ Difference uses the producer-declared rig-space painting artifact; see [Declared-grid Difference](PARTS_VIEW.md#declared-grid-difference).
194
218
  `tests/parts-comparison.test.ts` guards the geometry/settings; `tests/parts-overlay-browser.ts` verifies
195
219
  displayed overlay pixels and comment restoration in both languages.
196
220
 
package/docs/PANELS.md CHANGED
@@ -455,17 +455,40 @@ not create pipeline stages or sign-offs. Opening or switching never submits a
455
455
  verdict, applies an edit or starts a producer job. Interview and Direction name
456
456
  their missing consumer contracts; no tools are fabricated for them.
457
457
 
458
- Stage 1 on compiled sessions embeds the existing **atlas inspection, read only**.
459
- Its atlas is always the **inspected input package**, never a subsequently applied
460
- scratch revision. The parent keeps pending edits and applied builds untouched;
461
- applied-scratch atlas inspection is unavailable. Data reads revalidate the full
462
- inspection binding. The initial atlas cache resolves only after post-load Review and Parts binding
463
- checks. Indexed image reads validate the pinned model and requested
464
- page hash through the same opened file, without rehashing unrelated reference
465
- video bytes. Pre-rig parts, mesh sign-off and draft corrections are not
466
- available in this embedding. Use the existing `parts` command for pre-rig parts
467
- and its separate explicit sign-off. Missing model/atlas inputs name the missing
468
- capability. No sibling package is guessed.
458
+ Stage 1 in a single compiled inspection with a producer handoff shows the
459
+ handoff's **separated parts and draft meshes**, labelled **Draft rig · structure
460
+ evidence only**. It proves each part's original raster crop against the rig image
461
+ and binds its exact skin/slot/attachment, dimensions, UVs and triangle indices to
462
+ the compiled mesh. UV values compare as exact float32 values, including the
463
+ compiler's shortest round-trip decimal representation; no numeric tolerance is
464
+ used. A name alone is insufficient. This is structure inspection, never final
465
+ rigging approval or evidence of unmeasured compiler gates.
466
+
467
+ Choose **Chest regions**, **Mesh parameters** or **Edit Mesh** on the selected
468
+ part to open the existing Setup precision instrument. The part and exact
469
+ `rig-parts remesh --mesh` or `rig-parts remesh --delta` operation remain visible.
470
+ Apply/Rebuild and Reset are the existing producer-backed actions. Return with
471
+ **1 Parts + mesh** to inspect the revision actually drawn by the parent, including
472
+ a checked scratch revision. Each entry reloads against that explicit build ID;
473
+ a pending candidate or the server's unrelated latest build is never substituted.
474
+ Reset returns to the inspected revision. New scratch reads and made-mesh feedback
475
+ submissions recheck pinned producer inputs, revision files and compiled files.
476
+ A changed scratch input cannot inherit clean checked evidence.
477
+
478
+ The embedding is read-only: original verdicts and comments are never copied onto
479
+ scratch geometry or saved by navigating. Use the standalone `parts` command for
480
+ its separate explicit original-parts sign-off. Parts-only inputs remain
481
+ inspectable and name `STAGE_DRAFT_UNAVAILABLE` for direct correction. A missing
482
+ handoff keeps the inspected atlas available where supplied. Compare retains its
483
+ read-only, side-specific inspected atlas. Neither flow guesses a sibling draft.
484
+
485
+ Named draft boundaries are `STAGE_DRAFT_UNAVAILABLE`, `STAGE_DRAFT_MISMATCH`,
486
+ `STAGE_DRAFT_STALE`, `STAGE_DRAFT_CHANGED`, `STAGE_DRAFT_UNCHECKED` and
487
+ `STAGE_DRAFT_OPERATION`. Producer discovery and its named missing/old-producer
488
+ refusals are unchanged; Review never installs a producer. Correction-record
489
+ export remains unavailable pending review#369 and create#91. Existing reviewer
490
+ requests remain verbatim in their existing feedback/comment contracts; there
491
+ is no fake Apply for art repair.
469
492
 
470
493
  Only Stage 3 shows the legacy Setup, Animate and Compare switch; its existing
471
494
  instruments, DOM and mode IDs are retained. In Stage 1 a compare session keeps
@@ -473,7 +496,8 @@ the A/B source picker usable and shows the selected side's cached atlas frame.
473
496
  **Open setup mesh instruments** returns from the atlas to Setup; it does not
474
497
  rebuild. Existing bookmarks, Apply/Reset provenance, selected slot, compare side,
475
498
  time, pending edits and applied build stay owned by those original tools. Stage
476
- changes retain both the original workspace and each side's atlas controller in
477
- the document. Language changes update retained frames without reloading them.
499
+ changes retain the original workspace and each compare side's atlas controller.
500
+ Single draft frames are rebound on revision changes. Language changes update retained
501
+ frames without applying or submitting.
478
502
  The parts-only entry retains its part selection, geometry and pending verdict
479
503
  while visiting unavailable stages; it needs no compiled model.
@@ -32,41 +32,70 @@ is written), `--painting <png>` (the original painting), `--format json|issue` (
32
32
  region's own view keeps 4 page pixels around its box (dashed) so bleed is visible. Clicking a region opens it.
33
33
  - **Producer flags**, read from the files rig-parts writes and shown on the part they name. None is re-measured here. Each reads as one labelled line (an opening's parts, animation, frame and cells; a seam pair's pixel counts; a gate's name, status and readings), with the producer's object verbatim under a collapsed **Producer line**.
34
34
 
35
+ The [23-part EN/KO comparison](https://github.com/rig-c/review/tree/main/tests/fixtures/parts-approve-all-evidence) records the same 1600×1100 initial view against installed 1.8.0: row height 49.375 → 26.1875 px, with all 23 after rows on one line (`tests/parts-approve-all-browser.ts`).
36
+
35
37
  ### Producer row groups
36
38
 
37
- The sidebar reports separate source counts, for example **mesh 1 · check 4**, rather than a combined flag total.
38
- Only sources actually read get a count; an absent report is never shown as zero. A part with no flags from any
39
- read source has no count badge. Custom input filenames follow the same rule.
40
- The selected part's rows sit under **mesh_report.json** and **check.json**, each with collapsed producer-root groups
41
- and their row counts. Open a group to inspect its rows. A check headline includes its root, exact JSON path and
42
- the row's own string fields (including pair names, part names, status and reason when present), followed by the
43
- existing labelled readings. The enclosing block's status is labelled **Block**; a row's own `unavailable` does not
44
- become `WARN` merely because its block warns. Producer field values and the raw object are never translated.
45
-
46
- This is grouping by input source, **not classification of defects**. The existing extraction rules below are
47
- unchanged: unavailable support rows, informational pair readings and unknown rows that the reader already
48
- attributed remain present, counted under their source. One producer row can name multiple parts and appear on each;
49
- counts are per-part attributions, not unique problems across a rig. No scope, finding/evidence kind or acceptance
50
- verdict is inferred. Source hashes, saved flag ids and sign-off binding remain unchanged.
51
-
52
- The public regression input [`parts-check-380.json`](https://github.com/rig-c/review/blob/main/tests/fixtures/parts-check-380.json)
53
- is synthetic data, not a producer run or a private package. Its fields follow the producer's
54
- [`SupportReport` / `SupportPair`](https://github.com/rig-c/parts/blob/main/src/coincide.ts),
55
- [`MotionSeamLine` / `MotionSeamPair` and `LimbLine` / `LimbRow`](https://github.com/rig-c/parts/blob/main/src/check.ts).
56
- Alongside the public planted parts package, it retains 1 mesh attribution and 11 check attributions: on the back
57
- defect part **mesh 1 · check 4**, on the control **mesh 0 · check 2**, and on the front **mesh 0 · check 5**.
58
- The fixture deliberately keeps unavailable support, pair and part rows together. DOM checks exercise collapsed
59
- root counts, distinct same-part pair headlines, separate source badges and unchanged input hashes in both languages.
60
-
61
- | Flag | Read from | When |
39
+ The sidebar counts **only mesh-report flags and explicit part findings**. A check row counts only
40
+ when `row_scope: "part"`, `row_kind: "finding"` and a valid `row_subjects` array names that part.
41
+ A block status, a JSON path, a reason or a legacy part/slot/bone field never determines classification.
42
+ Counts stay separate by source, for example **mesh 1 · check 1**; an absent report is not shown as zero.
43
+ A part with no counted flags has no count badge, even when it has other readings.
44
+
45
+ Rows appear beneath **mesh_report.json** / **check.json**, with collapsed categories and producer-root groups:
46
+ - **Part findings**: the explicitly attributed findings counted in the badge.
47
+ - **Pair readings**: pair findings on both explicit subjects, never counted.
48
+ - **Check evidence**: every evidence row and every rig row (including rig findings), never counted.
49
+ Subject-bound evidence appears on its subjects; rig rows have no implied part and are visible on every selection.
50
+ - **Unclassified check rows**: incomplete or invalid metadata, never counted. In a mixed document an object row
51
+ without a complete tuple remains visible here globally, without guessed subject attribution. The tuple requires
52
+ scope part/pair/rig, kind finding/evidence, and respectively 1/2/0 distinct nonempty string subjects.
53
+ If any subject is not held in this view, the entire tuple is unclassified globally, including a pair with one held subject. No partial or substitute attribution is made.
54
+
55
+ The reader walks all roots regardless of block status, nested observation arrays, alternate sets and
56
+ `requirements.lines` dictionaries. Singleton summaries are not rows, except that a top-level FAIL/WARN gate
57
+ without a tuple is preserved globally as unclassified, even in a labelled document. Its status does not make
58
+ it a classified finding. Each headline preserves root, exact path,
59
+ producer string fields and measurements. **Block** labels the enclosing block status; it never overrides the
60
+ row's kind. **Producer line** holds the full original row object. Producer values are never translated.
61
+
62
+ A document with no row metadata keeps #380's source-root extraction and attribution, explicitly **unclassified**.
63
+ It can retain unavailable support and informational pairs; none becomes a counted finding. The public legacy
64
+ [`parts-check-380.json`](https://github.com/rig-c/review/blob/main/tests/fixtures/parts-check-380.json) remains a
65
+ synthetic compatibility fixture. Its 11 historical check attributions remain in the verdict wire collection,
66
+ while its sidebar check finding count is absent (only the back defect's mesh flag counts).
67
+
68
+ The fixture contract is pinned to published **@rig-c/parts@2.17.0**, source
69
+ [`971b3a7`](https://github.com/rig-c/parts/tree/971b3a7fab1109adf5be11750886687a7addb306),
70
+ whose [consumer row table](https://github.com/rig-c/parts/blob/971b3a7fab1109adf5be11750886687a7addb306/docs/AUTHORING.md#consumer-check-rows-issue-1089)
71
+ and `src/checkrow.ts` define the fields. This is an evidence pin, not a runtime dependency or automatic install.
72
+ `tests/fixtures/parts-check-385-real.json` is the byte-exact public synthetic-rig check output from the installed
73
+ producer; check exit **1** is its deliberately planted stretch finding, not a green rig. The measurement packet's
74
+ exit 0 means capture completed. The separate `parts-check-385.json` is a clearly synthetic six-combination matrix,
75
+ including status/subject decoys. `parts-check-385.provenance.json` records hashes, source and the reproduction recipe.
76
+ `tests/parts-classification.test.ts` guards the actual DOM callers, API, classification and unchanged wire binding;
77
+ `tests/parts-classification-browser.ts` supplies real bilingual screenshots and collapsed/expanded/legacy checks.
78
+ Representative public screenshots: [English collapsed](https://github.com/rig-c/review/blob/main/tests/fixtures/parts-check-385-evidence/collapsed-en.png),
79
+ [English expanded](https://github.com/rig-c/review/blob/main/tests/fixtures/parts-check-385-evidence/expanded-en.png),
80
+ [Korean collapsed](https://github.com/rig-c/review/blob/main/tests/fixtures/parts-check-385-evidence/collapsed-ko.png),
81
+ [Korean expanded](https://github.com/rig-c/review/blob/main/tests/fixtures/parts-check-385-evidence/expanded-ko.png).
82
+
83
+ Classification is a separate read-only `readings` collection in the view response. The historical `flags`
84
+ collection and `buildVerdict` extraction remain unchanged: verdict/2 `parts.<name>.flags`, source file hashes,
85
+ comment serialization and create consumption keep their existing semantics. Display counts are not verdict IDs
86
+ or an approval decision. Changing the check document still invalidates an offered saved sign-off.
87
+
88
+ | Stored flag ID | Read from | Existing verdict/2 extraction (unchanged) |
62
89
  | --- | --- | --- |
63
- | `faint:<i>` | `mesh_report.json` beside `parts.json` (`rig` writes it there): a row's `contour.bridges.faint[i]` | a faint island the mesh left out (rig-parts #326) |
64
- | `check:<path>` | `check/check.json` beside `rig/` | a gate whose `status` is `FAIL` or `WARN` (not `PASS`, `CLEAR`, `SKIP` or `REPORTED`), or a `seam_pairs` / `figure_openings` entry, that names the part by a string field; bone fields (`bone`, `root`, `tip`, `link`) never attribute |
90
+ | `faint:<i>` | `mesh_report.json` beside `parts.json` | a faint island the mesh left out |
91
+ | `check:<path>` | `check/check.json` beside `rig/` | historical FAIL/WARN gates or seam/opening lists naming a part by a non-bone string field; this is not the new sidebar classification |
65
92
 
66
93
  The occlusion-coverage report (rig-c/parts#998) is not read yet; the footprint toggle stands without it.
67
94
 
68
95
  ## The sign-off
69
96
 
97
+ **Approve all** marks every pending part and available mesh clean, then saves an explicit approved sign-off. It preserves notes and existing clean outcomes; any flagged part or mesh refuses with `PARTS_APPROVE_ALL_FLAGGED` before changes are made. Individual approval remains available. `tests/parts-approve-all.test.ts` exercises the page action and unchanged verdict guard; `tests/parts-approve-all-browser.ts` checks the real save and refusal flows.
98
+
70
99
  Each item is **pending**, **clean** or **flagged** with a note (a note is optional on clean). **Save sign-off**
71
100
  writes `parts-review.json` beside `parts.json` (atlas mode: beside the model), or to `--verdict`:
72
101
 
@@ -92,7 +121,7 @@ writes `parts-review.json` beside `parts.json` (atlas mode: beside the model), o
92
121
  verdict file's directory**, POSIX separators. A part added, removed or repainted after sign-off changes the hash.
93
122
  - `source.sha256` is the SHA-256 of the UTF-8 lines `<path>\t<sha256>\n`, one per `source.files` entry, sorted by path
94
123
  bytewise. Consumers recompute it from the files on disk.
95
- - `source.flags` lists the producer files the flags were read from; `parts.<name>.flags` the flag ids shown on that part.
124
+ - `source.flags` lists the producer files the flags were read from; `parts.<name>.flags` the historical producer-attribution IDs defined above, not the classified sidebar count.
96
125
  - `status`: `approved` only when every part is clean; `changes-requested` only with at least one part flagged;
97
126
  otherwise `pending`.
98
127
 
@@ -283,8 +312,8 @@ A downstream create consumer must support verdict/2 before a review release can
283
312
 
284
313
  **Assembled** toggles the existing rig/reference pair from the selected part to the declared
285
314
  `rig_size` canvas. Parts draw back to front in package order at their exact fractional rig-pixel
286
- placements. **Visible** beside each part controls assembly visibility only; the verdict remains
287
- per part. A tap selects the frontmost visible part with nonzero native source alpha, including
315
+ placements. The checkbox beside each part controls assembly visibility only; the verdict remains
316
+ per part. List rows occupy one line, with full part names available to assistive technology and on hover, separate source counts and the outcome badge. The former **Visible / 표시** caption is removed; the checkbox retains its per-part accessible name (`tests/parts-approve-all.test.ts`, with full-list geometry in `tests/parts-approve-all-browser.ts`). A tap selects the frontmost visible part with nonzero native source alpha, including
288
317
  through transparent holes; drags remain camera gestures. The selected part's alpha edge is a
289
318
  separate outline, outside the comparison raster. Background, alpha-only, Fit, 1:1 and the shared
290
319
  camera controls remain available. `tests/parts-assembly.test.ts` guards fractional placement,
@@ -301,3 +330,82 @@ checks real EN/KO assembly/reference pixels against an independent browser draw
301
330
  base-vs-base control, tap/hole/hide selection, pan, camera preservation, background, alpha,
302
331
  verdict save and missing-input refusals. Existing `tests/parts-comparison.test.ts` and
303
332
  `tests/parts-comments.test.ts` retain the painting-size and protected-input guards.
333
+
334
+ ## Draft mesh correction connection
335
+
336
+ In a single compiled inspection with a live producer handoff, Stage 1 reads the
337
+ same original `parts.json`/PNGs through the existing reader and uses the exact
338
+ inspected or checked applied scratch `rig.json` for its mesh overlay. The
339
+ skin/slot/attachment, float32 UVs, dimensions and triangle arrays must match the
340
+ compiled model; raster equality is still proved by `locateMeshRasters`. Neither
341
+ matching names nor a shared folder is enough. Mismatch refuses by name.
342
+
343
+ The selected part opens the actual Chest regions, Mesh parameters or Edit Mesh
344
+ instrument, naming `remesh --mesh` or `remesh --delta`. The existing installed
345
+ producer writes only scratch. Return to Stage 1 after Apply to inspect the
346
+ recorded revision; Reset restores the original revision. New applied chest and
347
+ delta records carry the producer check, counts, file diff and a scratch input
348
+ pin. Changed scratch input, pending builds and missing/failed checks cannot be
349
+ submitted as new checked made evidence. Historical records with no check remain
350
+ readable as historical evidence; no PASS is synthesized for them.
351
+
352
+ Stage 1 does not rewrite `rig-review-parts-verdict/2`: `source.files`,
353
+ `source.flags`, their digest, per-part outcomes and comment/crop/comparison
354
+ bindings remain the standalone original-parts contract. Scratch inspection
355
+ returns no inherited verdict. Its own parts digest and build evidence accompany
356
+ the original package `sourceHash`; original Review sessions/drafts remain scoped
357
+ to their original `sourceHash`/`reviewedSource`. A standalone parts-only package
358
+ names the absent draft instead of offering an Apply that cannot run.
359
+
360
+ Correction-record export is unfinished, blocked on review#369/create#91. Existing
361
+ comments and feedback preserve reviewer wording, but are not a substitute for
362
+ that shared export or for create-owned structure decisions.
363
+
364
+ ### Declared-grid Difference
365
+
366
+ **Difference** in an individual part view reads the optional producer declaration
367
+ `painting_in_rig: {path, sha256, resample:"lanczos3-rgb-opaque"}` in `parts.json`.
368
+ The literal portable path resolves inside the package. Its PNG must be RGBA8,
369
+ alpha 255 and exactly `rig_size`; its bytes must match the declared SHA-256.
370
+ The artifact joins `source.files` and protected inputs. Original `--painting`
371
+ A/B and Overlay remain independent. Legacy manifests without the declaration
372
+ still open normally; Difference requests refuse `PARTS_DIFFERENCE_UNAVAILABLE`.
373
+
374
+ The consumer is pinned to the published contract in
375
+ [@rig-c/parts 2.19.0](https://github.com/rig-c/parts/tree/193380b36b61a44daa3a4fcc5824a58efd6750a4).
376
+ This is assemble's operand: source RGB forced opaque, then producer Lanczos3.
377
+ Check instead flattens source alpha over its backdrop before resizing. The
378
+ [producer's per-example report](https://github.com/rig-c/parts/pull/1101)
379
+ reports equality for its five opaque example sources. That report is provenance,
380
+ not a consumer verdict or proof of `SETUP_MATCHES_PAINTING`.
381
+
382
+ For each original part cell with alpha > 0, the server compares stored RGB to
383
+ `painting_in_rig[x+cellX,y+cellY]`. No premultiplication, resampling or browser
384
+ pixel readback enters the metric. Difference is
385
+ `max(abs(dR),abs(dG),abs(dB))`, counted only when **strictly greater** than the
386
+ integer Threshold (0–255). Above-threshold cells are red with intensity equal
387
+ to the difference; others are black. Alpha-zero cells show the sentinel.
388
+ Invalid threshold input is refused and visibly restored to the last valid value.
389
+ There is no automatic approval or pass/fail verdict.
390
+
391
+ With Footprints enabled, a cell held at alpha > 0 by any overlapping later
392
+ part at the same integer rig coordinate is grey (128,128,128) and excluded
393
+ from the count. Off compares the selected part without decoding or sampling front
394
+ rasters. The selected part and any front parts sampled with Footprints on need
395
+ integer x/y, PNG dimensions equal to w/h, and native RGBA8 operands.
396
+ A nontransparent selected cell outside the rig grid or fractional placement
397
+ refuses `PARTS_DIFFERENCE_ALIGNMENT`; review never rounds placement or invents
398
+ edge coverage. Assembly remains a separate visual view.
399
+
400
+ Difference comments retain `view.comparison:{mode:"difference",opacity,threshold}`
401
+ and the existing footprints, background and cameras. Older part/overlay states
402
+ keep their two-field shape. The common viewport crop captures the displayed
403
+ comparison; the native crop keeps original RGBA. Save, reopen, restore, JSON
404
+ and issue Markdown retain this state, with source checks before use.
405
+
406
+ Named input refusals: `PARTS_DIFFERENCE_PROVENANCE`, `PARTS_DIFFERENCE_PATH`,
407
+ `PARTS_DIFFERENCE_HASH`, `PARTS_DIFFERENCE_PNG`, `PARTS_DIFFERENCE_SIZE`,
408
+ `PARTS_DIFFERENCE_ALPHA`. A changed loaded input uses
409
+ `PARTS_VIEW_SOURCE_CHANGED`. No producer command executes for Difference.
410
+ `tests/parts-difference.test.ts` supplies literal independent numeric controls;
411
+ `tests/parts-difference-browser.ts` exercises bilingual display and saved evidence.
@@ -826,3 +826,69 @@ existing verdict/1 records read with no comments. This identity comes from the e
826
826
  parts verdict source digest and actual original PNG SHA-256, without a fabricated review
827
827
  manifest id, revision or compiled model. The rig's `rig-review-comment/1` schema stays closed.
828
828
  See [the parts contract and validation instruments](PARTS_VIEW.md#pointed-parts-comments).
829
+
830
+ ## Stage-1 draft mesh inspection
831
+
832
+ `GET /api/stage-parts` in single inspections uses the live handoff's original
833
+ separated parts when a compatible draft is supplied. Its fixed indexed image
834
+ routes use the same binding. The closed `X-Review-Stage-Build` read header is
835
+ `inspected` or a 64-hex applied build ID; it is not a path or an execution request.
836
+ The managed front forwards it only for these single-inspection read routes.
837
+ Without a separated draft, the existing inspected atlas remains read-only and
838
+ names direct-correction absence. Compare stays read-only and side-closed.
839
+ Region-only handoff drafts retain the separated-parts view and image inspection;
840
+ `STAGE_DRAFT_NO_MESH` names unavailable direct correction on a part without a
841
+ mesh attachment, in English and Korean. It does not turn inspection into an error.
842
+ Opening another chest-capable part rebinds both region rows and landmarks to
843
+ that part's config and kept-region seed. Reopening the same part keeps its edits.
844
+
845
+ The draft response adds `draft:{label,buildId,inspectionSourceHash,mappings,evidence}`
846
+ to the existing parts-view response; `mappings` names the exact part,
847
+ skin/slot/attachment and mesh counts. It includes no inherited verdict or
848
+ submission authority. Raster/crop, float32 UV, triangle and source-hash checks
849
+ bind the displayed geometry. `evidence` is the actual applied producer job, not
850
+ a guessed correction-export object. A changed original refuses; scratch is never
851
+ quietly repinned. Every scratch read revalidates the recorded revision and build.
852
+
853
+ New `rig-review-applied/1` (Chest regions) and `/3` (Edit Mesh) records add optional
854
+ `check` and `stageInputHash`. Chest records also support `files` and `mesh`, as
855
+ existing patch/delta records do; `/2` can carry `stageInputHash` too. The input
856
+ pin hashes the whole revision plus the present scratch mesh/config/delta/world
857
+ inputs; compiled file hashes stay in their existing build record. Producer
858
+ remesh checks are reused only when their revision hash rows validate; older
859
+ producers run the existing check operation on scratch. A new null, failed or
860
+ nonzero-exit mesh check refuses `EDIT_SUBMIT_UNCHECKED`. Historical `/1` and `/3`
861
+ without those optional fields stay readable and never gain synthesized checks.
862
+ A newly requested Apply does not reuse a historical result lacking check data.
863
+ Each settled Apply writes a server-owned, SHA-256-verified evidence seal under
864
+ `<state>/applied-evidence/<package hash>/<build id>.json`, bounded to 1 MiB per
865
+ build. It holds the exact applied record, package binding, operation, input and
866
+ output digests, model hash and check summary. Seals remain for the state directory's
867
+ lifetime, independently of the eight-build Undo cache; pending strip candidates
868
+ are not applied and receive no seal. Add feedback remains local until Submit.
869
+ New made-mesh submissions with an input pin must exactly equal their sealed
870
+ record, including after Undo, eviction or a server restart. Missing, damaged or
871
+ different evidence refuses `STAGE_DRAFT_STALE`; client fields or `result.json`
872
+ alone are never evidence. Historical feedback describes the recorded Apply,
873
+ not the currently displayed revision. Stage reads separately re-hash the live
874
+ revision and compiled files, require the settled current Apply and successful
875
+ check, and retain `STAGE_DRAFT_CHANGED`/pending refusals. A seal never authorizes
876
+ drawing an evicted, changed or pending build as current.
877
+
878
+ Original `sourceHash`, `reviewedSource`, session/draft scope and parts verdict/2
879
+ remain unchanged. The scratch parts digest changes with its geometry; original
880
+ approvals never become scratch mesh approvals. Reset returns inspection to the
881
+ original. Draft geometry is structure evidence only. Correction-record export
882
+ remains blocked on review#369/create#91; no universal export, artwork Apply,
883
+ source-key write or automatic message is introduced.
884
+
885
+
886
+ Draft correspondence supports producer-authored named `weights` (compiled
887
+ weighted bindings) and authored unweighted `vertices` (compiled `xy`), comparing
888
+ the bone names and each represented float32 component exactly. Raw bone-indexed
889
+ vertex runs refuse `STAGE_DRAFT_GEOMETRY_UNSUPPORTED`; Review does not infer their
890
+ index mapping. This does not restrict standalone parts-mode UV inspection.
891
+ Equal UV/index arrays alone are insufficient when compiled vertex data differs.
892
+ Single Stage-1 controllers retain selection/camera on same-build navigation;
893
+ cross-revision restoration requires the same original package/image/placement
894
+ and exact draft skin/slot/attachment address, with named refusal if absent.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rig-review",
3
- "version": "1.8.0",
3
+ "version": "1.10.0",
4
4
  "type": "module",
5
5
  "description": "Local human rig inspection and structured feedback export",
6
6
  "license": "MIT",
@@ -55,6 +55,7 @@ export interface CheckSummary {
55
55
  }
56
56
  export interface Tool { package: string; version: string }
57
57
  export interface AppliedPatch {
58
+ stageInputHash?: string;
58
59
  schema: typeof APPLIED_PATCH_SCHEMA;
59
60
  buildId: string;
60
61
  patch: ConfigPatch;
@@ -104,6 +105,8 @@ function parseAssembled(v: unknown, field: string): void {
104
105
  }
105
106
  /** #135: Edit Mesh's delta as applied by `rig-parts remesh --delta`. */
106
107
  export interface AppliedDelta {
108
+ stageInputHash?: string;
109
+ check?: CheckSummary | null;
107
110
  schema: typeof APPLIED_DELTA_SCHEMA;
108
111
  buildId: string;
109
112
  part: string;
@@ -191,7 +194,7 @@ const meshCounts = (v: unknown, field: string) => {
191
194
  const isObject = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
192
195
  const hex = (v: unknown) => typeof v === 'string' && /^[a-f0-9]{64}$/.test(v);
193
196
  const exact = (v: unknown, keys: string, field: string): Record<string, unknown> => {
194
- if (!isObject(v) || Object.keys(v).sort().join(',') !== keys) throw new Error(`${field}: expected exactly {${keys.split(',').join(', ')}}`);
197
+ if (!isObject(v) || Object.keys(v).sort().join(',') !== keys.split(',').sort().join(',')) throw new Error(`${field}: expected exactly {${keys.split(',').join(', ')}}`);
195
198
  return v;
196
199
  };
197
200
  const tool = (v: unknown, field: string) => { const t = exact(v, 'package,version', field); if (typeof t.package !== 'string' || typeof t.version !== 'string') throw new Error(`${field}: package and version are strings`); };
@@ -223,9 +226,15 @@ export function parseAppliedContext(value: unknown): void {
223
226
  if (value === null) return;
224
227
  if (!isObject(value)) throw new Error('feedback.context.applied: expected an applied record or null');
225
228
  const field = 'feedback.context.applied';
229
+ if(Object.hasOwn(value,'stageInputHash')&&!hex(value.stageInputHash))throw new Error(`${field}.stageInputHash: SHA-256 required`);
226
230
  if (value.schema === APPLIED_REGIONS_SCHEMA) {
227
231
  // #105: a landmarks Apply adds `bust` (the contour.bust entry as sent); its `regions` are review's derived circles.
228
- const v = exact(value, Object.hasOwn(value, 'bust') ? 'buildId,bust,compiler,configHash,entrySha256,line,modelHash,part,producer,regions,schema' : 'buildId,compiler,configHash,entrySha256,line,modelHash,part,producer,regions,schema', field);
232
+ const keys = Object.hasOwn(value, 'bust') ? 'buildId,bust,compiler,configHash,entrySha256,line,modelHash,part,producer,regions,schema' : 'buildId,compiler,configHash,entrySha256,line,modelHash,part,producer,regions,schema';
233
+ const v = exact(value, keys + ['check','stageInputHash','files','mesh'].filter(k=>Object.hasOwn(value,k)).map(k=>','+k).join(''), field);
234
+ if (Object.hasOwn(v, 'check')) parseCheck(v.check, `${field}.check`);
235
+ if (Object.hasOwn(v, 'stageInputHash')&&!hex(v.stageInputHash))throw new Error(`${field}.stageInputHash: SHA-256 required`);
236
+ if(Object.hasOwn(v,'files'))parseFilesDiff(v.files,`${field}.files`);
237
+ if(Object.hasOwn(v,'mesh')){const m=exact(v.mesh,'after,before,part',`${field}.mesh`);if(m.part!==v.part)throw new Error(`${field}.mesh.part: expected the designated part`);meshCounts(m.before,`${field}.mesh.before`);meshCounts(m.after,`${field}.mesh.after`);}
229
238
  if (Object.hasOwn(v, 'bust')) { try { parseBustSpec(v.bust, `${field}.bust`); } catch (e) { throw new Error(e instanceof Error ? e.message : String(e)); } }
230
239
  if (![v.buildId, v.configHash, v.entrySha256, v.modelHash].every(hex)) throw new Error(`${field}: buildId, configHash, entrySha256 and modelHash are SHA-256 hex`);
231
240
  if (typeof v.part !== 'string' || !Array.isArray(v.regions)) throw new Error(`${field}: part and regions`);
@@ -233,7 +242,7 @@ export function parseAppliedContext(value: unknown): void {
233
242
  return;
234
243
  }
235
244
  if (value.schema === APPLIED_PATCH_SCHEMA) {
236
- const v = exact(value, `${Object.hasOwn(value, 'assembled') ? 'assembled,' : ''}buildId,check,${Object.hasOwn(value, 'cloth') ? 'cloth,' : ''}compiler,configHash,diff,${Object.hasOwn(value, 'environment') ? 'environment,' : ''}${Object.hasOwn(value, 'files') ? 'files,' : ''}line,${Object.hasOwn(value, 'mesh') ? 'mesh,' : ''}modelHash,${Object.hasOwn(value, 'op') ? 'op,' : ''}patch,patchSha256,producer,schema`, field);
245
+ const v = exact(value, `${Object.hasOwn(value, 'stageInputHash')?'stageInputHash,':''}${Object.hasOwn(value, 'assembled') ? 'assembled,' : ''}buildId,check,${Object.hasOwn(value, 'cloth') ? 'cloth,' : ''}compiler,configHash,diff,${Object.hasOwn(value, 'environment') ? 'environment,' : ''}${Object.hasOwn(value, 'files') ? 'files,' : ''}line,${Object.hasOwn(value, 'mesh') ? 'mesh,' : ''}modelHash,${Object.hasOwn(value, 'op') ? 'op,' : ''}patch,patchSha256,producer,schema`, field);
237
246
  if (![v.buildId, v.configHash, v.patchSha256, v.modelHash].every(hex)) throw new Error(`${field}: buildId, configHash, patchSha256 and modelHash are SHA-256 hex`);
238
247
  let patch: ConfigPatch;
239
248
  try { patch = parseConfigPatch(v.patch); } catch (e) { throw new Error(`${field}.patch: ${e instanceof Error ? e.message : String(e)}`); }
@@ -263,13 +272,14 @@ export function parseAppliedContext(value: unknown): void {
263
272
  return;
264
273
  }
265
274
  if (value.schema === APPLIED_DELTA_SCHEMA) {
266
- const v = exact(value, `buildId,compiler,configHash,delta,deltaSha256,files,line,${Object.hasOwn(value, 'mesh') ? 'mesh,' : ''}modelHash,op,part,producer,schema`, field);
275
+ const v = exact(value, `${Object.hasOwn(value,'stageInputHash')?'stageInputHash,':''}buildId,${Object.hasOwn(value, 'check') ? 'check,' : ''}compiler,configHash,delta,deltaSha256,files,line,${Object.hasOwn(value, 'mesh') ? 'mesh,' : ''}modelHash,op,part,producer,schema`, field);
267
276
  if (![v.buildId, v.configHash, v.deltaSha256, v.modelHash].every(hex)) throw new Error(`${field}: buildId, configHash, deltaSha256 and modelHash are SHA-256 hex`);
268
277
  if (typeof v.part !== 'string' || !/^[A-Za-z0-9_-]{1,64}$/.test(v.part)) throw new Error(`${field}.part: the part remesh --delta ran on`);
269
278
  const d = v.delta;
270
279
  if (!isObject(d) || d.schema !== MESH_EDIT_SCHEMA || d.basis !== MESH_EDIT_BASIS || d.slot !== v.part || !isObject(d.source) || !hex(d.source.hash) || !Array.isArray(d.ops) || d.ops.length > MESH_EDIT_MAX_OPS) throw new Error(`${field}.delta: a ${MESH_EDIT_SCHEMA} document (basis "${MESH_EDIT_BASIS}", slot the part, source.hash, at most ${MESH_EDIT_MAX_OPS} ops)`);
271
280
  if (v.op !== 'remesh') throw new Error(`${field}.op: "remesh" for a mesh-edit delta`);
272
281
  tool(v.producer, `${field}.producer`); tool(v.compiler, `${field}.compiler`); lineOrNull(v.line, `${field}.line`);
282
+ if (Object.hasOwn(v, 'check')) parseCheck(v.check, `${field}.check`);
273
283
  parseFilesDiff(v.files, `${field}.files`);
274
284
  if (Object.hasOwn(v, 'mesh')) {
275
285
  const m = exact(v.mesh, 'after,before,part', `${field}.mesh`);
@@ -350,6 +360,9 @@ export function appliedSummary(value: unknown): string | null {
350
360
  * else the first bar check.json marks FAIL — verbatim. Null when the record is not a patch or its check did not FAIL.
351
361
  */
352
362
  export function appliedCheckRefusal(value: unknown): string | null {
363
+ if (isObject(value) && [APPLIED_REGIONS_SCHEMA, APPLIED_DELTA_SCHEMA].includes(String(value.schema)) && Object.hasOwn(value, 'check')) {
364
+ if (!isObject(value.check) || value.check.pass !== true || value.check.exitCode !== 0) return 'EDIT_SUBMIT_UNCHECKED: applied mesh has no successful producer check';
365
+ }
353
366
  if (!isObject(value) || (value.schema !== APPLIED_PATCH_SCHEMA && value.schema !== APPLIED_ANIMATION_SCHEMA) || !isObject(value.check) || value.check.pass !== false) return null;
354
367
  const check = value.check as unknown as CheckSummary;
355
368
  const bar = Object.entries(check.bars ?? {}).find(([, status]) => status === 'FAIL')?.[0];
package/src/front.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import {stageDraftRefusals} from './stage-parts.ts';
1
2
  /** Managed loopback front: one stable origin (127.0.0.1:4318 by default) routing `/instances/<key>/…` to the
2
3
  * worker named by that key's private open record. It is a router, not an authority: it never reads packages,
3
4
  * never serves or logs a capability, and forwards a mutation (rewriting Origin) only with the page capability. */
@@ -108,7 +109,9 @@ async function stagePartsRefusal(mode:'single'|'compare',method:string,path:stri
108
109
  for(;;){const {value,done}=await reader.read();if(done)break;bytes+=value.byteLength;if(bytes>limit){void reader.cancel().catch(()=>{});return null;}chunks.push(value);}
109
110
  const body=new Uint8Array(bytes);let offset=0;for(const chunk of chunks){body.set(chunk,offset);offset+=chunk.byteLength;}
110
111
  const data:unknown=JSON.parse(new TextDecoder().decode(body)),named='PARTS_ATLAS_UNAVAILABLE: the inspected package has no usable atlas or its source changed.';
111
- return data!==null&&typeof data==='object'&&!Array.isArray(data)&&Object.keys(data).length===1&&(data as {error?:unknown}).error===named?named:null;
112
+ if(data===null||typeof data!=='object'||Array.isArray(data)||Object.keys(data).length!==1)return null;
113
+ const error=(data as {error?:unknown}).error;
114
+ return typeof error==='string'&&[named,...Object.values(stageDraftRefusals)].includes(error)?error:null;
112
115
  }catch{return null;}finally{reader.releaseLock();}
113
116
  }
114
117
  export const maximumUpstreamStreams=32;
@@ -168,6 +171,7 @@ export function startFront(options:{control:string;port:number;nonce:string;fing
168
171
  }
169
172
  if(active>=maximumUpstreamStreams)return refuse('FRONT_BUSY: too many concurrent upstream streams',503);
170
173
  const headers=new Headers({[openNonceHeader]:record.nonce});for(const name of ['accept','range','if-range',...(route.mutation?['content-type']:[]),...(route.control?['authorization']:[])]){const value=req.headers.get(name);if(value!==null)headers.set(name,value);}
174
+ if(/^\/api\/stage-parts(?:\/(?:image|page)\/\d+)?$/.test(path)){const build=req.headers.get('X-Review-Stage-Build');if(build!==null){if(build!=='inspected'&&!/^[a-f0-9]{64}$/.test(build))return refuse('FRONT_QUERY_REFUSED',400);headers.set('X-Review-Stage-Build',build);}}
171
175
  if(route.mutation){headers.set('origin',record.origin);headers.set(capabilityHeader,record.capability);}
172
176
  active++;let released=false;const abort=new AbortController(),timer=setTimeout(()=>abort.abort(),route.timeoutMs);const release=()=>{if(released)return;released=true;active--;clearTimeout(timer);};
173
177
  req.signal.addEventListener('abort',()=>abort.abort(),{once:true});
@@ -4,7 +4,7 @@ import {readFile} from 'node:fs/promises';
4
4
  import {PNG} from 'pngjs';
5
5
  import {parsePartsComment,assertPartsCommentBinding,type PartsComment} from './parts-comment.ts';
6
6
  import {validatePngCrop,storePngCrop,readPngCrop} from './comment-crops.ts';
7
- import {verdictSource,type PartsViewPackage} from './parts-view.ts';
7
+ import {assertPartsUnchanged,partsDifference,verdictSource,type PartsViewPackage} from './parts-view.ts';
8
8
  export async function preparePartsComment(pkg:PartsViewPackage,raw:unknown,requireNative=false):Promise<PartsComment>{return resolvePartsComment(pkg,raw,requireNative,true);}
9
9
  export async function validateStoredPartsComment(pkg:PartsViewPackage,raw:unknown):Promise<PartsComment>{return resolvePartsComment(pkg,raw,true,false);}
10
10
  async function resolvePartsComment(pkg:PartsViewPackage,raw:unknown,requireNative:boolean,persist:boolean):Promise<PartsComment>{
@@ -13,7 +13,9 @@ async function resolvePartsComment(pkg:PartsViewPackage,raw:unknown,requireNativ
13
13
  const path=pkg.imagePaths[item.index],file=pkg.files.find(f=>f.abs===path);if(!path||!file)throw new Error('PARTS_COMMENT_UNAVAILABLE: bound original PNG required');
14
14
  assertPartsCommentBinding(c,item,file.sha256,verdictSource(pkg).sha256);
15
15
  if(c.view.comparison?.mode==='overlay'&&!pkg.painting)throw new Error('PARTS_COMPARISON_UNAVAILABLE: original painting required');
16
+ if(c.view.comparison?.mode==='difference')await partsDifference(pkg,item.index,c.view.comparison.threshold,c.view.footprints);
16
17
  const bytes=await readFile(path);if(createHash('sha256').update(bytes).digest('hex')!==file.sha256)throw new Error('PARTS_COMMENT_STALE_SOURCE: original PNG changed');
18
+ await assertPartsUnchanged(pkg);
17
19
  validatePngCrop(c.crop);
18
20
  const original=PNG.sync.read(bytes),r=c.imageRegion;
19
21
  if(original.width!==item.w||original.height!==item.h)throw new Error('PARTS_COMMENT_IMAGE_SIZE: original dimensions differ from placement');
@@ -1,9 +1,10 @@
1
1
  /** Visual comparison settings are evidence, never a producer verdict. Older comments omit them. */
2
- export interface PartsComparison {mode:'part'|'overlay';opacity:number}
2
+ export type PartsComparison = {mode:'part'|'overlay';opacity:number} | {mode:'difference';opacity:number;threshold:number};
3
3
  export const defaultPartsComparison = ():PartsComparison => ({mode:'part',opacity:.5});
4
4
  export function parsePartsComparison(raw:unknown):PartsComparison {
5
5
  const v=raw as PartsComparison;
6
- if(!v||typeof v!=='object'||Array.isArray(v)||Object.keys(v).length!==2||!['mode','opacity'].every(k=>Object.hasOwn(v,k))||!['part','overlay'].includes(v.mode)||typeof v.opacity!=='number'||!Number.isFinite(v.opacity)||v.opacity<0||v.opacity>1)throw new Error('PARTS_COMPARISON_INVALID: part/overlay mode and opacity 0..1 required');
6
+ const keys=v?.mode==='difference'?['mode','opacity','threshold']:['mode','opacity'];
7
+ if(!v||typeof v!=='object'||Array.isArray(v)||Object.keys(v).length!==keys.length||!keys.every(k=>Object.hasOwn(v,k))||!['part','overlay','difference'].includes(v.mode)||typeof v.opacity!=='number'||!Number.isFinite(v.opacity)||v.opacity<0||v.opacity>1||v.mode==='difference'&&(!Number.isInteger(v.threshold)||v.threshold<0||v.threshold>255))throw new Error('PARTS_COMPARISON_INVALID: part/overlay with opacity 0..1, or difference with integer threshold 0..255 required');
7
8
  return v;
8
9
  }
9
10
  export interface PaintingRectangle {x:number;y:number;width:number;height:number}
@@ -18,3 +19,25 @@ export function paintingRectangle(item:{x:number;y:number;w:number;h:number},rig
18
19
  const x=painting.width/rigSize[0]!,y=painting.height/rigSize[1]!;
19
20
  return {x:item.x*x,y:item.y*y,width:item.w*x,height:item.h*y};
20
21
  }
22
+
23
+ export interface DifferenceRaster {width:number;height:number;data:Uint8Array}
24
+ export interface DifferenceBox {x:number;y:number;w:number;h:number}
25
+ /** Exact native-cell pairing only. No placement rounding, filtering or alpha premultiplication. */
26
+ export function differencePixels(part:DifferenceRaster,box:DifferenceBox,painting:DifferenceRaster,fronts:readonly {box:DifferenceBox;raster:DifferenceRaster}[],threshold:number,excludeCovered:boolean) {
27
+ if(!Number.isInteger(threshold)||threshold<0||threshold>255)throw new Error('PARTS_COMPARISON_INVALID: integer threshold 0..255 required');
28
+ const valid=(b:DifferenceBox,r:DifferenceRaster)=>[b.x,b.y,b.w,b.h].every(Number.isSafeInteger)&&b.w===r.width&&b.h===r.height&&r.data.length===r.width*r.height*4;
29
+ if(!valid(box,part)||(excludeCovered&&fronts.some(f=>!valid(f.box,f.raster))))throw new Error('PARTS_DIFFERENCE_ALIGNMENT: integer native placement and exact PNG dimensions required');
30
+ const rgba=new Uint8Array(part.width*part.height*4);let count=0,covered=0,compared=0;
31
+ for(let y=0;y<part.height;y++)for(let x=0;x<part.width;x++){
32
+ const i=(y*part.width+x)*4;if(!part.data[i+3])continue;
33
+ const gx=box.x+x,gy=box.y+y;
34
+ if(gx<0||gy<0||gx>=painting.width||gy>=painting.height)throw new Error('PARTS_DIFFERENCE_ALIGNMENT: nontransparent part pixel lies outside declared rig grid');
35
+ if(excludeCovered&&fronts.some(f=>{const fx=gx-f.box.x,fy=gy-f.box.y;return fx>=0&&fy>=0&&fx<f.raster.width&&fy<f.raster.height&&f.raster.data[(fy*f.raster.width+fx)*4+3]!>0;})){
36
+ rgba.set([128,128,128,255],i);covered++;continue;
37
+ }
38
+ const j=(gy*painting.width+gx)*4,d=Math.max(...[0,1,2].map(c=>Math.abs(part.data[i+c]!-painting.data[j+c]!)));
39
+ compared++;if(d>threshold)count++;
40
+ rgba.set([d>threshold?d:0,0,0,255],i);
41
+ }
42
+ return {width:part.width,height:part.height,data:rgba,count,covered,compared};
43
+ }