@rig-c/review 2.5.0 → 2.6.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.
@@ -11,7 +11,7 @@ npx rig-review parts <out>/check # a built rig's atlas (any review package
11
11
  ```
12
12
 
13
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.
14
+ is written), `--painting <png>` (the original painting), `--by <name>` (launch-only reviewer declaration), `--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
 
@@ -94,10 +94,14 @@ The occlusion-coverage report (rig-c/parts#998) is not read yet; the footprint t
94
94
 
95
95
  ## The sign-off
96
96
 
97
+ Standalone sign-off uses saved files. The active Create and Parts cycle uses finalized acts through the
98
+ [standing live job workflow](WORKFLOWS.md#standing-live-job-workflow).
99
+
97
100
  **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
101
 
99
102
  Each item is **pending**, **clean** or **flagged** with a note (a note is optional on clean). **Save sign-off**
100
- writes `parts-review.json` beside `parts.json` (atlas mode: beside the model), or to `--verdict`:
103
+ writes `parts-review.json` beside `parts.json` (atlas mode: beside the model), or to `--verdict`.
104
+ An unnamed save has the following `/2` shape.
101
105
 
102
106
  ```json
103
107
  {
@@ -120,7 +124,7 @@ writes `parts-review.json` beside `parts.json` (atlas mode: beside the model), o
120
124
  - `source.files` is `parts.json` and every part PNG (atlas mode: the model and every page), each path **relative to the
121
125
  verdict file's directory**, POSIX separators. A part added, removed or repainted after sign-off changes the hash.
122
126
  - `source.sha256` is the SHA-256 of the UTF-8 lines `<path>\t<sha256>\n`, one per `source.files` entry, sorted by path
123
- bytewise. Consumers recompute it from the files on disk.
127
+ bytewise. Review revalidates inspected inputs when reading a saved verdict.
124
128
  - `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.
125
129
  - `status`: `approved` only when every part is clean; `changes-requested` only with at least one part flagged;
126
130
  otherwise `pending`.
@@ -148,6 +152,81 @@ as `PARTS_IMAGE_OUTSIDE` / `PARTS_FILE_OUTSIDE`, and a discovered `mesh_report.j
148
152
 
149
153
  Editing parts is out of scope: repairs go through the producer's source ladder, never the browser.
150
154
 
155
+ ### Reviewer name and saved-result read
156
+
157
+ HQ supplies `--by` when launching owner-facing standalone parts windows.
158
+
159
+ ```sh
160
+ npx rig-review parts /absolute/path/to/out/rig --by "Reviewer name"
161
+ npx rig-review parts /absolute/path/to/out/rig --format json
162
+ ```
163
+
164
+ `--by` requires a nonblank name and stores the argument verbatim, including Unicode and surrounding
165
+ whitespace, on each explicit Save. Empty, whitespace-only, duplicate or export/correction-mode use fails
166
+ with exit 1. The name comes from the launch declaration. Browser fields and a reader's identity provide
167
+ no attribution authority. Opening and reading preserve the saved bytes.
168
+
169
+ | Saved revision | Attribution on default CLI JSON read |
170
+ | --- | --- |
171
+ | Legacy `rig-review-parts-verdict/1` or `/2` | `by: null`, including an ignored historical `by` extension |
172
+ | Named `rig-review-parts-verdict/3` | Required nonblank `by`, preserved verbatim |
173
+ | Explicit resave from an unnamed launch | New ordinary `/2` save with `by: null` on read, clearing the earlier name |
174
+
175
+ Named `/3` keeps the existing verdict fields and adds required `by`. A missing, null, non-string or
176
+ whitespace-only `/3` name refuses `PARTS_VERDICT_INVALID`. Older executables accepting only `/1` and `/2`
177
+ reject named `/3` with that refusal. This opt-in saved-format compatibility cost is part of the contract.
178
+
179
+ Ordinary `parts <input> --format json` returns normalized `schema: "rig-review-parts-verdict/2"` with
180
+ every existing field, including `mode`, `tool`, `source`, `status`, all per-part outcomes, notes and flags,
181
+ available mesh outcomes and notes, `comments` and `updatedAt`. It adds root `by: string | null` and
182
+ `savedFileSha256`, a 64-character lowercase hexadecimal SHA-256 of the exact saved bytes, including any
183
+ final LF. Legacy reads retain their original byte digest and `/1` normalizes to empty comments.
184
+
185
+ The core, recorded name and digest derive from one validated saved-file snapshot, with current source
186
+ and producer-flag checks. `source.sha256`, `source.files` and `source.flags` retain the inspected-input
187
+ binding. Exported comment crops retain resolved paths and hashes. Missing or stale saves refuse
188
+ `PARTS_VERDICT_UNAVAILABLE` with exit 1 and no successful JSON result. Read, date, JSON and evidence
189
+ failures retain their named refusals.
190
+
191
+ Agents retrieve the result through this CLI using the same input options and designated `--verdict`
192
+ when supplied. Storage layout stays internal. `savedFileSha256` identifies raw saved bytes. Create's
193
+ separate receipt hashes the exact CLI stdout, whose normalized JSON and metadata have their own byte
194
+ identity. The recorded reviewer name is bootstrap-declared provenance. Issue and correction exports
195
+ retain their existing forms.
196
+
197
+ ### Durable save notifications
198
+
199
+ Each successful standalone Save emits one UTF-8 stdout record after file and parent-directory fsync.
200
+ The illustrative path and digest below show the framing.
201
+
202
+ ```text
203
+ RIG_REVIEW_PARTS_SAVED {"verdictPath":"/absolute/path/to/parts-review.json","sha256":"0000000000000000000000000000000000000000000000000000000000000000","status":"approved","saveCount":1}
204
+ ```
205
+
206
+ Match the literal `RIG_REVIEW_PARTS_SAVED ` prefix, including its ASCII space, then parse the compact
207
+ JSON with keys `verdictPath`, `sha256`, `status`, `saveCount` in that order and one terminating LF.
208
+ Control characters and U+2028/U+2029 are escaped within the JSON. Accept complete LF-terminated records.
209
+ Existing startup output shares stdout. The writer awaits output completion and backpressure before
210
+ reporting ordinary save success.
211
+
212
+ `sha256` hashes the exact committed save buffer (matching `savedFileSha256` when that commit is read via
213
+ `--format json`, and distinct from the normalized CLI stdout receipt bytes) and uses 64 lowercase hex
214
+ characters. `status` is
215
+ `pending`, `approved` or `changes-requested`. Saves are serialized within one foreground process.
216
+ `saveCount` starts at 1 and advances through 2, 3 and onward for every durable save, including identical
217
+ saves, then restarts with a new process. The positive safe-integer counter is process-scoped.
218
+ `verdictPath` is informational. Agents query the CLI above for the validated result. A later save can
219
+ give that read a different digest.
220
+
221
+ A failed durable write emits zero save events and leaves the counter unadvanced, with named
222
+ `PARTS_VERDICT_WRITE_FAILED` or the existing validation refusal. Pre-replacement failure preserves the
223
+ previous file. Post-replacement durability failure can leave visible bytes requiring CLI readback.
224
+ Stdout failure after commit, including EPIPE, reports `PARTS_VERDICT_NOTIFY_FAILED` and exit 1 while
225
+ preserving the committed file and allocated count. Recovery uses CLI readback. Automatic save or
226
+ notification replay is disabled. A crash between commit and delivery can lose the event. The guarantee
227
+ covers an emission attempt after each durable commit while the process and stream remain available.
228
+ Crash-proof exactly-once delivery requires an additional acknowledgment/replay protocol.
229
+
151
230
  ## Mesh geometry
152
231
 
153
232
  In parts mode, a `rig.json` beside `parts.json` supplies optional mesh geometry;
@@ -1148,13 +1148,13 @@ apply through the existing cycle. [Public shapes and refusals](STABILITY.md#imag
1148
1148
 
1149
1149
  New rig-review verdicts use `rig-review/act@3` and a top-level `still` with `path`, `sha256`, `camera:"fixed"` and `frame`. The path is exactly `<sha256>.png`. Setup uses `frame:"setup"`. Numeric seconds require `animation` alongside the frame. Other new acts and historical rig acts retain act@2. `JOB_ACT_SCHEMA`, API@2, stored compatibility markers and the twelve public facade runtime exports retain their established values. The rig-specific revision constant is internal to the contract module. Public type exports include `JobRigReviewAct`, `JobRigStill` and `JobRigCapture`.
1150
1150
 
1151
- The authenticated rig UI submission accepts `capture` alongside the human `value`. Its closed fields are `png` as a PNG data URI, `width`, `height`, `camera`, `framing`, `view`, `frame`, optional `animation`, `playing` and `binding`. Binding contains `publicationId`, `instanceKey`, `sourceHash`, `pageId`, `askId`, `drawGeneration` and `playerGeneration`. The daemon compares source/page/ask/instance identity with the current displayed nonce and derives the hash and filename from validated PNG bytes. Draw provenance is supplied by the authenticated human UI. The PNG is the whole default-camera Rig viewport and its background, with tool overlays excluded. The standing window normally composites the player's model rasters and background into one visible canonical bitmap, with tool overlays kept separate. Capture synchronously makes only an equal-size copy of that committed bitmap. Model rendering and background composition occur exclusively during normal presentation. Whole-device-pixel global translation of the unchanged bitmap preserves capture eligibility. Changes to device-pixel phase, pane-local placement or extent, source binding, or player/frame generation refuse capture. A successful public draw snapshot binds canonical bitmap identity, native dimensions, CSS size and DPR, local placement and device-pixel phase together with the exact time, animation and source before asynchronous PNG encoding. The first full request and human words are retained for reply-loss retry. The inspection transport seeks and pauses playback. Exact-pixel acceptance compares the full model and background in an overlay-free square fixture. Frame chrome lies outside the capture contract. Continuous moving-playback acceptance remains separate in #559.
1151
+ The authenticated rig UI submission accepts `capture` alongside the human `value`. Its closed fields are `png` as a PNG data URI, `width`, `height`, `camera`, `framing`, `view`, `frame`, optional `animation`, `playing` and `binding`. Binding contains `publicationId`, `instanceKey`, `sourceHash`, `pageId`, `askId`, `drawGeneration` and `playerGeneration`. The daemon compares source/page/ask/instance identity with the current displayed nonce and derives the hash and filename from validated PNG bytes. Draw provenance is supplied by the authenticated human UI. The PNG is the whole default-camera Rig viewport and its background, with tool overlays excluded. The standing window normally composites the player's model rasters and background into one visible canonical bitmap, with tool overlays kept separate. Capture synchronously makes only an equal-size copy of that committed bitmap without pausing active playback. Model rendering and background composition occur exclusively during normal presentation. Whole-device-pixel global translation of the unchanged bitmap preserves capture eligibility. Changes to device-pixel phase, pane-local placement or extent, source binding, or player/frame generation refuse capture. A successful public draw snapshot binds canonical bitmap identity, native dimensions, CSS size and DPR, local placement and device-pixel phase together with the public wrapped clip time (`entry(0).animationTime` as numeric `frame`), internal unwrapped `trackTime` (`player.time`), loop state, animation and source before asynchronous PNG encoding. The first full request and human words are retained unchanged for reply-loss retry across subsequent motion or transport changes. The inspection transport starts paused on `Setup` (`Play` disabled, `Repeat` enabled), drives continuous playback through public `Play`/`Pause` and `Repeat` controls over an owned `requestAnimationFrame` loop, pauses on clip selection or manual time seek, and on a `Repeat` toggle explicitly restarts the clip with the new loop flag and deterministically seeks the current visible time (resetting physics carry and frame delta). Owned animation frames and playback stop on source replacement, hidden-hub visibility transitions, `pagehide` and unmount. Exact-pixel acceptance in an overlay-free square fixture compares the full viewport screenshot against the exported CLI PNG for paused captures, and compares the synchronously sampled canonical bitmap, copied encoding canvas and exported CLI PNG at `toBlob` entry for moving captures while playback continues. Frame chrome lies outside the capture contract.
1152
1152
 
1153
1153
  Failed capture, nondefault camera/framing, solo/highlight/comparison and mismatched binding refuse by name. Playing is accepted. Raw PNG is bounded to 8 MiB, each axis to 16384 and the decoded image to 16,777,216 pixels. Only authenticated same-origin rig-capture submissions may use a 12 MiB JSON body. Ordinary mutations retain 256 KiB. PNG BLOB, exact act bytes, act, replay, answered ask and event commit in one SQLite transaction. Retried submissions reuse the immutable first act. Close revokes fetch while preserving the act and PNG for the act lifetime.
1154
1154
 
1155
1155
  The existing consumer POST `/jobs/<jobId>/api` accepts the unchanged fetch-act body and existing bearer grant. Default/JSON Accept returns the existing API envelope. `Accept: application/vnd.rig-review.act+json` returns raw act bytes, and `Accept: image/png` returns the bound PNG for the same actId. Destination paths stay local to the CLI.
1156
1156
 
1157
- The consumer CLI bounds stdin to 4096 bytes and accepts one existing 64-hex grant with an optional final newline. It bounds raw act reads to 512 KiB and PNG reads to 8 MiB independently of Content-Length. It validates both responses before writing a PNG temporary file inside the existing consumer directory, fsyncs the file, renames it to the content-addressed filename and then writes exact act bytes to stdout. Per-directory local output serialization preserves existing verified PNGs and refuses conflicting files/locks. Pre-stdout failure removes only this invocation's files. A MIDWRITE EPIPE exits nonzero and may leave the installed PNG. The consumer ignores partial stdout on nonzero exit and owns act.json persistence and pair staging.
1157
+ The consumer CLI bounds stdin to 4096 bytes and accepts one existing 64-hex grant with an optional final newline. It bounds raw act reads to 512 KiB and PNG reads to 8 MiB independently of Content-Length. It validates both responses before writing a PNG temporary file inside the existing consumer directory, fsyncs the file, renames it to the content-addressed filename, fsyncs the destination directory and then writes exact act bytes to stdout. Per-directory local output serialization preserves existing verified PNGs and refuses conflicting files or a retained `.rig-review-still.lock`, naming the exact local lock path without automatically deleting another writer's lock. Pre-stdout failure removes only this invocation's files. A MIDWRITE EPIPE exits nonzero and may leave the installed PNG. The consumer ignores partial stdout on nonzero exit and owns act.json persistence and pair staging.
1158
1158
 
1159
1159
  The consumer writes successful stdout verbatim as act.json beside the PNG and hashes those exact bytes itself. The act contains the PNG hash only. No self-hash, manifest, envelope, private binding discovery or destination filesystem endpoint is introduced.
1160
1160
 
package/docs/WORKFLOWS.md CHANGED
@@ -609,13 +609,14 @@ bound has no hardware performance guarantee. Hidden hub members suspend their ev
609
609
 
610
610
  The active Create and Parts inspection cycle uses the semantic job contract in `src/job-contract.ts` (`JOB_API_SCHEMA` set to `rig-review/job-api@2`, `JOB_ACT_SCHEMA` set to `rig-review/act@2`, [Review #484](https://github.com/rig-c/review/issues/484)) together with the implemented backend session/store (`src/job-session.ts`, `src/job-source.ts`, `src/job-act.ts`, `src/job-api.ts`), loopback job front and browser window runtime (`src/job-front.ts`, `web/job-session.ts`), and `rig-review session` CLI (`src/entry.ts`, `src/job-cli.ts`). The public installed managed-host entry is `@rig-c/review/job-host` with frozen exports in [Public API stability](STABILITY.md#managed-owner-host), and Create's production publication reader and writer-owned sibling `fetch-act` readback remain pending [Create #184](https://github.com/rig-c/create/issues/184) (publishing a Create root containing `project.json` without a host `readPublished` callback refuses `JOB_SOURCE_UNRETAINABLE` with `CREATE_PUBLICATION_CONTRACT_UNAVAILABLE`). See [Live job contract](REVIEW_PACKAGE.md#live-job-contract) for the full schema and host seam reference.
611
611
 
612
- Exact CLI usage from `src/entry.ts` and `src/job-cli.ts` (`publish`, `ask`, `next` and `close` also accept optional `--request-id <id>`):
612
+ CLI usage (`publish`, `ask`, `next` and `close` also accept optional `--request-id <id>`).
613
613
 
614
614
  ```text
615
615
  Usage: rig-review session open <root>
616
616
  rig-review session publish <job-url> --generation <n> --key <id> --result <relative-path> --freeze-hold <id> [--selector <JSON>] [--record <path> --record-hash <sha256>]
617
617
  rig-review session ask <job-url> --generation <n> --key <id> --publication <id> --subject <JSON>
618
618
  rig-review session next <job-url> [--after <cursor>] [--wait-ms <n>]
619
+ rig-review session next <job-url> [--after <cursor>] --until act --wait-ms <n>
619
620
  rig-review session close <job-url> --generation <n> --key <id> --reason <words>
620
621
  ```
621
622
 
@@ -642,6 +643,41 @@ rig-review session close http://127.0.0.1:<port>/jobs/<job-id> \
642
643
  --generation <current-generation> --key close-1 --reason "inspection complete"
643
644
  ```
644
645
 
646
+ To wait for a finalized act from another authenticated CLI process, use one call with an explicit
647
+ integer overall wait of 1 through 600000 ms.
648
+
649
+ ```text
650
+ rig-review session next <job-url> --after <accepted-cursor> --until act --wait-ms 600000
651
+ ```
652
+
653
+ `--until` accepts `act` only. Missing, zero, fractional or out-of-range opt-in waits refuse
654
+ `JOB_REQUEST_INVALID` with exit 1 before HTTP. One monotonic deadline covers requests, response-body
655
+ reads, decoding and validation. Existing server waits remain bounded to 30000 ms each and are chained
656
+ inside this call, advancing through unrelated publication and ask events. Only complete responses
657
+ validated within the deadline are accepted. Calls without `--until act` retain their existing wait,
658
+ response and exit behavior, including immediate reads and successful timeout envelopes.
659
+
660
+ Success exits 0 with the whole validated `JobApiResponse` batch containing an act. Process every row
661
+ in `value.events`, including additional acts, before persisting `value.cursor`. Act rows expose
662
+ `act.actId` and `act.kind`. Reads replay events without consuming them. For future acts, pass the last
663
+ accepted cursor. An omitted `--after` starts historical replay. Resume from the last accepted cursor
664
+ and deduplicate by `actId` after retries.
665
+
666
+ On overall expiry, stderr reports CLI-local `JOB_NEXT_TIMEOUT` and exit 3. Stdout contains the last
667
+ accepted complete response envelope, preserving its cursor and status, or stays empty if none was
668
+ accepted. Closure before an act returns the closed response with `JOB_CLOSED` and exit 1. Authentication,
669
+ cursor, storage and caller-cancellation failures retain exit 1.
670
+
671
+ The acceptance bar includes one CLI wait spanning a real finalized UI act submitted after more than
672
+ 30 seconds. Focused validation covers a synthetic normal-CLI wait (`tests/job-next-wait.test.ts`)
673
+ where one `rig-review session next ... --until act --wait-ms 40000` call chains two 30000 ms-bounded
674
+ `next` API requests across ~31 seconds and returns a finalized synthetic UI act committed after 31
675
+ seconds, alongside fast multi-slice and boundary tests; full browser and PR CI acceptance runs
676
+ separately. Standalone legacy
677
+ file-only Save has the separate [save-notification contract](PARTS_VIEW.md#durable-save-notifications).
678
+ Waking this act wait requires a real finalized job act. Consumers use writer-owned `fetch-act` for
679
+ the source-bound result and deduplicate by `actId`.
680
+
645
681
  - **One standing window and visual gate.** Every owner visual, question, choice, correction and verdict goes through one standing Review window/link plus one what-to-look-at line. Internal agent and HQ media stay internal and are never substituted for the owner handoff. When a required visual is missing (`visual.status` set to `'unavailable'` with a named `code`), the agent stops immediately and files a Create on-path Review card rather than falling back to chat text or images.
646
682
  - **Human UI vs agent verbs.** People submit through the Review browser UI (`actor` set to `'human'`, `channel` set to `'review-ui'`). Trusted host bootstrap declares `reviewer` (`id` and `role` as `'owner'` or `'delegate'`), which the browser UI cannot type or override. This binding records bootstrap-declared provenance rather than keyboard-user authentication, and Create maps `role` to its existing `by` authority. Agents use only `publish`, `ask`, `next` and `close` (`JobAgentRequest`), with `expectedGeneration` compare-and-swap (CAS) and `idempotencyKey` on mutations.
647
683
  - **Explicit producer-held freeze and explicit close.** Every `publish` request designates a root-relative `result` (`path` and `selector`, never a command) and carries an explicit producer-held freeze (`freeze.kind` set to `'producer-held'`, `holdId`, `record` as `JobFileIdentity` or `null` for a declared non-Create root) held until acknowledgment. Review validates retained bytes, detects a moved record (`JOB_RECORD_MOVED`, `JOB_RECORD_INCOMPLETE`, `JOB_FREEZE_REQUIRED`, `JOB_SOURCE_MISMATCH`, `JOB_SOURCE_UNRETAINABLE`, `JOB_ROOT_REPLACED`) and commits local generation CAS (`JOB_GENERATION_STALE`, `JOB_IDEMPOTENCY_CONFLICT`). The freeze assertion is a caller obligation rather than a lock Review can impose on independent writers. Review offers no watched-root or automatic-close guarantee, and only explicit `close` ends an active job.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rig-c/review",
3
- "version": "2.5.0",
3
+ "version": "2.6.0",
4
4
  "type": "module",
5
5
  "description": "Local human rig inspection and structured feedback export",
6
6
  "license": "MIT",
package/src/cli.ts CHANGED
@@ -18,14 +18,14 @@ import { readFeedbackSession, readFeedbackCompareSession } from './session-histo
18
18
  import { startServer } from './server.ts';
19
19
  import { loadCompare } from './compare.ts';
20
20
  import { startCompareServer } from './compare-server.ts';
21
- import { loadPartsView, readVerdict, exportPartsVerdict, exportPartsCorrection, assertPartsUnchanged, type PartsViewOptions } from './parts-view.ts';
21
+ import { loadPartsView, readVerdict, readPartsVerdictJson, exportPartsVerdict, exportPartsCorrection, assertPartsUnchanged, type PartsViewOptions } from './parts-view.ts';
22
22
  import { startPartsServer } from './parts-server.ts';
23
23
  import { readSession, parseSession, sessionFile, type Feedback } from './session.ts';
24
24
  import { readCompareSession } from './compare-session.ts';
25
25
  import { exportReviewStrip, exportCompareStrip, stripJson, writeStripOutput, validateStripOutput } from './strip-export.ts';
26
26
  import type { StripInterval, StripRequest } from './strip.ts';
27
27
  const handoffUsage='[--config <path> [--parts <dir>] [--source <png> --full <dir> [--head <dir>]] [--keypoints <file>]]';
28
- const usage='Usage: rig-review open <dir> [<dir> ...] [--animation-for <index> <name>] [--reference <video>] [--compare <dir>] [--animation <name>] [--control] [--direct] [--view-only] [--project <create-root> (--project-version <rig> [--post-version <post>] | --project-draft <id> [--parts-verdict-dir <dir>]) --picks-dir <dir>] '+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 owner workspace at 127.0.0.1:4318 (RIG_REVIEW_FRONT_PORT overrides) hosts targets in one process; --animation applies to all targets, --animation-for overrides one 1-based target, and --direct keeps a separate single-target worker.\n rig-review control <dir> [--reference <video>] [--compare <dir>] [--animation <name>] '+handoffUsage+' [--project <create-root> --project-version <rig> --picks-dir <dir> [--post-version <post>]] [--page <id> --expected-revision <n> --command <JSON> --wait-ms <n>]\n rig-review feedback <dir> [--reference <video>] [--compare <dir>] [--animation <name>] '+handoffUsage+' [--project <create-root> --project-version <rig> --picks-dir <dir> [--post-version <post>]] [--format json|issue] [--correction <item id>]\n rig-review <dir> <dir> ... [--animation <name>] [--animation-for <index> <name>] [--port 4318] [--reference <video>] [--view-only] [--control] '+handoffUsage+'\n Foreground multi owns a new workspace in this CLI process; a compatible existing owner is joined and the launcher exits. Multi --port accepts 1..65535; single foreground keeps 4317 and --port 0.\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] [--correction <item id> --parts-file <inventory> [--part-note <part>]] [--port <n>]\n rig-review interview <create-root> --picks-dir <project-relative directory> [--port <n>]\n rig-review --version';
28
+ const usage='Usage: rig-review open <dir> [<dir> ...] [--animation-for <index> <name>] [--reference <video>] [--compare <dir>] [--animation <name>] [--control] [--direct] [--view-only] [--project <create-root> (--project-version <rig> [--post-version <post>] | --project-draft <id> [--parts-verdict-dir <dir>]) --picks-dir <dir>] '+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 owner workspace at 127.0.0.1:4318 (RIG_REVIEW_FRONT_PORT overrides) hosts targets in one process; --animation applies to all targets, --animation-for overrides one 1-based target, and --direct keeps a separate single-target worker.\n rig-review control <dir> [--reference <video>] [--compare <dir>] [--animation <name>] '+handoffUsage+' [--project <create-root> --project-version <rig> --picks-dir <dir> [--post-version <post>]] [--page <id> --expected-revision <n> --command <JSON> --wait-ms <n>]\n rig-review feedback <dir> [--reference <video>] [--compare <dir>] [--animation <name>] '+handoffUsage+' [--project <create-root> --project-version <rig> --picks-dir <dir> [--post-version <post>]] [--format json|issue] [--correction <item id>]\n rig-review <dir> <dir> ... [--animation <name>] [--animation-for <index> <name>] [--port 4318] [--reference <video>] [--view-only] [--control] '+handoffUsage+'\n Foreground multi owns a new workspace in this CLI process; a compatible existing owner is joined and the launcher exits. Multi --port accepts 1..65535; single foreground keeps 4317 and --port 0.\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>] [--by <name>] [--format json|issue] [--correction <item id> --parts-file <inventory> [--part-note <part>]] [--port <n>]\n rig-review interview <create-root> --picks-dir <project-relative directory> [--port <n>]\n rig-review --version';
29
29
  async function stripCommand(args:string[],options:{stateDir?:string}){
30
30
  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)');
31
31
  let reference:string|undefined,referenceVideo:string|undefined,animation:string|undefined,basis:'a'|'b'|undefined,range:string|undefined,output:string|undefined,jsonOnly=false,all=false;
@@ -201,17 +201,19 @@ function commandHelpRequested(args:readonly string[],command:'open'|'review'|'ch
201
201
  }
202
202
  return false;
203
203
  }
