rig-review 1.5.4 → 1.7.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
@@ -4,7 +4,7 @@
4
4
 
5
5
  The delivery unit is an existing output folder or an optional curated review package handed from an agent to a person. This reusable app owns inspection, reference comparison, annotations and feedback export. Upstream compiler, splitter and runtime remain their respective tools. The existing producing agent needs no change to open its output here.
6
6
 
7
- The person uses one inspection workspace with **Setup** and **Animate** sections and a review dialog for feedback (the compare page keeps **View**, **Rig**, **Playback** and **Feedback** sections). Setup covers setup geometry, source art, pivot/joint placement, meshes, weights and draw order; Animate covers angle coverage, frame intervals, reference video/poses, contact/deformation, audio inspection and the inspection environment (wind, gravity and impulses through the published player's `environment`/`moved`; its state is feedback context, never a model or motion edit) and the physics tuning panel (#103: constraint values edited as config patch ops and applied through the producer, never written into the model by review), and the readings block (#108: the compiler's own `rigc render` readings of the drawn animation, run on the inspected build and on the latest scratch build, shown as timeline ticks and worst-frame lines), the Environment block's *Use for readings* (#112: the controls exported as a `rigc-environment/1` schedule that readings, Apply's check and *Check under this world* — the installed producer's `rig-parts check --environment` — read, so the bars and readings are taken under the wind the person watched; the schedule is feedback context and is never authored into the rig), and the requirements block (#113: the scene's declared requirements written as a `spine-parts-requirements/1` file and measured by the installed producer's `rig-parts check --requirements`, one worst-frame line each). Motion is strictly **view, annotate and export**: time/angle controls navigate inspection. This app does not author animation keys, retime motion or write `motion.json`. Future modeling touch-up remains in scope as a design goal; it is not implemented by this starter.
7
+ The person uses one inspection workspace with **Setup** and **Animate** sections and a review dialog for feedback (the compare page keeps **View**, **Rig**, **Playback** and **Feedback** sections). Setup covers setup geometry, source art, pivot/joint placement, meshes, weights and draw order; Animate covers angle coverage, frame intervals, reference video/poses, contact/deformation, audio inspection and the inspection environment (wind, gravity and impulses through the published player's `environment`/`moved`; its state is feedback context, never a model or motion edit) and the physics tuning panel (#103: constraint values edited as config patch ops and applied through the producer, never written into the model by review), and the readings block (#108: the compiler's own `rigc render` readings of the drawn animation, run on the inspected build and on the latest scratch build, shown as timeline ticks and worst-frame lines), the Environment block's *Use for readings* (#112: the controls exported as a `rigc-environment/1` schedule that readings, Apply's check and *Check under this world* — the installed producer's `rig-parts check --environment` — read, so the bars and readings are taken under the wind the person watched; the schedule is feedback context and is never authored into the rig), and the requirements block (#113: the scene's declared requirements written as a `spine-parts-requirements/1` file and measured by the installed producer's `rig-parts check --requirements`, one worst-frame line each). Time/angle controls navigate inspection. Timeline edits are six typed keyed operations on a scratch copy of `motion.animations_from`, built by the installed producer; review never writes source motion. Implemented modeling instruments send bounded changes through the installed producer into scratch, including setup-space mesh deltas.
8
8
 
9
9
  ## Implemented foundation
10
10
 
@@ -18,15 +18,15 @@ Identity, revision and content hash bind every decision. A submission also recor
18
18
 
19
19
  ## Retarget tuning (#114)
20
20
 
21
- Animate's Retarget block edits what a pose retarget is made from — the `rig-pose-map/1` (per chain, the bone that carries each segment), the clean and retarget flags and the declared sequence — and hands them to the installed `@rig-c/pose`, which writes the motion in scratch; review authors no keys and never writes the package's `motion.json`. The block is the "point → rebuild → watch → repeat" loop of the modeling instruments applied to motion inputs: the producer's refusals come back by name, the built animation plays beside its reference, and its FEET / STANCE / FLIP / SHORT / END-ON / LEG-SCALE / REACH lines seek to their frames. Key editing stays outside the app.
21
+ Animate's Retarget block edits what a pose retarget is made from — the `rig-pose-map/1` (per chain, the bone that carries each segment), the clean and retarget flags and the declared sequence — and hands them to the installed `@rig-c/pose`, which writes the motion in scratch; review authors no keys and never writes the package's `motion.json`. The block is the "point → rebuild → watch → repeat" loop of the modeling instruments applied to motion inputs: the producer's refusals come back by name, the built animation plays beside its reference, and its FEET / STANCE / FLIP / SHORT / END-ON / LEG-SCALE / REACH lines seek to their frames. Timeline edits use `set_key_time`, `set_key_value`, `set_key_curve`, `set_key_ease`, `insert_key` and `delete_key` through the shared scratch runner (`src/animation-ops.ts`), never on source files.
22
22
 
23
23
  ## Modeling touch-up direction
24
24
 
25
- The chest-region editor and Edit Mesh exist for detail that cannot be said in words. Issue #99 states the loop: **point → rebuild → watch → repeat → submit**. Review builds no mesh itself; **Apply · Rebuild runs the installed producer as a child process** on the user's own designation, into a scratch build beside the inspected one, and the viewer reloads that build in place. Every applied state goes into the draft and the submitted feedback (`context.applied`), so the AI receiving the review gets the exact last applied state, not a description of it. Edit Mesh's delta has no producer operation yet and refuses by name.
25
+ The chest-region editor and Edit Mesh exist for detail that cannot be said in words. Issue #99 states the loop: **point → rebuild → watch → repeat → submit**. Review builds no mesh itself; **Apply · Rebuild runs the installed producer as a child process** on the user's own designation, into a scratch build beside the inspected one, and the viewer reloads that build in place. A feedback row captures the applied state being watched when that row is created (`context.applied`); submitting the review sends those existing rows. Apply followed directly by Submit does not automatically add the latest applied state to feedback. A unified described/made handoff remains separate work (#369 / create#91), not an automatic transfer promised by this workspace. Edit Mesh sends a typed setup-space delta through `rig-parts remesh --delta` and the shared compile/check runner, loading the scratch revision in place; producer refusals remain named.
26
26
 
