@rig-c/review 2.4.5 → 2.5.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.
@@ -1019,6 +1019,22 @@ and standalone parts retain their existing inspection surfaces.
1019
1019
 
1020
1020
  In the standing live-job contract ([Review #484](https://github.com/rig-c/review/issues/484)), direction carriage is metadata-only (`source.direction` and the `direction-review` stage on `review-verdict`). That metadata carriage is distinct from [Review #482](https://github.com/rig-c/review/issues/482) preview and [Review #483](https://github.com/rig-c/review/issues/483) actual plated take playback, while [Review #373](https://github.com/rig-c/review/issues/373) remains parked.
1021
1021
 
1022
+ ### Scene interview records
1023
+
1024
+ The interview reader supports the scene option codec and dated currentness in
1025
+ Create's merged [PROJECT contract](https://github.com/rig-c/create/blob/f1868eeeed2dcc6b792c230a8bf93117a05edcd5/docs/PROJECT.md#scene-option-context).
1026
+ It checks every historical answer and completed decision at its own time and
1027
+ retains original words, source, time and set bindings with named record issues.
1028
+ Pre-cutoff currentness-only exceptions display `INTERVIEW_OPTIONS_SCENE_LEGACY`
1029
+ without blocking the legacy interview. Full scene image and registration checks
1030
+ remain producer checks.
1031
+
1032
+ The temporary [#555 gate](https://github.com/rig-c/review/issues/555) refuses
1033
+ standing publication with `JOB_RECORD_INCOMPLETE` for scene answers, legacy
1034
+ warnings or historical record issues before publication lookup or snapshot
1035
+ writes. Named diagnostic carriage remains an unmet gate pending the signed
1036
+ job API@2 contract. An editable current scene can proceed to publication lookup.
1037
+
1022
1038
  ## Live job contract
1023
1039
 
1024
1040
  `src/job-contract.ts` defines the frozen semantic contract boundary for [Review #484](https://github.com/rig-c/review/issues/484), [Create #182](https://github.com/rig-c/create/issues/182), [Create #184](https://github.com/rig-c/create/issues/184), [Parts #1159](https://github.com/rig-c/parts/issues/1159) and [Parts #1163](https://github.com/rig-c/parts/issues/1163) under `JOB_API_SCHEMA` (`rig-review/job-api@2`) and `JOB_ACT_SCHEMA` (`rig-review/act@2`), implemented across the backend session/store (`src/job-store.ts`, `src/job-session.ts`, `src/job-source.ts`, `src/job-act.ts`, `src/job-api.ts`, `src/job-worker.ts`), standing 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`). One-shot file-handoff workflows documented elsewhere in this reference remain preserved as legacy/history compatibility for existing callers.
@@ -1069,6 +1085,7 @@ the host-owned integration example are in
1069
1085
  - `rig-review session ask <job-url> --generation <n> --key <id> --publication <id> --subject <JSON> [--request-id <id>]`
1070
1086
  - `rig-review session next <job-url> [--after <cursor>] [--wait-ms <n>] [--request-id <id>]`
1071
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`.
1072
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.
1073
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.
1074
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.
@@ -1127,9 +1144,23 @@ use exact member names and human words. Every source identity and digest is
1127
1144
  server-derived. Consumer fetch, human authority, drafts, nonce and cursor rules
1128
1145
  apply through the existing cycle. [Public shapes and refusals](STABILITY.md#image-set-verdict-extension).
1129
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. 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.
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 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.
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
+
1130
1161
  ### C4 schema and stored-state compatibility
1131
1162
 
1132
- 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.
1133
1164
 
1134
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).
1135
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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rig-c/review",
3
- "version": "2.4.5",
3
+ "version": "2.5.0",
4
4
  "type": "module",
5
5
  "description": "Local human rig inspection and structured feedback export",
6
6
  "license": "MIT",
@@ -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.`;
@@ -2,6 +2,7 @@ import { createHash } from 'node:crypto';
2
2
  import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, realpathSync } from 'node:fs';
3
3
  import { extname, join, resolve } from 'node:path';
4
4
  import { isDeepStrictEqual as equal } from 'node:util';
5
+ import {coveringChange, sceneAt} from './interview-scene.ts';
5
6
 
6
7
  type RecordData = Record<string, unknown>;
7
8
  export interface SetRef {path: string; sha256: string}
@@ -13,7 +14,14 @@ export interface InterviewSet {
13
14
  asks: Ask[]; assembly: {rule: 'single' | 'concat' | 'merge'}; constraints?: Constraint[];
14
15
  }
15
16
  interface Image {ref: SetRef; name: string; type: string}
16
- export interface HistoricalInterview {question: string; verbatim: string; by?: string; at?: string}
17
+ export interface HistoricalInterview {
18
+ question: string; verbatim: string; by?: string; at?: string;
19
+ ref?: SetRef; record?: string; answer?: RecordData;
20
+ }
21
+ export interface InterviewDiagnostic {
22
+ code: 'INTERVIEW_OPTIONS_STALE' | 'INTERVIEW_OPTIONS_SCENE_LEGACY';
23
+ question: string; record: string; ref: SetRef; at?: string;
24
+ }
17
25
  export interface InterviewQuestion {ref: SetRef; set: InterviewSet; editable: boolean; images: Image[]; hasParts: boolean; partsUnavailable?: boolean; answer?: RecordData}
18
26
  export const digest = (data: Buffer | string) => createHash('sha256').update(data).digest('hex');
19
27
  export const object = (v: unknown): RecordData => v !== null && typeof v === 'object' && !Array.isArray(v) ? v as RecordData : {};
@@ -24,7 +32,6 @@ const invalidOptions = (message: string): never => {throw new Error('INTERVIEW_O
24
32
  const stale = (message: string): never => {throw new Error('INTERVIEW_OPTIONS_STALE: ' + message);};
25
33
  const text = (v: unknown): v is string => typeof v === 'string' && !!v.trim();
26
34
  const id = (v: unknown): v is string => typeof v === 'string' && /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/.test(v);
27
- const stages = ['interview', 'plan-approved', 'parts', 'parts-review', 'rigging-interview', 'rigging', 'rig-review', 'post-interview', 'post', 'direction-review', 'accepted'];
28
35
  const optionStages = ['interview', 'rigging-interview', 'post-interview'];
29
36
 
30
37
  export function literalPath(path: unknown): path is string {
@@ -120,13 +127,7 @@ function validateSet(raw: RecordData, question: unknown, allowedStages: string[]
120
127
  return raw as unknown as InterviewSet;
121
128
  }
122
129
 
123
- function reopened(project: RecordData, stage: string, after: number, through: number): boolean {
124
- return records(project.reopens).some(reopen => {
125
- const index = stages.indexOf(String(reopen.stage));
126
- const at = date(reopen.at);
127
- return index >= 0 && index <= stages.indexOf(stage) && at > after && at <= through;
128
- });
129
- }
130
+ const reopened = coveringChange;
130
131
  function approval(project: RecordData, stage: string, at: number) {
131
132
  return records(project.signoffs).filter(s => s.stage === stage && (s.checkpoint === null || s.checkpoint === undefined) &&
132
133
  text(s.by) && s.by.toLowerCase() !== 'agent' && date(s.at) <= at &&
@@ -154,9 +155,30 @@ function contextAt(project: RecordData, stage: string, at: number): unknown {
154
155
  config: object(rig.provenance).config, parts: draft.parts};
155
156
  }
156
157
 
157
- function inspectContext(root: string, project: RecordData, raw: RecordData, set: InterviewSet, at: number, fresh: boolean) {
158
+ function inspectContext(root: string, project: RecordData, raw: RecordData, set: InterviewSet, at: number, fresh: boolean): {
159
+ images: Image[]; hasParts: boolean; partsUnavailable?: boolean; legacy?: boolean;
160
+ } {
158
161
  const drafted = date(set.drafted_at);
159
162
  const ctx = object(raw.context);
163
+ if (!Number.isFinite(at) || drafted > at || reopened(project, set.stage, drafted, at)) return stale(set.id);
164
+ if (ctx.kind === 'scene') {
165
+ if (set.stage !== 'post-interview') return stale(set.id);
166
+ let legacy = false;
167
+ let scene: RecordData = {};
168
+ for (const instant of [drafted, at]) {
169
+ const selected = sceneAt(project, instant, ref => jsonObject(boundBytes(root, ref)));
170
+ if (!selected || !equal(selected.context, ctx)) return stale(set.id);
171
+ if (!selected.current) {
172
+ if (drafted >= Date.parse('2026-11-08T00:00:00Z')) return stale(set.id);
173
+ legacy = true;
174
+ }
175
+ scene = selected.document;
176
+ }
177
+ const images = records(scene.plates).map(plate => ({
178
+ ref: {path: plate.path as string, sha256: plate.sha256 as string}, name: plate.role as string, type: 'image/png',
179
+ }));
180
+ return {images, hasParts: false, legacy};
181
+ }
160
182
  const expected = contextAt(project, set.stage, drafted);
161
183
  const historicalInputs = !fresh && set.stage === 'interview';
162
184
  const matches = historicalInputs ? ctx.kind === 'inputs' && records(ctx.files).length > 0 &&
@@ -214,13 +236,16 @@ export function readProject(root: string, now = Date.now()) {
214
236
  const interview = object(project.interview);
215
237
  const questions: InterviewQuestion[] = [];
216
238
  const historical: HistoricalInterview[] = [];
239
+ const diagnostics: InterviewDiagnostic[] = [];
240
+ let sceneAnswers = 0;
217
241
  const seen = new Map<string, string>();
218
- for (const [items, answerKey, allowed] of [
219
- [interview.framing, 'answer', ['interview']],
220
- [interview.waypoints, 'guide', optionStages.slice(0, 2)],
221
- [object(interview.post).items, 'guide', ['post-interview']],
242
+ for (const [items, answerKey, allowed, collection] of [
243
+ [interview.framing, 'answer', ['interview'], 'interview.framing'],
244
+ [interview.waypoints, 'guide', optionStages.slice(0, 2), 'interview.waypoints'],
245
+ [object(interview.post).items, 'guide', ['post-interview'], 'interview.post.items'],
222
246
  ] as const) {
223
- for (const item of records(items)) {
247
+ for (const [itemIndex, item] of records(items).entries()) {
248
+ const itemPath = `${collection}[${itemIndex}]`;
224
249
  const current = object(item[answerKey]);
225
250
  const answers = [current, ...records(item.history)];
226
251
  for (const answer of answers) {
@@ -230,33 +255,63 @@ export function readProject(root: string, now = Date.now()) {
230
255
  }
231
256
  }
232
257
  const entries = [
233
- ...(item.pending_options === undefined ? [] : [{ref: item.pending_options, answer: undefined}]),
234
- ...answers.filter(answer => object(answer.choice).spec === 'rig-create/interview-choice@1')
235
- .map(answer => ({ref: object(answer.choice).set, answer})),
258
+ ...(item.pending_options === undefined ? [] : [{ref: item.pending_options, answer: undefined, record: itemPath + '.pending_options'}]),
259
+ ...answers.map((answer, index) => ({answer, record: index === 0 ? itemPath + '.' + answerKey : `${itemPath}.history[${index - 1}]`}))
260
+ .filter(({answer}) => object(answer.choice).spec === 'rig-create/interview-choice@1')
261
+ .map(({answer, record}) => ({ref: object(answer.choice).set, answer, record})),
236
262
  ];
237
263
  for (const entry of entries) {
238
264
  const ref = binding(entry.ref);
239
265
  const prior = seen.get(ref.sha256);
240
266
  if (prior !== undefined) {
241
267
  if (prior !== ref.path) return invalid('A retained set hash has conflicting paths');
242
- continue;
243
268
  }
244
- const raw = readSet(root, ref);
245
- const expectedStage = allowed.length === 1 ? allowed[0]! :
246
- ['rig_type','reference','seethrough','assemble'].includes(String(item.id)) ? 'interview' : 'rigging-interview';
247
- const set = validateSet(raw, item.id, [expectedStage]);
248
- if (object(raw.context).kind === 'scene') throw new Error('INTERVIEW_CONTEXT_KIND_UNSUPPORTED: scene');
249
269
  const editable = entry.answer === undefined;
270
+ let raw: RecordData;
271
+ let set: InterviewSet;
272
+ try {
273
+ raw = readSet(root, ref);
274
+ const expectedStage = allowed.length === 1 ? allowed[0]! :
275
+ ['rig_type','reference','seethrough','assemble'].includes(String(item.id)) ? 'interview' : 'rigging-interview';
276
+ set = validateSet(raw, item.id, [expectedStage]);
277
+ } catch (error) {
278
+ if (editable) throw error;
279
+ const answer = entry.answer!;
280
+ historical.push({question: String(item.id), verbatim: typeof answer.verbatim === 'string' ? answer.verbatim : '',
281
+ by: typeof answer.by === 'string' ? answer.by : undefined, at: typeof answer.at === 'string' ? answer.at : undefined,
282
+ ref, record: entry.record, answer});
283
+ diagnostics.push({code: 'INTERVIEW_OPTIONS_STALE', question: String(item.id), record: entry.record, ref,
284
+ ...(typeof answer.at === 'string' ? {at: answer.at} : {})});
285
+ continue;
286
+ }
250
287
  if (editable && (set.stage === 'interview' || set.stage === 'rigging-interview') &&
251
288
  (object(interview.order).spec !== 'rig-create/stage-order@2' || !Number.isFinite(date(object(interview.order).choices_adopted_at)))) {
252
289
  throw new Error('INTERVIEW_CHOICE_REQUIRED: Adopt create choices before selecting');
253
290
  }
254
291
  if (editable && approval(project, set.stage === 'interview' ? 'plan-approved' : set.stage, now)) return invalid('Question approval is still live');
255
- const context = inspectContext(root, project, raw, set, editable ? now : date(entry.answer?.at), editable);
292
+ const sceneKind = object(raw.context).kind === 'scene';
293
+ if (!editable && sceneKind) sceneAnswers++;
294
+ const evaluate = (at: number, record: string) => {
295
+ try {
296
+ const {legacy, ...context} = inspectContext(root, project, raw, set, at, editable);
297
+ if (legacy) diagnostics.push({code: 'INTERVIEW_OPTIONS_SCENE_LEGACY', question: set.question, record, ref, at: new Date(at).toISOString()});
298
+ return context;
299
+ } catch (error) {
300
+ if (editable || !(error instanceof Error) || !error.message.startsWith('INTERVIEW_OPTIONS_STALE:')) throw error;
301
+ diagnostics.push({code: 'INTERVIEW_OPTIONS_STALE', question: set.question, record, ref,
302
+ ...(Number.isFinite(at) ? {at: new Date(at).toISOString()} : {})});
303
+ return {images: [], hasParts: false};
304
+ }
305
+ };
306
+ const context = evaluate(editable ? now : date(entry.answer?.at), entry.record);
307
+ const decision = object(entry.answer?.agent_decision);
308
+ if (!editable && ['at', 'value', 'fragments'].some(key => Object.hasOwn(decision, key))) {
309
+ evaluate(date(decision.at), entry.record + '.agent_decision');
310
+ }
256
311
  questions.push({ref, set, editable, answer: entry.answer, ...context});
257
312
  seen.set(ref.sha256, ref.path);
258
313
  }
259
314
  }
260
315
  }
261
- return {root, hash: digest(bytes), project, questions, historical};
316
+ return {root, hash: digest(bytes), project, questions, historical, diagnostics, sceneAnswers};
262
317
  }
@@ -56,7 +56,9 @@ export function interviewRoutes(root: string, output: string, capability: string
56
56
  };
57
57
  const current = async () => {
58
58
  await joined?.assertCurrent();
59
- if (readProject(opened.root).hash !== opened.hash) throw new Error('INTERVIEW_OPTIONS_STALE: Project changed; reopen the interview');
59
+ const validated = readProject(opened.root);
60
+ if (validated.hash !== opened.hash) throw new Error('INTERVIEW_OPTIONS_STALE: Project changed; reopen the interview');
61
+ return validated;
60
62
  };
61
63
  return async (req: Request, origin: string): Promise<Response | undefined> => {
62
64
  const url = new URL(req.url);
@@ -66,18 +68,24 @@ export function interviewRoutes(root: string, output: string, capability: string
66
68
  try {
67
69
  if (joined && interviewRequest(url.pathname) && !joined.available) return json({error:'INTERVIEW_UNAVAILABLE'}, 404);
68
70
  if (req.method === 'GET' && url.pathname === '/api/interview') {
69
- await current();
71
+ const validated = await current();
70
72
  const dir = destination();
71
- return json({...(joined ? {binding:{projectHash:opened.hash, sourceHash:joined.sourceHash, ...(joined.draftId===undefined?{version:joined.version}:{draftId:joined.draftId})}} : {}), historical:opened.historical, questions:opened.questions.map(question => ({
73
+ return json({...(joined ? {binding:{projectHash:opened.hash, sourceHash:joined.sourceHash, ...(joined.draftId===undefined?{version:joined.version}:{draftId:joined.draftId})}} : {}), historical:validated.historical, diagnostics:validated.diagnostics, questions:validated.questions.map(question => ({
72
74
  ...question, saved:question.editable ? readPicks(dir, question) : null,
73
75
  images:question.images.map(({name}, index) => ({name, url:'/api/interview/image/' + question.ref.sha256 + '/' + index})),
74
76
  }))});
75
77
  }
76
78
  const image = /^\/api\/interview\/image\/([a-f0-9]{64})\/(0|[1-9]\d*)$/.exec(url.pathname);
77
79
  if (image && req.method === 'GET') {
78
- await current();
79
- const asset = opened.questions.find(question => question.ref.sha256 === image[1])?.images[Number(image[2])];
80
- if (!asset) return json({error:'Not found'}, 404);
80
+ const validated = await current();
81
+ const index = Number(image[2]);
82
+ const asset = validated.questions.find(question => question.ref.sha256 === image[1] && question.images[index])?.images[index];
83
+ if (!asset) {
84
+ if (validated.diagnostics.some(diagnostic => diagnostic.ref.sha256 === image[1] && diagnostic.code === 'INTERVIEW_OPTIONS_STALE')) {
85
+ throw new Error('INTERVIEW_OPTIONS_STALE: Image evidence changed');
86
+ }
87
+ return json({error:'Not found'}, 404);
88
+ }
81
89
  let bytes: Buffer;
82
90
  try {bytes = boundBytes(opened.root, asset.ref);}
83
91
  catch {throw new Error('INTERVIEW_OPTIONS_STALE: Image bytes changed');}
@@ -0,0 +1,109 @@
1
+ /** Private scene option gate, from Create PROJECT rule 4. */
2
+ import {createHash} from 'node:crypto';
3
+ import {isDeepStrictEqual as equal} from 'node:util';
4
+ import type {SetRef} from './interview-project.ts';
5
+
6
+ type Data = Record<string, unknown>;
7
+ const object = (value: unknown): Data => value !== null && typeof value === 'object' && !Array.isArray(value) ? value as Data : {};
8
+ const records = (value: unknown): Data[] => Array.isArray(value) ? value.map(object) : [];
9
+ const date = (value: unknown) => typeof value === 'string' ? Date.parse(value) : NaN;
10
+ const text = (value: unknown): value is string => typeof value === 'string' && !!value.trim();
11
+ const hash = (value: unknown) => typeof value === 'string' && /^[a-f0-9]{64}$/.test(value);
12
+ const count = (value: unknown) => Number.isSafeInteger(value) && Number(value) > 0;
13
+ const path = (value: unknown): value is string => text(value) && !value.startsWith('/') && !/^[a-z]:/i.test(value) &&
14
+ !value.includes('\\') && value.split('/').every(part => part !== '' && part !== '.' && part !== '..');
15
+ const human = (value: unknown) => text(value) && value.toLowerCase() !== 'agent';
16
+ const stages = ['interview', 'plan-approved', 'parts', 'parts-review', 'rigging-interview', 'rigging', 'rig-review', 'post-interview', 'post', 'direction-review', 'accepted'];
17
+ const stale = (): never => {throw new Error('INTERVIEW_OPTIONS_STALE: scene context');};
18
+
19
+ function closed(value: unknown, required: string[], optional: string[] = []): boolean {
20
+ const data = object(value);
21
+ return data === value && required.every(key => Object.hasOwn(data, key)) &&
22
+ Object.keys(data).every(key => required.includes(key) || optional.includes(key));
23
+ }
24
+ const binding = (value: unknown) => closed(value, ['path', 'sha256']) && path(object(value).path) && hash(object(value).sha256);
25
+ function box(value: unknown): boolean {
26
+ return closed(value, ['x', 'y', 'width', 'height']) && Object.values(object(value)).every(n => typeof n === 'number');
27
+ }
28
+ function citation(value: unknown): boolean {
29
+ if (!closed(value, [], ['guide', 'asks', 'quote', 'delegated'])) return false;
30
+ const data = object(value);
31
+ return (!('guide' in data) || typeof data.guide === 'string') &&
32
+ (!('quote' in data) || typeof data.quote === 'string') &&
33
+ (!('delegated' in data) || typeof data.delegated === 'boolean') &&
34
+ (!('asks' in data) || Array.isArray(data.asks) && data.asks.every(ask => typeof ask === 'string'));
35
+ }
36
+ function plate(value: unknown): boolean {
37
+ const p = object(value), registered = object(p.registered);
38
+ return closed(value, ['role', 'path', 'sha256', 'width', 'height', 'rect', 'registered'], ['citation']) &&
39
+ ['background', 'foreground'].includes(String(p.role)) && path(p.path) && hash(p.sha256) && count(p.width) && count(p.height) && box(p.rect) &&
40
+ closed(p.registered, ['kind', 'ref']) && ['input', 'derived'].includes(String(registered.kind)) && text(registered.ref) &&
41
+ (!('citation' in p) || citation(p.citation));
42
+ }
43
+ function document(value: Data, n: unknown): boolean {
44
+ const rig = object(value.rig), animation = object(rig.animation), acceptance = object(rig.acceptance);
45
+ const signoff = object(acceptance.signoff), reviewPackage = object(acceptance.review_package), frame = object(value.frame);
46
+ return closed(value, ['schema', 'n', 'rig', 'frame', 'plates', 'layers']) && value.schema === 'rig-create/scene@1' && count(value.n) && value.n === n &&
47
+ closed(value.rig, ['version', 'acceptance', 'model', 'animation']) && count(rig.version) && binding(rig.model) &&
48
+ closed(rig.animation, ['name'], ['frames']) && text(animation.name) && (!('frames' in animation) || binding(animation.frames)) &&
49
+ closed(rig.acceptance, ['signoff', 'verdict', 'review_package']) && typeof acceptance.verdict === 'string' && /^versions\[\d+\]\.verdicts\[\d+\]$/.test(acceptance.verdict) &&
50
+ closed(acceptance.review_package, ['path', 'sha256']) && text(reviewPackage.path) && hash(reviewPackage.sha256) &&
51
+ closed(acceptance.signoff, ['stage', 'checkpoint', 'at']) && signoff.stage === 'rig-review' && signoff.checkpoint === null && Number.isFinite(date(signoff.at)) &&
52
+ closed(value.frame, ['space', 'stage']) && frame.space === 'rig-world-y-up' && box(frame.stage) &&
53
+ Array.isArray(value.plates) && value.plates.every(plate) && Array.isArray(value.layers) && value.layers.every(layer => typeof layer === 'string');
54
+ }
55
+
56
+ export function coveringChange(project: Data, stage: string, after: number, through: number): boolean {
57
+ const changes = [...records(project.reopens), ...records(project.amendments).map((entry): Data => ({...entry, stage: object(entry.target).stage}))];
58
+ return changes.some(change => {
59
+ const index = stages.indexOf(String(change.stage)), at = date(change.at);
60
+ return index >= 0 && index <= stages.indexOf(stage) && at > after && at <= through;
61
+ });
62
+ }
63
+ function sorted(value: unknown): unknown {
64
+ if (Array.isArray(value)) return value.map(sorted);
65
+ const data = object(value);
66
+ if (data !== value) return value;
67
+ return Object.fromEntries(Object.keys(data).sort().map(key => [key, sorted(data[key])]));
68
+ }
69
+ function current(project: Data, scene: Data, at: number): boolean {
70
+ const live = records(project.versions).map((version, index) => ({version, index})).filter(({version}) =>
71
+ version.kind === 'rig' && date(version.at) <= at && !coveringChange(project, 'rig-review', date(version.at) - 1, at));
72
+ const latest = live.sort((a, b) => Number(b.version.n) - Number(a.version.n))[0];
73
+ if (!latest || latest.version.n !== object(scene.rig).version) return false;
74
+ const {version, index} = latest;
75
+ const verdicts = records(version.verdicts);
76
+ const operative = verdicts.map((verdict, index) => ({verdict, index})).filter(({verdict}) =>
77
+ verdict.review === 'rig-review' && human(verdict.by) && verdict.verdict !== 'provisional' && date(verdict.at) <= at).at(-1);
78
+ if (!operative || operative.verdict.verdict !== 'accepted') return false;
79
+ const signature = records(project.signoffs).filter(signoff => signoff.stage === 'rig-review' && signoff.checkpoint === null &&
80
+ human(signoff.by) && date(signoff.at) <= at && object(signoff.target).version === version.n &&
81
+ !coveringChange(project, 'rig-review', date(signoff.at) - 1, at)).reverse().sort((a, b) => date(b.at) - date(a.at))[0];
82
+ if (!signature) return false;
83
+ const target = object(signature.target), pkg = object(version.review_package);
84
+ const packageHash = createHash('sha256').update(JSON.stringify(sorted({config: pkg.config, files: pkg.files}))).digest('hex');
85
+ if (target.verdict !== `versions[${index}].verdicts[${operative.index}]` ||
86
+ !equal(target.review_package, {path: `versions[${index}].review_package`, sha256: packageHash})) return false;
87
+ return equal(object(scene.rig).acceptance, {
88
+ signoff: {stage: signature.stage, checkpoint: signature.checkpoint, at: signature.at},
89
+ verdict: target.verdict, review_package: target.review_package,
90
+ });
91
+ }
92
+
93
+ export function sceneAt(project: Data, at: number, read: (ref: SetRef) => Data) {
94
+ if (project.scenes === undefined) return undefined;
95
+ if (!Array.isArray(project.scenes)) return stale();
96
+ const entries = records(project.scenes);
97
+ for (const [index, entry] of entries.entries()) {
98
+ if (!closed(entry, ['n', 'path', 'sha256', 'at', 'by']) || entry.n !== index + 1 ||
99
+ entry.path !== `evidence/scene/s${index + 1}.json` || !hash(entry.sha256) || !human(entry.by) ||
100
+ typeof entry.at !== 'string' || !entry.at.endsWith('Z') || !Number.isFinite(date(entry.at))) return stale();
101
+ }
102
+ const candidate = entries.filter(entry => date(entry.at) <= at).at(-1);
103
+ if (!candidate) return undefined;
104
+ const reference = {n: candidate.n, path: candidate.path as string, sha256: candidate.sha256 as string};
105
+ let scene: Data;
106
+ try {scene = read(reference);} catch {return stale();}
107
+ if (!document(scene, candidate.n)) return stale();
108
+ return {context: {kind: 'scene', scene: reference}, current: current(project, scene, at), document: scene};
109
+ }
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),