rig-review 2.4.6 → 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;
@@ -1085,6 +1085,7 @@ the host-owned integration example are in
1085
1085
  - `rig-review session ask <job-url> --generation <n> --key <id> --publication <id> --subject <JSON> [--request-id <id>]`
1086
1086
  - `rig-review session next <job-url> [--after <cursor>] [--wait-ms <n>] [--request-id <id>]`
1087
1087
  - `rig-review session close <job-url> --generation <n> --key <id> --reason <words> [--request-id <id>]`
1088
+ - Consumer only, `rig-review session fetch-act <job-url> --act <actId> --consumer-capability-stdin [--still-out <existing-directory>]`. The trusted consumer pipes its existing grant on stdin. New rig acts require `--still-out`.
1088
1089
  Agent verbs authenticate with `RIG_REVIEW_JOB_AGENT_CAPABILITY` (`Authorization: Bearer …`) against `http://127.0.0.1:<port>/jobs/<jobId>` and refuse `fetch-act` (`JOB_AUTHORITY_REFUSED`). See [Standing live job workflow](WORKFLOWS.md#standing-live-job-workflow) for an ordinary-package launch, bootstrap and explicit close example.
1089
1090
  - **Bootstrap-declared reviewer.** `JobReviewerBinding` (`id` and `role` as `'owner'` or `'delegate'` inside `JobHumanAuthority`) is declared by trusted host bootstrap when opening the window. The browser UI cannot type, edit or override this binding. It records bootstrap-declared provenance rather than keyboard-user authentication. Create maps `role` to its existing `by` authority and preserves the declared reviewer identity.
1090
1091
  - **Trusted host ports and public managed-host startup seam.** `JobHostPorts` separates `handleJobApi` (which accepts agent verbs and consumer `fetch-act` only) from closed same-origin UI routes (`readPublication`, `commitUIAct`, `ackDisplayed`, `jobLiveness`, `subscribeJob`, mounted by `createJobFront` under `/jobs/<jobId>/…` with sealed retained publication routes; the standalone owner HTML root accepts the default or literal `?lang=en` or `?lang=ko` only) that remain unavailable to agent tokens. Raw `Request` objects preserve real `Origin`, capability, body size and abort context. A TypeScript value is never authentication evidence. In the public managed-host startup seam (`startJobHost(options: JobHostOptions): Promise<JobOwnerHost>` from `@rig-c/review/job-host`, where `JobHostOptions extends JobWorkerOptions` adds `readerId?: string`, `bindingId?: string` and `partsEnumeratorId?: string`, frozen in [Public API stability](STABILITY.md#managed-owner-host)), each present hook (`readPublished`, `installWriterBinding`, `partsEnumerator`) requires a nonempty declared ID and a missing hook requires its ID to be absent (`JOB_HOST_OPTION_ID_INVALID`). Equal declared IDs, API/act schemas and actual enumerator versions permit authenticated active-listener reuse across processes and newly allocated function objects via `/jobs/<jobId>/host` (`schema: 'rig-review-job-host/1'`); differing IDs, hook-presence differences and unrecorded older listener IDs fail by name (`JOB_HOST_REUSE_MISMATCH`) with the option name and both IDs while preserving the existing listener. No function hashes are used. `installWriterBinding` receives `{jobId, origin, fetchCapability}` after reuse validation and runs on a matching new or reused host.
@@ -1143,9 +1144,23 @@ use exact member names and human words. Every source identity and digest is
1143
1144
  server-derived. Consumer fetch, human authority, drafts, nonce and cursor rules
1144
1145
  apply through the existing cycle. [Public shapes and refusals](STABILITY.md#image-set-verdict-extension).
1145
1146
 
1147
+ ### Rig verdict still backend
1148
+
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
+
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
+
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
+
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
+
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
+
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
+
1146
1161
  ### C4 schema and stored-state compatibility
1147
1162
 
1148
- API@1 and unsupported requests refuse `JOB_REQUEST_INVALID` with `JOB_API_SCHEMA_MISMATCH`, HTTP 400, the current API@2 response schema and unchanged generation. The CLI checks response schema before consuming its value. Consumer writers must also check act@2. JobData and host descriptors carry explicit `apiSchema` and `actSchema` markers. Missing or old stored markers refuse `JOB_STORED_SCHEMA_MISMATCH` before credentials, status or replay. Authenticated active-listener reuse compares declared hook IDs, API/act schemas and the actual enumerator version. A stopped listener can be explicitly restarted for the same job with new valid hook IDs. Old retained documents and approvals remain under their original schemas and are never migrated or relabelled. Legacy one-shot contracts retain their documented boundaries.
1163
+ API@1 and unsupported requests refuse `JOB_REQUEST_INVALID` with `JOB_API_SCHEMA_MISMATCH`, HTTP 400, the current API@2 response schema and unchanged generation. The CLI checks response schema before consuming its value. Consumer writers check act@2 for ordinary/historical acts and act@3 for new rig-review verdicts with a still. JobData and host descriptors carry explicit `apiSchema` and `actSchema` markers. Missing or old stored markers refuse `JOB_STORED_SCHEMA_MISMATCH` before credentials, status or replay. Authenticated active-listener reuse compares declared hook IDs, API/act schemas and the actual enumerator version. A stopped listener can be explicitly restarted for the same job with new valid hook IDs. Old retained documents and approvals remain under their original schemas and are never migrated or relabelled. Legacy one-shot contracts retain their documented boundaries.
1149
1164
 
1150
1165
  The manifest and complete retained image rows enter the composite source hash. Limits are 4096 rows, 128 UTF-16 role units, 4096 path units, 64 MiB per raw file or decoded RGBA allocation and 256 MiB unique retained bytes. Source-bound refusals retain the old head and generation. Reference-set, path, missing-file, PNG, hash and limit details are bounded. A missing row names its official zero-based index, role and manifest-relative path. Create #184 owns its production record projection and consumer checks, which remain pending. [Public boundary](STABILITY.md#parts-enumeration-boundary).
1151
1166
 
package/docs/STABILITY.md CHANGED
@@ -353,6 +353,8 @@ model binding nor a valid image-set binding uses `JOB_ASK_INVALID`.
353
353
 
354
354
  ## Named export inventory
355
355
 
356
+ The backend rig-still extension retains the twelve runtime exports and `JOB_ACT_SCHEMA` at act@2. `JobAct` additionally includes `JobRigReviewAct` at act@3 with top-level `JobRigStill`. The facade adds type-only `JobLegacyAct`, `JobRigReviewAct`, `JobRigStill` and `JobRigCapture` exports. Existing API/store/reuse markers and ordinary/historical acts retain @2. The rig revision constant and transport limits remain internal to `src/job-contract.ts`. Consumer checks distinguish these act revisions as described in [Rig verdict still backend](REVIEW_PACKAGE.md#rig-verdict-still-backend).
357
+
356
358
  The exact runtime exports are listed below. Constants preserve their literal
357
359
  values from the frozen semantic contract.
358
360
 
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-review",
3
- "version": "2.4.6",
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();
@@ -12,9 +12,54 @@ export function validateCommentCrop(value:unknown):Buffer {return validatePngCro
12
12
  /** Shared bounded PNG validator; callers own their closed comment codecs. */
13
13
  export function validatePngCrop(crop:PngCrop):Buffer {
14
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');
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');
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;
15
+ const bytes=Buffer.from(crop.png.slice('data:image/png;base64,'.length),'base64');
16
+ if(createHash('sha256').update(bytes).digest('hex')!==crop.sha256)throw new Error('COMMENT_CROP_INVALID: PNG signature, dimensions or SHA-256 differ');
17
+ return validatePngBytes(bytes,crop.width,crop.height);
18
+ }
19
+
20
+ /** Shared decoded-byte core. Callers enforce their own transport and byte limits. */
21
+ export function validatePngBytes(bytes:Buffer,width:number,height:number):Buffer {
22
+ if(!Number.isSafeInteger(width)||!Number.isSafeInteger(height)||width<1||height<1||
23
+ width>16384||height>16384||width*height>16777216||bytes.length<33||
24
+ bytes.subarray(0,8).toString('hex')!=='89504e470d0a1a0a'||
25
+ bytes.toString('ascii',12,16)!=='IHDR'||bytes.readUInt32BE(16)!==width||bytes.readUInt32BE(20)!==height) {
26
+ throw new Error('COMMENT_CROP_INVALID: PNG signature, dimensions or SHA-256 differ');
27
+ }
28
+ const data:Buffer[]=[];
29
+ let offset=8,ended=false,hasData=false;
30
+ const color=bytes[25],channels=color===6?4:color===2?3:0;
31
+ if(bytes[24]!==8||!channels||bytes[26]!==0||bytes[27]!==0||bytes[28]!==0) {
32
+ throw new Error('COMMENT_CROP_INVALID: expected noninterlaced 8-bit RGB/RGBA');
33
+ }
34
+ while(offset<bytes.length) {
35
+ if(offset+12>bytes.length)throw new Error('COMMENT_CROP_INVALID: truncated PNG chunk');
36
+ const length=bytes.readUInt32BE(offset),end=offset+12+length;
37
+ if(end>bytes.length)throw new Error('COMMENT_CROP_INVALID: PNG chunk length');
38
+ const type=bytes.toString('ascii',offset+4,offset+8);
39
+ let crc=0xffffffff;
40
+ for(const n of bytes.subarray(offset+4,end-4)) {
41
+ crc^=n;
42
+ for(let bit=0;bit<8;bit++)crc=(crc>>>1)^((crc&1)?0xedb88320:0);
43
+ }
44
+ if(((crc^0xffffffff)>>>0)!==bytes.readUInt32BE(end-4))throw new Error('COMMENT_CROP_INVALID: PNG chunk CRC');
45
+ if(type==='IDAT'){hasData=true;data.push(bytes.subarray(offset+8,end-4));}
46
+ if(type==='acTL')throw new Error('COMMENT_CROP_INVALID: static PNG required');
47
+ if(type==='IEND') {
48
+ if(length!==0||end!==bytes.length)throw new Error('COMMENT_CROP_INVALID: PNG end');
49
+ ended=true;
50
+ }
51
+ offset=end;
52
+ }
53
+ if(!ended||!hasData)throw new Error('COMMENT_CROP_INVALID: PNG data/end missing');
54
+ const stride=width*channels+1;
55
+ let inflated:Buffer;
56
+ try{inflated=inflateSync(Buffer.concat(data),{maxOutputLength:stride*height});}
57
+ catch{throw new Error('COMMENT_CROP_INVALID: bounded PNG data decode');}
58
+ if(inflated.length!==stride*height)throw new Error('COMMENT_CROP_INVALID: PNG scanlines');
59
+ for(let row=0;row<height;row++) {
60
+ if(inflated[row*stride]!>4)throw new Error('COMMENT_CROP_INVALID: PNG scanlines');
61
+ }
62
+ return bytes;
18
63
  }
19
64
  const stateRoot=(state?:string)=>state??process.env.RIG_REVIEW_STATE_DIR??join(homedir(),'.local','state','rig-c-review');
20
65
  export async function storePngCrop(crop:PngCrop,state?:string):Promise<void>{
package/src/entry.ts CHANGED
@@ -12,6 +12,7 @@ const sessionUsage = `Usage: rig-review session open <root>
12
12
  rig-review session ask <job-url> --generation <n> --key <id> --publication <id> --subject <JSON>
13
13
  rig-review session next <job-url> [--after <cursor>] [--wait-ms <n>]
14
14
  rig-review session close <job-url> --generation <n> --key <id> --reason <words>
15
+ rig-review session fetch-act <job-url> --act <actId> --consumer-capability-stdin [--still-out <existing-directory>]
15
16
  Open requires RIG_REVIEW_JOB_REVIEWER_ID and RIG_REVIEW_JOB_REVIEWER_ROLE (owner or delegate).
16
17
  RIG_REVIEW_JOB_AGENT_FD optionally delivers the private agent bootstrap on an inherited writable descriptor >= 3.
17
18
  Agent verbs use RIG_REVIEW_JOB_AGENT_CAPABILITY. Create's writer binding is installed by its trusted host callback.`;
package/src/job-act.ts CHANGED
@@ -1,15 +1,16 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import {
3
- JOB_ACT_SCHEMA, JOB_ENABLED_ACT_KINDS, JOB_PLAN_BOUND_SIGNOFF_STAGES, JOB_RESERVED_ACT_KINDS,
3
+ JOB_ACT_SCHEMA, JOB_RIG_REVIEW_ACT_SCHEMA, jobStillByteLimit, JOB_ENABLED_ACT_KINDS, JOB_PLAN_BOUND_SIGNOFF_STAGES, JOB_RESERVED_ACT_KINDS,
4
4
  type JobAct, type JobActValues, type JobPendingAsk, type JobReviewerBinding,
5
- type JobSourceBinding, type JobSubject, type JobUISubmission,
5
+ type JobSourceBinding, type JobSubject, type JobUISubmission, type JobRigCapture, type JobRigStill,
6
6
  } from './job-contract.ts';
7
- import { jobId, jobInteger, jobObject, requestDigest } from './job-api.ts';
7
+ import { jobHash, jobId, jobInteger, jobObject, requestDigest } from './job-api.ts';
8
8
  import { validatePicks } from './interview-picks.ts';
9
9
  import type { JobRetainedSource } from './job-source.ts';
10
10
  import { JobError } from './job-store.ts';
11
11
  import { checkedPath, readRegular } from './interview-project.ts';
12
12
  import { prepareJobImageSet } from './job-image-set.ts';
13
+ import {validatePngBytes} from './comment-crops.ts';
13
14
 
14
15
  function words(value: unknown): string {
15
16
  if (typeof value !== 'string' || value.length > 10_000) throw new JobError('JOB_ACT_INVALID');
@@ -66,16 +67,62 @@ export function bindJobAsk(subject: JobSubject, retained: JobRetainedSource): Jo
66
67
  }
67
68
 
68
69
  export function parseUISubmission(value: unknown): JobUISubmission {
69
- const item = jobObject(value, ['publicationId', 'askId', 'pageId', 'displayedNonce', 'expectedGeneration', 'submissionId', 'kind', 'value']);
70
+ const item = jobObject(value, ['publicationId', 'askId', 'pageId', 'displayedNonce', 'expectedGeneration', 'submissionId', 'kind', 'value', 'capture']);
70
71
  if ((JOB_RESERVED_ACT_KINDS as readonly unknown[]).includes(item.kind)) throw new JobError('JOB_ACT_KIND_DISABLED');
71
72
  jobId(item.publicationId); jobId(item.askId); jobId(item.pageId); jobId(item.displayedNonce); jobId(item.submissionId);
72
73
  jobInteger(item.expectedGeneration);
73
74
  if (!(JOB_ENABLED_ACT_KINDS as readonly string[]).includes(String(item.kind))) {
74
75
  throw new JobError('JOB_ACT_INVALID');
75
76
  }
77
+ if (item.capture !== undefined && (item.kind !== 'review-verdict' ||
78
+ (item.value as {stage?: unknown} | null)?.stage !== 'rig-review')) throw new JobError('JOB_REQUEST_INVALID');
76
79
  return item as unknown as JobUISubmission;
77
80
  }
78
81
 
82
+ /** The browser supplies pixels and draw provenance, never a trusted hash or path. */
83
+ export function prepareJobStill(input: JobUISubmission, ask: JobPendingAsk, retained: JobRetainedSource): {
84
+ readonly still: JobRigStill;
85
+ readonly bytes: Buffer;
86
+ readonly binding: JobRigCapture['binding'];
87
+ } {
88
+ if (input.kind !== 'review-verdict' || !input.capture) throw new JobError('JOB_STILL_CAPTURE_FAILED');
89
+ const capture = jobObject(input.capture, ['png', 'width', 'height', 'camera', 'framing', 'view', 'frame', 'animation', 'playing', 'binding']);
90
+ if (capture.camera !== 'fixed' || capture.framing !== 'default') throw new JobError('JOB_STILL_CAMERA_NOT_FIXED');
91
+ if (capture.view !== 'whole-rig') throw new JobError('JOB_STILL_VIEW_UNSUPPORTED');
92
+ const binding = jobObject(capture.binding, ['publicationId', 'instanceKey', 'sourceHash', 'pageId', 'askId', 'drawGeneration', 'playerGeneration']);
93
+ if (binding.publicationId !== input.publicationId || binding.publicationId !== ask.publicationId ||
94
+ binding.instanceKey !== retained.instanceKey || binding.sourceHash !== retained.source.sourceHash ||
95
+ binding.pageId !== input.pageId || binding.askId !== ask.askId ||
96
+ !Number.isSafeInteger(binding.drawGeneration) || (binding.drawGeneration as number) < 1 ||
97
+ !Number.isSafeInteger(binding.playerGeneration) || (binding.playerGeneration as number) < 0) {
98
+ throw new JobError('JOB_STILL_BINDING_MISMATCH');
99
+ }
100
+ if (typeof capture.playing !== 'boolean') throw new JobError('JOB_STILL_CAPTURE_FAILED');
101
+ const frame = capture.frame;
102
+ if (frame === 'setup') {
103
+ if (capture.animation !== undefined) throw new JobError('JOB_STILL_CAPTURE_FAILED');
104
+ } else {
105
+ if (typeof frame !== 'number' || !Number.isFinite(frame) || frame < 0 ||
106
+ typeof capture.animation !== 'string' || !capture.animation || capture.animation.length > 512 ||
107
+ retained.source.subject === 'image-set' || !retained.source.model) throw new JobError('JOB_STILL_CAPTURE_FAILED');
108
+ const model = JSON.parse(readRegular(checkedPath(retained.snapshotRoot, retained.source.model.path), 64 * 1024 * 1024).toString('utf8'));
109
+ const clip = model.animations?.find((item: {name: string; duration: number}) => item.name === capture.animation);
110
+ if (!clip || !Number.isFinite(clip.duration) || frame > clip.duration) throw new JobError('JOB_STILL_CAPTURE_FAILED');
111
+ }
112
+ const prefix = 'data:image/png;base64,';
113
+ if (typeof capture.png !== 'string' || capture.png.length > prefix.length + Math.ceil(jobStillByteLimit / 3) * 4 ||
114
+ !/^data:image\/png;base64,[A-Za-z0-9+/]+={0,2}$/.test(capture.png)) throw new JobError('JOB_STILL_CAPTURE_FAILED');
115
+ const bytes = Buffer.from(capture.png.slice(prefix.length), 'base64');
116
+ if (bytes.length > jobStillByteLimit || prefix + bytes.toString('base64') !== capture.png) throw new JobError('JOB_STILL_CAPTURE_FAILED');
117
+ try { validatePngBytes(bytes, capture.width as number, capture.height as number); }
118
+ catch { throw new JobError('JOB_STILL_CAPTURE_FAILED'); }
119
+ const sha256 = jobHash(bytes);
120
+ const common = {path: sha256 + '.png', sha256, camera: 'fixed' as const};
121
+ const still: JobRigStill = frame === 'setup' ? {...common, frame} :
122
+ {...common, frame: frame as number, animation: capture.animation as string};
123
+ return {still, bytes, binding: binding as unknown as JobRigCapture['binding']};
124
+ }
125
+
79
126
  /** Only the authenticated UI host invokes this adapter. All source and authority
80
127
  * fields are daemon-owned. Empty/whitespace strings remain exact human words.
81
128
  */
@@ -85,6 +132,7 @@ export function finalizeJobAct(options: {
85
132
  readonly ask: JobPendingAsk;
86
133
  readonly retained: JobRetainedSource;
87
134
  readonly reviewer: JobReviewerBinding;
135
+ readonly still?: JobRigStill;
88
136
  }): JobAct {
89
137
  const { submission, ask, retained, reviewer } = options;
90
138
  if (ask.status !== 'pending') throw new JobError('JOB_ASK_SUPERSEDED');
@@ -182,6 +230,13 @@ export function finalizeJobAct(options: {
182
230
  case 'review-verdict': {
183
231
  const value = jobObject(submission.value, ['stage', 'verdict', 'words']);
184
232
  if (ask.subject.kind !== 'review-verdict' || ask.subject.stage === 'image-review' || value.stage !== ask.subject.stage) throw new JobError('JOB_ACT_INVALID');
233
+ if (ask.subject.stage === 'rig-review') {
234
+ if (!options.still) throw new JobError('JOB_STILL_CAPTURE_FAILED');
235
+ return {...envelope, schema: JOB_RIG_REVIEW_ACT_SCHEMA, kind: 'review-verdict',
236
+ source: {...source, model: source.model!, selector: source.selector as Extract<NonNullable<JobSourceBinding['selector']>, {kind: 'rig'}>},
237
+ value: {stage: 'rig-review', verdict: choice(value.verdict, ['pending', 'approved', 'changes-requested'] as const), words: words(value.words)},
238
+ still: options.still};
239
+ }
185
240
  return { ...envelope, kind: 'review-verdict', source: { ...source, model: source.model!,
186
241
  selector: source.selector as Extract<NonNullable<JobSourceBinding['selector']>, { kind: 'rig' | 'post' }> }, value: {
187
242
  stage: ask.subject.stage, verdict: choice(value.verdict, ['pending', 'approved', 'changes-requested'] as const), words: words(value.words),
package/src/job-api.ts CHANGED
@@ -3,6 +3,7 @@ import {
3
3
  JOB_API_SCHEMA, JOB_PARTS_ENUMERATOR_RANGE, JOB_ENABLED_ACT_KINDS, JOB_RESERVED_ACT_KINDS,
4
4
  type JobAgentRequest, type JobDisplayAcknowledgment, type JobFetchActRequest,
5
5
  type JobHostPorts, type JobResult, type JobSelector, type JobSubject,
6
+ jobCaptureBodyLimit, jobRawActMediaType,
6
7
  } from './job-contract.ts';
7
8
  import { JobError } from './job-store.ts';
8
9
  import type { JobSession } from './job-session.ts';
@@ -183,7 +184,7 @@ export function parseJobRequest(value: unknown): JobAgentRequest | JobFetchActRe
183
184
  throw new JobError('JOB_REQUEST_INVALID');
184
185
  }
185
186
 
186
- export async function jobBody(request: Request): Promise<unknown> {
187
+ export async function jobBody(request: Request, maximum = jobBodyLimit): Promise<unknown> {
187
188
  if (!/^application\/json(?:\s*;|$)/i.test(request.headers.get('content-type') ?? '')) {
188
189
  throw new JobError('JOB_REQUEST_INVALID');
189
190
  }
@@ -204,10 +205,14 @@ export async function jobBody(request: Request): Promise<unknown> {
204
205
  const { done, value } = await Promise.race([reader.read(), interrupted]);
205
206
  if (done) break;
206
207
  size += value.length;
207
- if (size > jobBodyLimit) throw new JobError('JOB_BODY_LIMIT');
208
+ if (size > maximum) throw new JobError('JOB_BODY_LIMIT');
208
209
  chunks.push(value);
209
210
  }
210
- return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks)));
211
+ const value = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks)));
212
+ if (size > jobBodyLimit && (value?.kind !== 'review-verdict' || value?.value?.stage !== 'rig-review' || !value.capture)) {
213
+ throw new JobError('JOB_BODY_LIMIT');
214
+ }
215
+ return value;
211
216
  } catch (error) {
212
217
  void reader.cancel().catch(() => {});
213
218
  if (error instanceof JobError) throw error;
@@ -241,12 +246,12 @@ export function createJobHostPorts(session: JobSession, origin: string): JobHost
241
246
  if (request.headers.get('sec-fetch-site') === 'cross-site' ||
242
247
  (ui ? sent !== origin : sent !== null && sent !== origin)) throw new JobError('JOB_SAME_ORIGIN_REQUIRED');
243
248
  }
244
- async function uiCall<Value>(job: string, request: Request, path: string, action: (body: unknown) => Promise<Value>): Promise<JobResult<Value>> {
249
+ async function uiCall<Value>(job: string, request: Request, path: string, action: (body: unknown) => Promise<Value>, maximum = jobBodyLimit): Promise<JobResult<Value>> {
245
250
  try {
246
251
  if (job !== session.jobId) throw new JobError('JOB_UNKNOWN');
247
252
  gate(request, path, true);
248
253
  session.authorize('ui', request.headers.get('X-Review-Capability'));
249
- return { ok: true, value: await action(await jobBody(request)) };
254
+ return { ok: true, value: await action(await jobBody(request, maximum)) };
250
255
  } catch (error) { return jobFailure(error); }
251
256
  }
252
257
  return {
@@ -257,6 +262,16 @@ export function createJobHostPorts(session: JobSession, origin: string): JobHost
257
262
  input = parseJobRequest(await jobBody(request));
258
263
  if (input.jobId !== session.jobId) throw new JobError('JOB_UNKNOWN');
259
264
  session.authorize(input.verb === 'fetch-act' ? 'consumer' : 'agent', request.headers.get('authorization'));
265
+ if (input.verb === 'fetch-act') {
266
+ const accept = request.headers.get('accept');
267
+ if (accept === jobRawActMediaType || accept === 'image/png') {
268
+ if (request.signal.aborted) throw new JobError('JOB_REQUEST_INVALID');
269
+ const bytes = session.readActExport(input.actId, accept === 'image/png');
270
+ return new Response(new Uint8Array(bytes), {headers: {...responseHeaders,
271
+ 'Content-Type': accept, 'Content-Length': String(bytes.byteLength)}});
272
+ }
273
+ if (accept && accept !== '*/*' && accept !== 'application/json') throw new JobError('JOB_REQUEST_INVALID');
274
+ }
260
275
  const value = await session.execute(input, request.signal);
261
276
  return Response.json({ schema: JOB_API_SCHEMA, verb: input.verb, jobId: input.jobId, requestId: input.requestId,
262
277
  generation: session.status().generation, ok: true, value }, { headers: responseHeaders });
@@ -275,7 +290,7 @@ export function createJobHostPorts(session: JobSession, origin: string): JobHost
275
290
  return { ok: true, value: session.displayPublication(publication) };
276
291
  } catch (error) { return jobFailure(error); }
277
292
  },
278
- commitUIAct: (job, request) => uiCall(job, request, base + '/ui/acts', body => session.commitUIAct(body)),
293
+ commitUIAct: (job, request) => uiCall(job, request, base + '/ui/acts', body => session.commitUIAct(body), jobCaptureBodyLimit),
279
294
  ackDisplayed: (job, request) => uiCall(job, request, base + '/ui/displayed', async body => {
280
295
  const item = jobObject(body, ['publicationId', 'pageId', 'sourceHash']);
281
296
  const ack: JobDisplayAcknowledgment = {