27
27
  Every Apply needs a binding to what the inspected rig was built from (issue #101): the **producer handoff**, declared (`open --config`, or the review.json `producer` block) or found at fixed places (`config.json`, `rig/config.json`, and last `../config.json` beside an opened `out/`, which the bar names as outside the folder). Its files are hashed into the reviewed identity beside the package, and once per session a **baseline** rebuilds the whole rig from them and says whether it reproduces the inspected one. An op that rebuilds the whole rig runs only on a reproduced baseline (`EDIT_BASELINE_MISMATCH` names the first differing path); `remesh` checks its own part (`REMESH_BASELINE_MISMATCH`). A patch that touches only what `rig-parts retune` splices — constraints, the idle's tracks and duration, the blink's numbers — runs retune instead (parts 1.44.0+, #136), which holds every other byte of the inspected rig itself, so a build whose repair is a mesh the config does not reproduce can still take a physics or idle edit — but not one whose repair redrew an image, which retune holds too, nor one whose rig.json is not the writer's text (#148; the baseline line says which); bones, stops, regions, turn and the blink's groups and still keep the whole-rig path and its guard.
28
28
 
29
- Edits reach the producer as data (issue #102): every edit card states its edit as one **config patch** (`rig-review-config-patch/1`: the config hash it was made against, JSON Pointer ops, the producer and the op), and one generic runner applies it to a scratch copy of the handoff config, runs the op (`rig` for the whole rig, `remesh` for one part's entry), compiles and runs `check` on the result. A stale patch is refused (`EDIT_PATCH_STALE`) rather than rebased. The page's client exposes `applyPatch(patch)` with #99's stream, in-place reload and Reset; the physics tuning panel (#103) is the first editing UI that produces them. What was applied — the patch, its hash, the producer's line, check's summary and the rig.json diff — rides in `context.applied`, so the AI receiving the review can rebuild exactly that state.
29
+ Edits reach the producer as data (issue #102): config-based edit cards state their edit as one **config patch** (`rig-review-config-patch/1`: the config hash it was made against, JSON Pointer ops, the producer and the op), and one generic runner applies it to a scratch copy of the handoff config, runs the op (`rig` for the whole rig, `remesh` for one part's entry), compiles and runs `check` on the result. Mesh deltas, retarget requests and keyed motion operations retain their own typed artifacts and runner paths; they are not flattened into config patches. A stale config patch is refused (`EDIT_PATCH_STALE`) rather than rebased. The page's client exposes `applyPatch(patch)` with #99's stream, in-place reload and Reset; the physics tuning panel (#103) is the first editing UI that produces them. For a feedback row created while that patch build is drawn, `context.applied` captures the patch, its hash, the producer's line, check's summary and the rig.json diff. Submit preserves that row's captured state rather than replacing it with the latest Apply.
30
30
 
31
31
  Physics tuning (#103) edits only what the handoff config declares: a constraint row is resolved by `name` (and kind) against the config, never by index alone, and every op records both the index (its pointer) and the name, which the server checks (`EDIT_PATCH_NAME_MISMATCH`). Rows the rig stage adds (the `turn` twins) have no config field and are shown not editable with the reason. An Apply reloads under the world it was pressed in so before and after are seen under one wind, gust and jolt state; review judges no value (a mass of 0 is rigc's `A23` to refuse). A build whose check FAILed may be loaded and looked at, but a review written on it is not submitted (`EDIT_SUBMIT_UNCHECKED`). Published Play 1.14.0 supplies the six-field live preview (#206): strength, damping, inertia, wind, gravity and mix use its public set/read/clear methods; mass and component toggles still require Apply. Slider input updates the pending override; the label distinguishes it from the last evaluated effective values. The next evaluation uses the patch; a paused page explicitly re-poses the held time without seeking. Clear removes overrides while preserving pending ops and integrated history, and authored values resume at the next evaluation; it does not undo the old trajectory. Apply and model replacement clear the preview. It is labelled "preview — Apply decides" and is never recorded as applied state. Play replays the current standing patch, not historical edits: backward seek recomputes with today's patch, and a newly opened track's first authored pose precedes its pending patch. The readout's BEFORE for the inspected build is that build's own check: once the baseline reproduces, `rig-parts check` runs on the baseline output (byte-identical to the inspected rig) in the background, and its summary is stored beside the baseline record.
32
32
 
@@ -146,3 +146,57 @@ Rules:
146
146
  A layout is offered only for inputs that actually loaded and rendered. One pure decision (`src/comparison-eligibility.ts`) takes load outcomes, never declared paths: the rig counts after its first successful draw, an image after `decode()`, a pose after it parses, and a video after `seeked` at the held time with a decoded frame. A new video stays pending until then; a held time outside its duration is refused as `REFERENCE_OUT_OF_DOMAIN`, never clamped.
147
147
 
148
148
  Single review keeps the requested layout in the source-bound draft and shows it when usable; otherwise the most useful loaded single pane is shown. Unavailable layout buttons stay visible, disabled, with the named reason as their description, and no placeholder pane stands in for a missing input. Two-build comparison keeps its identity and domain checks: a failed side leaves the survivor as a static single pane with the failed side named, feedback needs the settled pair, and a real zero-duration domain allows static inspection without playback. Modeling-candidate comparison is reported as unavailable (no producer handoff); no candidate UI exists. Remote observation reports the requested and effective layouts and each reason.
149
+
150
+ ## Four inspection stages
151
+
152
+ The same numbered navigation appears on parts, compiled and compare inspections:
153
+ 1 Parts + mesh, 2 Interview, 3 Rig + animation, 4 Direction. These are navigation,
154
+ not create pipeline stages or sign-offs. Opening or switching never submits a
155
+ verdict, applies an edit or starts a producer job. Interview and Direction name
156
+ their missing consumer contracts; no tools are fabricated for them.
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.
169
+
170
+ Only Stage 3 shows the legacy Setup, Animate and Compare switch; its existing
171
+ instruments, DOM and mode IDs are retained. In Stage 1 a compare session keeps
172
+ the A/B source picker usable and shows the selected side's cached atlas frame.
173
+ **Open setup mesh instruments** returns from the atlas to Setup; it does not
174
+ rebuild. Existing bookmarks, Apply/Reset provenance, selected slot, compare side,
175
+ 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.
178
+ The parts-only entry retains its part selection, geometry and pending verdict
179
+ while visiting unavailable stages; it needs no compiled model.
180
+
181
+
182
+ ## Shared parts viewport and comments
183
+
184
+ Standalone pre-rig parts and the compiled Stage 1 atlas frame mount `viewport-pair.ts`'s actual
185
+ rig/reference DOM. `parts-viewport-provider.ts` supplies raster geometry and painting-crop pixels;
186
+ `viewport-controller.ts` and `view-controls.ts` own camera writes, cursor zoom, pan, fit, resize
187
+ and the common two-pointer pinch. Parts' native scale policy is separate from the unchanged
188
+ compiled-rig Fit-relative policy. `parts-render.ts` remains the source of part, footprint and
189
+ mesh painting. The optional protected `--painting` input supplies the real reference crop;
190
+ A/B and adjustable-opacity Overlay share the original painting
191
+ transform from declared rig/source canvas geometry, with exact fractional placement. This is a visual
192
+ 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).
194
+ `tests/parts-comparison.test.ts` guards the geometry/settings; `tests/parts-overlay-browser.ts` verifies
195
+ displayed overlay pixels and comment restoration in both languages.
196
+
197
+ `stage-comments.ts` shares capture/composer/pins with a codec boundary for the closed parts
198
+ variant; no rig frame/slot/model placeholder is manufactured. `viewport-capture.ts` supplies
199
+ displayed viewport pixels, while `parts-comment-crops.ts` cuts native RGBA evidence on the server
200
+ from the bound original PNG. `comment-crops.ts` supplies their common PNG validator and immutable
201
+ store. [Parts view](PARTS_VIEW.md#pointed-parts-comments) names the format, refusals and the unit
202
+ and real-browser instruments that verify these behaviors.
package/docs/PANELS.md CHANGED
@@ -446,3 +446,34 @@ Each mark is an ordinary feedback row, category defect, with its available singl
446
446
  Placing and editing comments are refused while an unapplied authoring preview or designation is on stage, without disabling the **Comment · C (n)** button. The control's tooltip and adjacent status note name `COMMENT_UNAPPLIED_PREVIEW` and the active tool (Idle tracks, Rig fields dial/handles, Physics live overrides, a loaded density-strip candidate, or Chest/Bones/Cuts/Cloth/Mesh editing geometry/handles), and clicking **Comment · C (n)** still opens the list read-only so existing comments stay reachable and restorable while placing and editing are refused by that same named reason. Pending form values with no stage effect remain allowed. Stop that preview explicitly; Comment never clears or applies it. An applied scratch build retains its refusal (`COMMENT_APPLIED_BUILD_UNSUPPORTED`), and a model replacement names `COMMENT_SOURCE_BUSY`. Enable-before-preview and asynchronous pause/crop transitions are rechecked before capture/save. Standalone Turn pad, world/reference inspection and source mesh/bone/selection/weights inspection stay available. Retarget has no unapplied live pose path; Apply is a rebuild.
447
447
 
448
448
  A reference-basis comment cannot become a producer-frame strip: CLI and browser batch export refuse `COMMENT_REFERENCE_STRIP_UNAVAILABLE` for reference-frame comments on any viewport, including compare A/B fallback. No frame-rate/time mapping is attempted. Ordinary manual and producer-frame intervals still export; time-only comments retain `COMMENT_CLOCK_UNAVAILABLE`. Comments and their JSON/issue reports remain savable/readable with their original reference timing.
449
+
450
+ ## Four inspection stages
451
+
452
+ The same numbered navigation appears on parts, compiled and compare inspections:
453
+ 1 Parts + mesh, 2 Interview, 3 Rig + animation, 4 Direction. These are navigation,
454
+ not create pipeline stages or sign-offs. Opening or switching never submits a
455
+ verdict, applies an edit or starts a producer job. Interview and Direction name
456
+ their missing consumer contracts; no tools are fabricated for them.
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.
469
+
470
+ Only Stage 3 shows the legacy Setup, Animate and Compare switch; its existing
471
+ instruments, DOM and mode IDs are retained. In Stage 1 a compare session keeps
472
+ the A/B source picker usable and shows the selected side's cached atlas frame.
473
+ **Open setup mesh instruments** returns from the atlas to Setup; it does not
474
+ rebuild. Existing bookmarks, Apply/Reset provenance, selected slot, compare side,
475
+ 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.
478
+ The parts-only entry retains its part selection, geometry and pending verdict
479
+ while visiting unavailable stages; it needs no compiled model.
@@ -10,8 +10,8 @@ npx rig-review parts <out>/rig # the same package, named directly
10
10
  npx rig-review parts <out>/check # a built rig's atlas (any review package with a compiled model)
11
11
  ```
12
12
 
13
- Options: `--mesh-report <file>`, `--check <file>` (producer flags; see below), `--verdict <file>` (where the sign-off
14
- is written), `--port <n>`. Like `review`, it serves in the foreground and exits 3 s after its last tab closes.
13
+ Options: `--rig <file>` (mesh geometry), `--mesh-report <file>`, `--check <file>` (producer flags; see below), `--verdict <file>` (where the sign-off
14
+ is written), `--painting <png>` (the original painting), `--format json|issue` (export the saved verdict), `--port <n>`. Like `review`, it serves in the foreground and exits 3 s after its last tab closes.
15
15
 
16
16
  ## Inputs
17
17
 
@@ -23,7 +23,7 @@ is written), `--port <n>`. Like `review`, it serves in the foreground and exits
23
23
  ## What it shows
24
24
 
25
25
  - **Every part on its own**, on a sentinel background (green, magenta, black, white or checker), at native scale with
26
- 2× and 4× nearest-neighbour zoom. **Alpha only** shows the alpha channel as grey (white is opaque).
26
+ Fit and exact **1:1**, cursor-anchored wheel zoom, pinch and drag pan in the shared rig/reference viewport pair. Sampling stays nearest-neighbour. **Alpha only** shows the alpha channel as grey (white is opaque).
27
27
  - **Footprints of parts in front** (parts mode): the alpha of every part later in `parts.json` whose box meets the
28
28
  selected part's box, placed by its rig box and tinted cyan at 50 %. Where the selected part has no pixel under its
29
29
  occluder, the tint lands on the bare sentinel, so a back part that stops exactly at its occluder's edge shows the
@@ -32,6 +32,32 @@ is written), `--port <n>`. Like `review`, it serves in the foreground and exits
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
+ ### Producer row groups
36
+
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
+
35
61
  | Flag | Read from | When |
36
62
  | --- | --- | --- |
37
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) |
@@ -46,7 +72,7 @@ writes `parts-review.json` beside `parts.json` (atlas mode: beside the model), o
46
72
 
47
73
  ```json
48
74
  {
49
- "schema": "rig-review-parts-verdict/1",
75
+ "schema": "rig-review-parts-verdict/2",
50
76
  "mode": "parts",
51
77
  "tool": { "name": "@rig-c/review", "version": "1.4.3" },
52
78
  "source": {
@@ -56,6 +82,7 @@ writes `parts-review.json` beside `parts.json` (atlas mode: beside the model), o
56
82
  },
57
83
  "status": "pending",
58
84
  "parts": { "hair_back": { "outcome": "flagged", "note": "no material under the arm", "flags": ["faint:0"] } },
85
+ "comments": [],
59
86
  "updatedAt": "2026-11-04T00:00:00.000Z"
60
87
  }
61
88
  ```
@@ -73,6 +100,14 @@ Refusals, by name: `PARTS_VERDICT_MISSING_PART`, `PARTS_VERDICT_UNKNOWN_PART`, `
73
100
  `PARTS_VERDICT_NOT_CLEAN`, `PARTS_VERDICT_NOTHING_FLAGGED`, `PARTS_VERDICT_INVALID`, and `PARTS_VIEW_SOURCE_CHANGED`
74
101
  when a file changed after the view opened.
75
102
 
103
+ A verdict destination matching a protected part, producer report, rig/package input, model or atlas image is
104
+ refused as `PARTS_VERDICT_INPUT_COLLISION`, including normalized paths, symbolic links and filesystem aliases.
105
+ Choose a separate verdict file; saving an existing verdict again remains supported.
106
+
107
+ Sign-off JSON requests are limited to 4 MiB (4,194,304 bytes) of UTF-8 while streaming. An over-limit body is
108
+ cancelled before its remainder is read; a valid request exactly at the byte limit is accepted. Same-origin and
109
+ write-capability requirements remain unchanged.
110
+
76
111
  On reopen, a saved sign-off is offered only when both `source.sha256` and `source.flags` match the files on disk. When
77
112
  only the producer flags differ, the page says the saved sign-off is for different producer flags and starts fresh.
78
113
  Consumers that gate on the sign-off (rig-c/create) check `source.sha256`.
@@ -83,3 +118,163 @@ as `PARTS_IMAGE_OUTSIDE` / `PARTS_FILE_OUTSIDE`, and a discovered `mesh_report.j
83
118
  (`--mesh-report`, `--check`) is read where it is.
84
119
 
85
120
  Editing parts is out of scope: repairs go through the producer's source ladder, never the browser.
121
+
122
+ ## Mesh geometry
123
+
124
+ In parts mode, a `rig.json` beside `parts.json` supplies optional mesh geometry;
125
+ `--rig <file>` selects an explicit input instead. The per-part **mesh from
126
+ rig.json UVs** toggle starts off. It draws edges and vertices over the sentinel
127
+ background, and tints nontransparent art pixels pink when their centres lie
128
+ outside every nondegenerate triangle (triangle boundaries count as covered).
129
+ The mesh outcome has its own Pending / Clean / Flagged states and note; Flagged
130
+ requires a note. Approval requires both part and mesh outcomes to be Clean.
131
+ A part without a mesh has no mesh controls or outcome.
132
+
133
+ Image-space positions are `(u × width, v × height)` from each attachment's own
134
+ UVs and dimensions, never reconstructed through bones or weights. The mesh's raster
135
+ is the rig image; the parts PNG is located inside it by pixel equality. The
136
+ attachment's literal `image` under the rig spec's literal `images` directory must
137
+ be a local PNG of exactly the declared dimensions. Its centred window must match
138
+ the parts PNG RGBA exactly, and every pixel outside must have alpha zero. The
139
+ window offset `((W-w)/2,(H-h)/2)` is subtracted from mesh positions. Fractional
140
+ or negative offsets refuse; no padding constant is assumed. Border vertices
141
+ are allowed and drawn clipped. The rig raster is hashed in `source.files`. The producer
142
+ rounds UVs to six decimals: the coordinate error is at most `0.5e-6 × dimension`
143
+ pixels on each axis (for a 598×465 image, at most 0.000299 and 0.0002325 px).
144
+ The overlay cannot show this subpixel error, and coverage tint works at whole
145
+ pixels, so it cannot move a tinted pixel unless a triangle edge lies within that
146
+ rounding distance of a pixel centre. Coverage describes these derived triangles,
147
+ not an exact recovery of the producer's original unrounded positions.
148
+
149
+ Mode, vertex count, triangle count, `art_coverage` and `stray_cleared` are copied
150
+ from the part's `mesh_report.json` row without recomputing them. Absent fields
151
+ say **not reported**; faint islands remain in Producer flags. A report count may
152
+ differ from the loaded geometry; it is the producer's reading. The verdict's
153
+ `parts[name].mesh` contains `{outcome,note}` only for a mesh-bearing part.
154
+ `rig.json` and the loaded mesh report enter `source.files`, and the mesh report
155
+ also remains in `source.flags`. Changes invalidate the saved sign-off. No rig
156
+ means the existing parts view and verdict format remain unchanged.
157
+
158
+ | Refusal | Found / required |
159
+ | --- | --- |
160
+ | `PARTS_MESH_UNKNOWN_PART` | An attachment name not in parts.json / a known part |
161
+ | `PARTS_MESH_UV` | Invalid coordinate pairs or UV outside [0,1] / finite UV pairs in [0,1] |
162
+ | `PARTS_MESH_TRIANGLE` | Invalid triples or index / integer indices within the vertex array |
163
+ | `PARTS_MESH_SIZE` | Invalid declared dimensions / positive integer dimensions and image |
164
+ | `PARTS_MESH_IMAGE_SIZE` | Raster size / attachment dimensions |
165
+ | `PARTS_MESH_IMAGE_MISMATCH` | First differing RGBA pixel, nontransparent border or incompatible crop / exact centred window and transparent border |
166
+ | `PARTS_MESH_IMAGE_PATH` | Unsafe or missing rig raster / literal inside path |
167
+ | `PARTS_MESH_IMAGE_FORMAT` | Undecodable raster / PNG |
168
+ | `PARTS_MESH_AMBIGUOUS` | Multiple mesh attachments for one name / one mesh |
169
+ | `PARTS_MESH_REPORT_AMBIGUOUS` | Multiple report rows for a mesh part / at most one |
170
+ | `PARTS_MESH_MALFORMED` | Missing skins object / a rig spec with skins |
171
+ | `PARTS_MESH_OUTSIDE` | A discovered rig symlink escaping the package / an inside file |
172
+ | `PARTS_MESH_OUTCOME` | Missing or invalid mesh outcome or oversized note / a valid outcome and bounded note |
173
+ | `PARTS_MESH_OUTCOME_UNAVAILABLE` | Mesh outcome on a part without a mesh / no mesh outcome |
174
+
175
+ Explicit CLI file paths are the user's designation, as with `--mesh-report`;
176
+ discovered paths cannot escape the package. This view never writes geometry,
177
+ bones, weights or source images. Repairs remain producer config changes.
178
+
179
+ The four-stage navigator preserves this entry and its explicit save behavior. Compiled sessions reuse the atlas surface read-only; see [Four inspection stages](PANELS.md#four-inspection-stages).
180
+
181
+ ## Pointed parts comments
182
+
183
+ **Comment · C (n)** uses the same capture toggle, dragged region, composer and pins as the rig stage.
184
+ While capture is on, drag draws only a region; close the toggle to pan. Enter adds the comment;
185
+ **Save sign-off** persists the verdict. Select a comment row or pin after reopening to restore its
186
+ part, both cameras, background, alpha, footprints, mesh and painting comparison view. There is no frame, animation or slot
187
+ placeholder in a parts comment. Atlas inspection remains read only for pointed comments.
188
+
189
+ `rig-review-parts-verdict/2` adds `comments[]`; a `/1` file reads with an empty comment array.
190
+ Each closed `rig-review-parts-comment/1` carries `id`, original reviewer `summary`, `part`,
191
+ `imageHash` (SHA-256 of the original part PNG), `sourceHash` (the verdict source identity),
192
+ `imageRegion`, `rigRegion`, `view`, `crop` and `nativeCrop`. `imageRegion` has integer native
193
+ pixel edges snapped outward from the drag. `rigRegion` is exact placement plus that region,
194
+ including fractional placement; it is never rounded. `view.camera` records native scale,
195
+ center and viewport extent, plus `cameraSync` and the actual `referenceCamera` (or null), alongside `background`, `alpha`, `footprints` and `mesh`. New comments add optional
196
+ `view.comparison: {mode:"part"|"overlay", opacity:0..1}`; older comments omit it and restore the
197
+ ordinary part view. Unknown modes/keys and out-of-range opacity refuse `PARTS_COMPARISON_INVALID`.
198
+
199
+ The viewport `crop` comes from the shared displayed-pixel compositor and includes its mark.
200
+ `nativeCrop` is cut on the server from the hash-bound original PNG, preserving all RGBA bytes,
201
+ including alpha. Both use the common PNG validator/content-addressed store; paths are selected
202
+ by the server. The native crop has no alpha-mask, background or zoom transform. The saved
203
+ viewport crop includes its private inline PNG; exported JSON and issue Markdown replace it
204
+ with a resolved file path and hash. Both exports name the part and both regions and crops.
205
+
206
+ ```sh
207
+ npx rig-review parts <out>/rig --painting painting.png
208
+ npx rig-review parts <out>/rig --painting painting.png --format json
209
+ npx rig-review parts <out>/rig --painting painting.png --format issue
210
+ ```
211
+
212
+ The optional painting must be a PNG contained in the parts package (including symlink resolution),
213
+ with a portable source path. Format, size and hash derive from one buffer read. Its original dimensions
214
+ must satisfy `trunc(width × scale_rig_per_source) = rig_size[0]` and the equivalent height check
215
+ (`PARTS_PAINTING_SIZE`); missing/invalid declared geometry refuses `PARTS_PAINTING_MAPPING`.
216
+ The painting stays in `source.files` and the protected input set. Adding it to an older verdict changes
217
+ source identity and shows the existing stale-files warning; it never reuses that earlier approval.
218
+ `tests/parts-comparison.test.ts` and `tests/parts-comments.test.ts` guard these contracts and refusals.
219
+
220
+ ### Visual painting comparison
221
+
222
+ The existing reference viewport provides side-by-side A/B. **Overlay** draws the selected part over
223
+ that original painting at adjustable **Part opacity** (0 = painting, 1 = part composited over painting).
224
+ Both use the existing canvas host/camera/capture. The original source rectangle is exactly
225
+ `(x × originalWidth/rigWidth, y × originalHeight/rigHeight, w × originalWidth/rigWidth,
226
+ h × originalHeight/rigHeight)`, retaining fractional placement. Browser image interpolation displays
227
+ this continuous rectangle; it does not reproduce the producer's resampling or claim native pixel equality.
228
+ Alpha-only and mesh diagnostics are disabled in Overlay; front footprints remain available.
229
+ Without a painting the comparison controls are absent and the reference pane names
230
+ `PARTS_REFERENCE_UNAVAILABLE`. No comparison changes the verdict. These behaviors are guarded by
231
+ `tests/parts-comparison.test.ts`; `tests/parts-overlay-browser.ts` separately exercises trusted input,
232
+ actual displayed pixels, camera preservation, mode/opacity save/reload/restore and both exports in EN/KO.
233
+ Its native crop remains the original part RGBA, while the viewport crop shows the displayed comparison.
234
+ A current image/painting render failure clears the part pixels and refuses comment creation/editing
235
+ as `PARTS_PAINT_FAILED` until a successful repaint. Older failed generations cannot invalidate a
236
+ newer successful view (`tests/parts-async-navigation.test.ts`; focused browser evidence in
237
+ `tests/parts-paint-failure-browser.ts`).
238
+
239
+ The transform follows the whole-canvas geometry in pinned
240
+ [parts 2.17.0 sourceInRig](https://github.com/rig-c/parts/blob/971b3a7fab1109adf5be11750886687a7addb306/src/assemble.ts#L2141)
241
+ and the [parts coordinate contract](https://github.com/rig-c/parts/blob/971b3a7fab1109adf5be11750886687a7addb306/src/parts.ts#L14).
242
+ `tests/parts-comparison.test.ts` pins scale 0.5, fractional coordinates and truncated canvas dimensions.
243
+ `tests/viewport-controller.test.ts` guards a delayed reference-size change realigning the pair before gestures.
244
+ The public synthetic overlapping fixture is generated by `tests/helpers/parts-comparison-package.ts`.
245
+ For real scaled evidence, `scripts/prepare-parts-overlay-demo.ts` fetches hash-verified public demo
246
+ inputs at `ba99e403d4058fc1cfe40699bdcde8aaf00a90c0`, then runs explicitly installed `@rig-c/parts@2.17.0`
247
+ assemble in a separate fixture directory. It is an evidence script, never an app action.
248
+
249
+ **Difference remains absent** pending the producer-declared rig-space painting raster and
250
+ [the waiting consumer #390](https://github.com/rig-c/review/issues/390). Review adds no producer resampler.
251
+ Neither visual comparison nor opening a package supplies an approval.
252
+
253
+ Parts native zoom ranges from `min(fit, 1)` to 16; exact native 1 is always reachable. **Fit** is
254
+ a separate action, and **1:1** is shown only at exactly 1. Out-of-range requests refuse as
255
+ `PARTS_CAMERA_RANGE`; the compiled rig's Fit-relative 0.25–8 policy stays unchanged.
256
+
257
+ Named comment refusals include `PARTS_COMMENT_EMPTY`, `PARTS_COMMENT_FRACTIONAL`,
258
+ `PARTS_COMMENT_OUT_OF_BOUNDS`, `PARTS_COMMENT_STALE_SOURCE`, `PARTS_COMMENT_RIG_REGION`,
259
+ `COMMENT_CROP_INVALID` and `PARTS_COMMENT_NATIVE_CROP_TAMPERED`. Request bodies retain the
260
+ 4 MiB limit and same-origin capability gate. Native crops are limited to 16 million pixels;
261
+ viewport crops retain the rig comment's 200,000-character PNG limit.
262
+
263
+ Contract guards: `tests/parts-comments.test.ts`, `tests/viewport-controller.test.ts`,
264
+ `tests/comment-safety.test.ts`, `tests/stage-comments.test.ts` and `tests/i18n.test.ts`.
265
+ `tests/parts-comments-browser.ts` is separate real-browser evidence for cursor/pan/pinch,
266
+ two comments, save/reload, view restoration, both exports, EN/KO, native RGBA parity, painting
267
+ subrectangle parity, immutable source files and the compiled Stage 1 canonical host.
268
+ The superseded #387 byte-equality comparator scripts are retired; commit #388 retains their
269
+ original reproduction. Camera persistence wiring tests with live callers remain.
270
+
271
+ Native-crop revalidation checks the stored PNG file hash/dimensions and decoded RGBA against the
272
+ original subrectangle, rather than requiring a particular encoder's PNG bytes. Verdict reads never
273
+ create or rewrite crop files. Missing/unreadable stored evidence surfaces
274
+ `COMMENT_CROP_STATE_UNAVAILABLE`; invalid native pixels surface `PARTS_COMMENT_NATIVE_CROP_TAMPERED`.
275
+ These are validation failures, not a stale-source warning or a reset: a subsequent save also refuses
276
+ while the existing verdict cannot be revalidated. Real source/flag identity changes retain their
277
+ separate stale warning. `PARTS_PAINTING_OUTSIDE` and `PARTS_PAINTING_PNG` refuse external or non-PNG
278
+ painting inputs. `tests/parts-comments.test.ts` covers these read and cross-encoding boundaries;
279
+ `tests/parts-async-navigation.test.ts` guards reordered painting loads and actionable atlas clicks.
280
+ A downstream create consumer must support verdict/2 before a review release can ship.
@@ -817,3 +817,12 @@ The comment mode is captured once at gesture start; switching mode cancels an un
817
817
  Stage comment capture refuses unrecorded authoring effects, by `COMMENT_UNAPPLIED_PREVIEW` plus tool name: actual idle/dial adjust functions, live physics parameter patches, a pending loaded density-strip model, visible authoring geometry (Chest/Bones/Cuts/Cloth/Mesh), and Idle/Rig fields stage handles. Unapplied form operations alone do not trigger this refusal. The **Comment · C (n)** control displays the reason without disabling the button, so the list still opens read-only and rows still restore while placing and editing are refused by name; active capture is cancelled if a preview begins, and capture/save recheck after asynchronous pause/crop. No preview is automatically cleared/applied or omitted from a crop. Applied scratch builds retain their refusal (`COMMENT_APPLIED_BUILD_UNSUPPORTED`); rebuild/model swaps refuse `COMMENT_SOURCE_BUSY`. Turn pad, world/reference and source inspection remain inspection, not authored previews.
818
818
 
819
819
  `frame.basis:reference` remains valid comment evidence and is retained in JSON/issue reports, but it is not a producer frame interval. `COMMENT_REFERENCE_STRIP_UNAVAILABLE` refuses its CLI and browser batch strip exports before planning/render, independently of viewport side. No reference→producer time/index mapping occurs. Numeric producer/manual ranges remain unchanged; unavailable time-only ranges still refuse `COMMENT_CLOCK_UNAVAILABLE`.
820
+
821
+
822
+ ### Parts pointed evidence
823
+
824
+ Pre-rig parts uses `rig-review-parts-verdict/2` and the closed `rig-review-parts-comment/1`;
825
+ existing verdict/1 records read with no comments. This identity comes from the existing
826
+ parts verdict source digest and actual original PNG SHA-256, without a fabricated review
827
+ manifest id, revision or compiled model. The rig's `rig-review-comment/1` schema stays closed.
828
+ See [the parts contract and validation instruments](PARTS_VIEW.md#pointed-parts-comments).
package/docs/WORKFLOWS.md CHANGED
@@ -353,3 +353,7 @@ Control capabilities are excluded from links and browser persistence.
353
353
  On the view you are inspecting, choose **Comment · C (n)**, drag over the detail (or click a point), type, and press Enter. Turning **Comment · C (n)** on enters comment mode and opens the comment list; turning it off or pressing Escape leaves both. Click a pin on the stage or a row in the list to restore its captured pose and open that comment in the same composer to edit or delete before submitting through the existing review flow (submitted marks open read-only, and under a capture refusal the button still opens the list read-only). No target, interval or category form is required. [Panel behavior](PANELS.md#stage-comments) explains pins, crop fitting and frame availability.
354
354
 
355
355
  `rig-review feedback <input> --format json` and `--format issue` retain these comments in the existing feedback report. Compare uses the same A/B/reference/animation arguments as its open command. Each comment includes source hashes, viewport, frame basis, animation, `context.turn`, camera, screen/world region, nearest-first drawn slots, and crop path/SHA-256/dimensions. Derived CLI reports omit the inline PNG; the private draft and submitted session retain it. The CLI resolves the PNG's derived crop path under the review state directory so an agent can open it without a browser. Crop files are created on submission, outside the input package. Unsubmitted UI drafts stay local. No comment field or output byte is added to a review without comments.
356
+
357
+ The four-stage navigator preserves this entry and its explicit save behavior. Compiled sessions reuse the atlas surface read-only; see [Four inspection stages](PANELS.md#four-inspection-stages).
358
+
359
+ The managed front forwards only the trusted stage-atlas frame query (`stageEmbed=1`, `lang=en|ko`, and a required `side=a|b` for compare; no side for single). Unknown or duplicate keys are refused; the frame carries no filesystem path, command or capability. Stage navigation never changes CLI arguments or package bindings.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rig-review",
3
- "version": "1.5.4",
3
+ "version": "1.7.0",
4
4
  "type": "module",
5
5
  "description": "Local human rig inspection and structured feedback export",
6
6
  "license": "MIT",
@@ -19,10 +19,12 @@
19
19
  },
20
20
  "dependencies": {
21
21
  "@napi-rs/canvas": "1.0.11",
22
- "@rig-c/play": "1.23.0"
22
+ "@rig-c/play": "1.23.0",
23
+ "pngjs": "7.0.0"
23
24
  },
24
25
  "devDependencies": {
25
26
  "@types/bun": "^1.3.0",
27
+ "@types/pngjs": "6.0.5",
26
28
  "typescript": "^5.9.3"
27
29
  },
28
30
  "engines": {
package/src/cli.ts CHANGED
@@ -15,14 +15,14 @@ import { readFeedbackSession, readFeedbackCompareSession } from './session-histo
15
15
  import { startServer } from './server.ts';
16
16
  import { loadCompare } from './compare.ts';
17
17
  import { startCompareServer } from './compare-server.ts';
18
- import { loadPartsView, type PartsViewOptions } from './parts-view.ts';
18
+ import { loadPartsView, readVerdict, exportPartsVerdict, type PartsViewOptions } from './parts-view.ts';
19
19
  import { startPartsServer } from './parts-server.ts';
20
20
  import { readSession, type Feedback } from './session.ts';
21
21
  import { readCompareSession } from './compare-session.ts';
22
22
  import { exportReviewStrip, exportCompareStrip, stripJson, writeStripOutput, validateStripOutput } from './strip-export.ts';
23
23
  import type { StripInterval, StripRequest } from './strip.ts';
24
24
  const handoffUsage='[--config <path> [--parts <dir>] [--source <png> --full <dir> [--head <dir>]] [--keypoints <file>]]';
25
- const usage='Usage: rig-review open <dir> [--reference <video>] [--compare <dir>] [--animation <name>] [--control] [--direct] [--view-only] '+handoffUsage+'\n --config declares the producer handoff (wins over the review.json "producer" block and discovery of config.json, rig/config.json, ../config.json beside an opened out/); feedback and control take the same flags; --view-only opens without a producer handoff.\n open is managed by default: one loopback front at 127.0.0.1:4318 (RIG_REVIEW_FRONT_PORT overrides) serves /instances/<key>/; --direct serves the worker on its own port.\n rig-review control <dir> [--reference <video>] [--compare <dir>] [--animation <name>] '+handoffUsage+' [--page <id> --expected-revision <n> --command <JSON> --wait-ms <n>]\n rig-review feedback <dir> [--reference <video>] [--compare <dir>] [--animation <name>] '+handoffUsage+' [--format json|issue]\n Usage: bun run review -- <review.json|output-directory> [--port 4317] [--checkpoint ID] [--view-only]\n bun run check -- <review.json|output-directory>\n bun run feedback -- <review.json|output-directory>\n bun run review -- compare <a> <b> --reference <video> --animation <name> [--port 4317]\n bun run check -- compare <a> <b> --reference <video> --animation <name>\n bun run feedback -- compare <a> <b> --reference <video> --animation <name>\n rig-review parts <build root | parts dir | review package> [--mesh-report <file>] [--check <file>] [--verdict <file>] [--port <n>]\n rig-review --version';
25
+ const usage='Usage: rig-review open <dir> [--reference <video>] [--compare <dir>] [--animation <name>] [--control] [--direct] [--view-only] '+handoffUsage+'\n --config declares the producer handoff (wins over the review.json "producer" block and discovery of config.json, rig/config.json, ../config.json beside an opened out/); feedback and control take the same flags; --view-only opens without a producer handoff.\n open is managed by default: one loopback front at 127.0.0.1:4318 (RIG_REVIEW_FRONT_PORT overrides) serves /instances/<key>/; --direct serves the worker on its own port.\n rig-review control <dir> [--reference <video>] [--compare <dir>] [--animation <name>] '+handoffUsage+' [--page <id> --expected-revision <n> --command <JSON> --wait-ms <n>]\n rig-review feedback <dir> [--reference <video>] [--compare <dir>] [--animation <name>] '+handoffUsage+' [--format json|issue]\n Usage: bun run review -- <review.json|output-directory> [--port 4317] [--checkpoint ID] [--view-only]\n bun run check -- <review.json|output-directory>\n bun run feedback -- <review.json|output-directory>\n bun run review -- compare <a> <b> --reference <video> --animation <name> [--port 4317]\n bun run check -- compare <a> <b> --reference <video> --animation <name>\n bun run feedback -- compare <a> <b> --reference <video> --animation <name>\n rig-review parts <build root | parts dir | review package> [--rig <file>] [--mesh-report <file>] [--check <file>] [--verdict <file>] [--painting <png>] [--format json|issue] [--port <n>]\n rig-review --version';
26
26
  async function stripCommand(args:string[],options:{stateDir?:string}){
27
27
  const compare=args[0]==='compare';if(compare)args.shift();const a=args.shift(),b=compare?args.shift():undefined;if(!a||compare&&!b)throw new Error('strip: expected package input(s)');
28
28
  let reference:string|undefined,referenceVideo:string|undefined,animation:string|undefined,basis:'a'|'b'|undefined,range:string|undefined,output:string|undefined,jsonOnly=false,all=false;
@@ -95,16 +95,17 @@ function commandHelpRequested(args:readonly string[],command:'open'|'review'|'ch
95
95
  }
96
96
  return false;
97
97
  }
98
- const partsUsage='Usage: rig-review parts <build root | parts dir | review package> [--mesh-report <file>] [--check <file>] [--verdict <file>] [--port <n>]\n A directory holding parts.json (or a build root whose rig/ holds it) opens in parts mode, before rigging; a review package or check/ folder opens its atlas.\n The sign-off is written to parts-review.json beside parts.json (or the model), or to --verdict.';
98
+ const partsUsage='Usage: rig-review parts <build root | parts dir | review package> [--rig <file>] [--mesh-report <file>] [--check <file>] [--verdict <file>] [--painting <png>] [--format json|issue] [--port <n>]\n A directory holding parts.json (or a build root whose rig/ holds it) opens in parts mode, before rigging; a review package or check/ folder opens its atlas.\n The sign-off is written to parts-review.json beside parts.json (or the model), or to --verdict.';
99
99
  /** `rig-review parts` (#348): the parts and atlas view, served in the foreground; exits when its last tab closes. */
100
100
  async function partsCommand(args:string[]){
101
101
  const input=args.shift();if(!input||input==='--help'||input==='-h'){console.log(partsUsage);return;}
102
- const options:PartsViewOptions={};let port=4317;const seen=new Set<string>();
102
+ const options:PartsViewOptions={};let port=4317,format:'json'|'issue'|null=null;const seen=new Set<string>();
103
103
  while(args.length){const flag=args.shift()!;if(flag==='--help'||flag==='-h'){console.log(partsUsage);return;}if(seen.has(flag))throw new Error(`parts: duplicate option ${flag}`);seen.add(flag);const value=args.shift();if(!value)throw new Error(`Missing value for ${flag}`);
104
- if(flag==='--mesh-report')options.meshReport=value;else if(flag==='--check')options.check=value;else if(flag==='--verdict')options.verdict=value;
104
+ if(flag==='--format'){if(value!=='json'&&value!=='issue')throw new Error('--format: expected json or issue');format=value;}else if(flag==='--painting')options.painting=value;else if(flag==='--rig')options.rig=value;else if(flag==='--mesh-report')options.meshReport=value;else if(flag==='--check')options.check=value;else if(flag==='--verdict')options.verdict=value;
105
105
  else if(flag==='--port'){port=Number(value);if(!Number.isInteger(port)||port<0||port>65535)throw new Error('--port: expected integer 0..65535');}
106
106
  else throw new Error(`Unknown option ${flag}\n${partsUsage}`);}
107
107
  const pkg=await loadPartsView(input,options);
108
+ if(format){const saved=await readVerdict(pkg);if(!saved.verdict)throw new Error('PARTS_VERDICT_UNAVAILABLE: save a verdict first');process.stdout.write(exportPartsVerdict(saved.verdict,format));return;}
108
109
  const capability=randomBytes(32).toString('hex'),server=await startPartsServer(pkg,{port,capability,exitOnClose:true});
109
110
  const stop=(sig:string)=>{server.stop(true);console.log(`review parts: exiting — received ${sig}.`);process.exit(0);};process.once('SIGINT',()=>stop('SIGINT'));process.once('SIGTERM',()=>stop('SIGTERM'));
110
111
  console.log(`Parts view ready: http://127.0.0.1:${server.port}/#cap=${capability}\nMode: ${pkg.mode} · ${pkg.items.length} ${pkg.mode==='parts'?'parts':'regions'} · ${pkg.flags.length} producer flags\nSign-off: ${pkg.verdictPath}\nPress Ctrl+C to stop.`);
@@ -7,16 +7,29 @@ import {isDeepStrictEqual} from 'node:util';
7
7
  import {homedir} from 'node:os';
8
8
  import {parseStageComment,hasStageComment} from './stage-comment.ts';
9
9
  import type {Feedback} from './session.ts';
10
- export function validateCommentCrop(value:unknown):Buffer {
11
- const c=parseStageComment(value),bytes=Buffer.from(c.crop.png.slice('data:image/png;base64,'.length),'base64');
10
+ export interface PngCrop {path:string;sha256:string;png:string;width:number;height:number}
11
+ export function validateCommentCrop(value:unknown):Buffer {return validatePngCrop(parseStageComment(value).crop);}
12
+ /** Shared bounded PNG validator; callers own their closed comment codecs. */
13
+ export function validatePngCrop(crop:PngCrop):Buffer {
14
+ if(!crop||!Number.isSafeInteger(crop.width)||!Number.isSafeInteger(crop.height)||crop.width<1||crop.height<1||crop.width>16384||crop.height>16384||crop.width*crop.height>16777216||typeof crop.png!=='string'||crop.png.length>90*1024*1024||!/^data:image\/png;base64,[A-Za-z0-9+/]+={0,2}$/.test(crop.png)||!/^[a-f0-9]{64}$/.test(crop.sha256)||crop.path!==`comment-crops/${crop.sha256}.png`)throw new Error('COMMENT_CROP_INVALID: bounded content-addressed PNG required');
15
+ const c={crop},bytes=Buffer.from(c.crop.png.slice('data:image/png;base64,'.length),'base64');
12
16
  if(bytes.length<33||bytes.subarray(0,8).toString('hex')!=='89504e470d0a1a0a'||bytes.toString('ascii',12,16)!=='IHDR'||bytes.readUInt32BE(16)!==c.crop.width||bytes.readUInt32BE(20)!==c.crop.height||createHash('sha256').update(bytes).digest('hex')!==c.crop.sha256)throw new Error('COMMENT_CROP_INVALID: PNG signature, dimensions or SHA-256 differ');
13
17
  const data:Buffer[]=[];let offset=8,ended=false,hasData=false;const color=bytes[25],channels=color===6?4:color===2?3:0;if(bytes[24]!==8||!channels||bytes[26]!==0||bytes[27]!==0||bytes[28]!==0)throw new Error('COMMENT_CROP_INVALID: expected noninterlaced 8-bit RGB/RGBA');while(offset<bytes.length){if(offset+12>bytes.length)throw new Error('COMMENT_CROP_INVALID: truncated PNG chunk');const length=bytes.readUInt32BE(offset),end=offset+12+length;if(end>bytes.length)throw new Error('COMMENT_CROP_INVALID: PNG chunk length');const type=bytes.toString('ascii',offset+4,offset+8);let crc=0xffffffff;for(const n of bytes.subarray(offset+4,end-4)){crc^=n;for(let bit=0;bit<8;bit++)crc=(crc>>>1)^((crc&1)?0xedb88320:0);}if(((crc^0xffffffff)>>>0)!==bytes.readUInt32BE(end-4))throw new Error('COMMENT_CROP_INVALID: PNG chunk CRC');if(type==='IDAT'){hasData=true;data.push(bytes.subarray(offset+8,end-4));}if(type==='acTL')throw new Error('COMMENT_CROP_INVALID: static PNG required');if(type==='IEND'){if(length!==0||end!==bytes.length)throw new Error('COMMENT_CROP_INVALID: PNG end');ended=true;}offset=end;}if(!ended||!hasData)throw new Error('COMMENT_CROP_INVALID: PNG data/end missing');const stride=c.crop.width*channels+1;let inflated:Buffer;try{inflated=inflateSync(Buffer.concat(data),{maxOutputLength:stride*c.crop.height});}catch{throw new Error('COMMENT_CROP_INVALID: bounded PNG data decode');}if(inflated.length!==stride*c.crop.height||Array.from({length:c.crop.height},(_,i)=>inflated[i*stride]).some(n=>n===undefined||n>4))throw new Error('COMMENT_CROP_INVALID: PNG scanlines');return bytes;
14
18
  }
15
- const stateRoot=(state?:string)=>state??join(homedir(),'.local','state','rig-c-review');
19
+ const stateRoot=(state?:string)=>state??process.env.RIG_REVIEW_STATE_DIR??join(homedir(),'.local','state','rig-c-review');
20
+ export async function storePngCrop(crop:PngCrop,state?:string):Promise<void>{
21
+ const bytes=validatePngCrop(crop),folder=join(stateRoot(state),'comment-crops');await mkdir(folder,{recursive:true,mode:0o700});if(!(await lstat(folder)).isDirectory())throw new Error('COMMENT_CROP_PATH: regular state directory required');const path=join(folder,crop.sha256+'.png');
22
+ try{await writeFile(path,bytes,{mode:0o600,flag:'wx'});}catch(error){if((error as NodeJS.ErrnoException).code!=='EEXIST')throw error;const info=await lstat(path);if(!info.isFile()||createHash('sha256').update(await readFile(path)).digest('hex')!==crop.sha256)throw new Error('COMMENT_CROP_PATH: existing crop is not the bound regular PNG');}
23
+ }
24
+ export function resolvedCropPath(path:string,state?:string):string {if(!/^comment-crops\/[a-f0-9]{64}\.png$/.test(path))throw new Error('COMMENT_CROP_PATH: content-addressed PNG required');return resolve(stateRoot(state),path);}
25
+ /** Read and validate stored evidence without creating state directories or rewriting a PNG. */
26
+ export async function readPngCrop(crop:Omit<PngCrop,'png'>,state?:string):Promise<Buffer>{
27
+ const path=resolvedCropPath(crop.path,state);let bytes:Buffer;
28
+ try{const info=await lstat(path);if(!info.isFile())throw new Error('COMMENT_CROP_PATH: stored crop must be a regular PNG');bytes=await readFile(path);}catch(error){if(error instanceof Error&&error.message.startsWith('COMMENT_CROP_PATH:'))throw error;throw new Error('COMMENT_CROP_STATE_UNAVAILABLE: stored crop cannot be read');}
29
+ return validatePngCrop({...crop,png:'data:image/png;base64,'+bytes.toString('base64')});
30
+ }
16
31
  export async function saveCommentCrops(feedback:Feedback[],state?:string):Promise<void>{
17
- for(const f of feedback){const context=f.context as Record<string,unknown>|undefined;if(!hasStageComment(context?.comment))continue;const c=parseStageComment(context?.comment),bytes=validateCommentCrop(c),folder=join(stateRoot(state),'comment-crops');await mkdir(folder,{recursive:true,mode:0o700});if(!(await lstat(folder)).isDirectory())throw new Error('COMMENT_CROP_PATH: regular state directory required');const path=join(folder,c.crop.sha256+'.png');
18
- try{await writeFile(path,bytes,{mode:0o600,flag:'wx'});}catch(error){if((error as NodeJS.ErrnoException).code!=='EEXIST')throw error;const info=await lstat(path);if(!info.isFile()||createHash('sha256').update(await readFile(path)).digest('hex')!==c.crop.sha256)throw new Error('COMMENT_CROP_PATH: existing crop is not the bound regular PNG');}
19
- }
32
+ for(const f of feedback){const context=f.context as Record<string,unknown>|undefined;if(!hasStageComment(context?.comment))continue;await storePngCrop(parseStageComment(context?.comment).crop,state);}
20
33
  }
21
34
  /** Only comment-bearing exports acquire resolved derived-evidence paths; old/no-comment bytes stay unchanged. */
22
35
  export function commentCropPaths<T extends {feedback:Feedback[]}>(session:T,state?:string):T {
@@ -1,3 +1,4 @@
1
+ import {expandViewportPair} from '../web/viewport-pair.ts';
1
2
  /**
2
3
  * Single-source Setup and Animate workspace markup for comparison sessions (#234).
3
4
  *
@@ -72,7 +73,7 @@ const REGIONS: readonly {
72
73
  placeholder: '<!-- shared:animate-block-row -->',
73
74
  start: '<nav class="block-row" role="tablist" aria-label="Animate blocks">',
74
75
  end: '<section id="motion-tools"',
75
- compareEnd: '<div class="compare-info">',
76
+ compareEnd: '<section id="compare-transport-context">',
76
77
  },
77
78
  {
78
79
  key: 'transportStrips',
@@ -99,6 +100,7 @@ function sliceRegion(html: string, start: string, end: string, label: string): s
99
100
  }
100
101
 
101
102
  export function extractSharedWorkspaceMarkup(indexHtml: string): SharedWorkspaceMarkup {
103
+ indexHtml=expandViewportPair(indexHtml);
102
104
  const out = {} as Record<keyof SharedWorkspaceMarkup, string>;
103
105
  for (const r of REGIONS) out[r.key] = sliceRegion(indexHtml, r.start, r.end, r.key);
104
106
  return out;
@@ -1,3 +1,4 @@
1
+ import {stagePartsRoutes} from './stage-parts.ts';
1
2
  import {createControlServer,type ControlIdentity} from './control-server.ts';
2
3
  import {openGate,staleOpenStatus,accessGate,openNonceGate,openNonceHeader,sameSecret,stampOpen,type OpenIdentity} from './open-protocol.ts';
3
4
  import { readFile } from 'node:fs/promises';
@@ -21,7 +22,7 @@ import { createEnvironmentCheck, ENVIRONMENT_CHECK_LIMIT, EnvironmentCheckError
21
22
  import { renderCompareHtml } from './compare-html.ts';
22
23
  import { createLiveLifecycle, LIVE_PATH, type LiveExitInfo, type UpgradableServer } from './live-lifecycle.ts';
23
24
 
24
- const headers={'X-Content-Type-Options':'nosniff','Cache-Control':'no-store','Content-Security-Policy':"default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' blob: data:; media-src 'self'; connect-src 'self'; font-src 'self'; base-uri 'none'; frame-ancestors 'none'; form-action 'none'",'Referrer-Policy':'no-referrer'};
25
+ const headers={'X-Content-Type-Options':'nosniff','Cache-Control':'no-store','Content-Security-Policy':"default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' blob: data:; media-src 'self'; frame-src 'self'; connect-src 'self'; font-src 'self'; base-uri 'none'; frame-ancestors 'none'; form-action 'none'",'Referrer-Policy':'no-referrer'};
25
26
  const MALFORMED=new Set(['REBUILD_REQUEST_INVALID','DENSITY_STRIP_REQUEST_INVALID','DENSITY_STRIP_FIELD','MESH_PATCH_SCOPE','EDIT_PATCH_INVALID','EDIT_PATCH_OP_UNKNOWN','EDIT_PATCH_POINTER_INVALID','EDIT_PATCH_CMD_UNKNOWN','EDIT_PATCH_ARG_UNKNOWN','BONES_OP_OUT_OF_SCOPE','RETARGET_REQUEST_INVALID']);
26
27
  const json=(value:unknown,status=200)=>Response.json(value,{status,headers});
27
28
  async function bodyJson(req:Request,limit=1024*1024,what='Session payload exceeds 1 MiB'):Promise<unknown>{
@@ -43,6 +44,7 @@ function serveAsset(req:Request,path:string):Response{
43
44
  }
44
45
  /** `capability` (open workers and foreground CLI serving) gates every non-GET request; tests may omit it. */
45
46
  export async function startCompareServer(p:ComparePackage,options:{port?:number;stateDir?:string;open?:OpenIdentity;activity?:()=>void;control?:ControlIdentity;capability?:string;cwd?:string;stripConcurrency?:number;graceMs?:number;unopenedTimeoutMs?:number;exitOnClose?:boolean;onClose?:(info:LiveExitInfo)=>void|Promise<void>;log?:(line:string)=>void}={}){
47
+ const stageParts=stagePartsRoutes({a:p.a,b:p.b});
46
48
  const bundle=await buildWeb('compare');
47
49
  const frames=referenceFrameIndex(p.referencePath,p.response.binding.reference.sha256,p.response.sourceHash);
48
50
  const stateDir=options.stateDir??process.env.RIG_REVIEW_STATE_DIR??join(homedir(),'.local','state','rig-c-review');
@@ -79,6 +81,8 @@ export async function startCompareServer(p:ComparePackage,options:{port?:number;
79
81
  }
80
82
  live.onRequestStart(url.pathname);
81
83
  try {
84
+ const stageResponse=await stageParts(req);if(stageResponse)return stageResponse;
85
+
82
86
  const controlled=await control?.(req,origin);if(controlled)return controlled;
83
87
  options.activity?.();const gate=openGate(req,options.open);if(gate){if(gate.status===200){try{await assertCompareUnchanged(p);}catch{return staleOpenStatus(options.open!);}if(!live.rearmUnopened())return json({error:'Server is closing'},503);}return gate;}
84
88
  if(req.method==='PUT'&&url.pathname==='/api/compare/session'){