204
- 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] [--correction <item id> --parts-file <inventory> [--part-note <part>]] [--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.';
204
+ const partsUsage='Usage: rig-review parts <build root | parts dir | review package> [--rig <file>] [--mesh-report <file>] [--check <file>] [--verdict <file>] [--painting <png>] [--by <name>] [--format json|issue] [--correction <item id> --parts-file <inventory> [--part-note <part>]] [--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.';
205
205
  /** `rig-review parts` (#348): the parts and atlas view, served in the foreground; exits when its last tab closes. */
206
206
  async function partsCommand(args:string[]){
207
207
  const input=args.shift();if(!input||input==='--help'||input==='-h'){console.log(partsUsage);return;}
208
208
  const options:PartsViewOptions={};let port=4317,format:'json'|'issue'|null=null;const seen=new Set<string>();
209
- let itemId:string|undefined,partNote:string|undefined,inventory:string|undefined;
209
+ let itemId:string|undefined,partNote:string|undefined,inventory:string|undefined,by:string|undefined;
210
210
  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}`);
211
211
  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;
212
+ else if(flag==='--by'){if(!value.trim())throw new Error('--by: expected a nonblank reviewer name');by=value;}
212
213
  else if(flag==='--correction')itemId=value;else if(flag==='--part-note')partNote=value;else if(flag==='--parts-file')inventory=value;
213
214
  else if(flag==='--port'){port=Number(value);if(!Number.isInteger(port)||port<0||port>65535)throw new Error('--port: expected integer 0..65535');}
214
215
  else throw new Error(`Unknown option ${flag}\n${partsUsage}`);}
216
+ if(by!==undefined&&(format||itemId||partNote||inventory))throw new Error('--by: launch only; incompatible with export or correction options');
215
217
  if((itemId||partNote||inventory)&&(!format||!itemId||!inventory))throw new Error('CORRECTION_SELECTOR_INVALID: parts correction requires --format, --correction and --parts-file');
216
218
  const pkg=await loadPartsView(input,options);
217
219
  if(format&&itemId&&inventory){
@@ -223,10 +225,53 @@ async function partsCommand(args:string[]){
223
225
  process.stdout.write(format==='json'?exportPartsCorrection(verdict,projected):formatCorrectionIssue(projected)+'\n');
224
226
  return;
225
227
  }
228
+ if(format==='json'){process.stdout.write(await readPartsVerdictJson(pkg));return;}
226
229
  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;}
227
- const capability=randomBytes(32).toString('hex'),server=await startPartsServer(pkg,{port,capability,exitOnClose:true});
228
- 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'));
229
- 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.`);
230
+ const capability=randomBytes(32).toString('hex');
231
+ let outputFailure: Error | null = null;
232
+ let rejectWrite: ((error: Error) => void) | undefined;
233
+ let server: Awaited<ReturnType<typeof startPartsServer>> | undefined;
234
+ let stopping: Promise<void> | undefined;
235
+ const shutdown = () => stopping ??= server!.shutdown();
236
+ const failOutput = (cause: unknown) => {
237
+ if (outputFailure) return;
238
+ outputFailure = new Error('PARTS_VERDICT_NOTIFY_FAILED: stdout failed', {cause});
239
+ process.exitCode = 1;
240
+ console.error(outputFailure.message);
241
+ rejectWrite?.(outputFailure);
242
+ if (server) void shutdown();
243
+ };
244
+ const outputClosed = () => failOutput(new Error('stdout closed'));
245
+ process.stdout.on('error', failOutput);
246
+ process.stdout.on('close', outputClosed);
247
+ const stop = (signal: string) => {
248
+ if (!outputFailure) console.log(`review parts: exiting — received ${signal}.`);
249
+ void shutdown();
250
+ };
251
+ const interrupt = () => stop('SIGINT'), terminate = () => stop('SIGTERM');
252
+ try {
253
+ server = await startPartsServer(pkg, {port, capability, by, onNotifyFailure: failOutput,
254
+ onWriteFailure: error => console.error(error.message),
255
+ onSaved: async event => {
256
+ if (outputFailure) throw outputFailure;
257
+ const line = 'RIG_REVIEW_PARTS_SAVED ' + JSON.stringify(event).replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029') + '\n';
258
+ // The callback settles after the complete write, including when write() reports backpressure.
259
+ await new Promise<void>((resolve, reject) => {
260
+ rejectWrite = reject;
261
+ try { process.stdout.write(line, error => error ? failOutput(error) : resolve()); }
262
+ catch (error) { failOutput(error); }
263
+ }).finally(() => { rejectWrite = undefined; });
264
+ },
265
+ });
266
+ process.once('SIGINT', interrupt);process.once('SIGTERM', terminate);
267
+ 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.`);
268
+ if (outputFailure) await shutdown();
269
+ await server.live.exited;
270
+ if (stopping) await stopping;
271
+ } finally {
272
+ process.removeListener('SIGINT', interrupt);process.removeListener('SIGTERM', terminate);
273
+ process.stdout.removeListener('error', failOutput);process.stdout.removeListener('close', outputClosed);
274
+ }
230
275
  }
231
276
  export async function main(args:string[],options:{stateDir?:string}={}){
232
277
  options={stateDir:options.stateDir??defaultStateDir()};if(args[0]==='--')args.shift();