rig-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.
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 = {
package/src/job-cli.ts CHANGED
@@ -1,7 +1,12 @@
1
1
  import { randomUUID } from 'node:crypto';
2
- import { JOB_API_SCHEMA, type JobAgentRequest } from './job-contract.ts';
3
- import { assertJobApiSchema, jobFailure, parseJobRequest } from './job-api.ts';
2
+ import {closeSync, constants, fstatSync, fsyncSync, lstatSync, openSync, readFileSync, renameSync, unlinkSync, writeSync} from 'node:fs';
3
+ import {join} from 'node:path';
4
+ import { JOB_API_SCHEMA, JOB_ACT_SCHEMA, JOB_RIG_REVIEW_ACT_SCHEMA, jobRawActMediaType, jobStillByteLimit,
5
+ type JobAct, type JobAgentRequest } from './job-contract.ts';
6
+ import { assertJobApiSchema, jobFailure, jobHash, jobId, jobObject, parseJobRequest } from './job-api.ts';
4
7
  import { JobError } from './job-store.ts';
8
+ import {validatePngBytes} from './comment-crops.ts';
9
+ import {destinationDirectory} from './destination-directory.ts';
5
10
 
6
11
  export interface JobCLIOptions {
7
12
  readonly agentCapability?: string;
@@ -13,6 +18,11 @@ export interface JobCLIOptions {
13
18
  readonly fetch?: typeof fetch;
14
19
  readonly signal?: AbortSignal;
15
20
  readonly write?: (text: string) => void;
21
+ /** Trusted in-process consumer adapter only. Production consumers pipe the same grant on stdin. */
22
+ readonly consumerCapability?: string;
23
+ readonly consumerInput?: ReadableStream<Uint8Array>;
24
+ /** Checked partial writes for consumer stdout and disposable output-fault controls. */
25
+ readonly writeBytes?: (bytes: Uint8Array) => number;
16
26
  }
17
27
 
18
28
  const commonFlags = ['generation', 'key', 'request-id'];
@@ -52,15 +62,9 @@ function semanticJSON(value: string): unknown {
52
62
  export function parseJobCLI(args: readonly string[]): { readonly endpoint: string; readonly request: JobAgentRequest } {
53
63
  const [verb, locator, ...rest] = args;
54
64
  if (!verbFlags[verb]) throw new JobError('JOB_REQUEST_INVALID');
55
- let url: URL;
56
- try { url = new URL(locator); }
57
- catch { throw new JobError('JOB_REQUEST_INVALID'); }
58
- const match = /^\/jobs\/([A-Za-z0-9][A-Za-z0-9._-]*)\/?$/.exec(url.pathname);
59
- if (url.protocol !== 'http:' || url.hostname !== '127.0.0.1' || url.username || url.password || url.search || url.hash || !match) {
60
- throw new JobError('JOB_LOOPBACK_REQUIRED');
61
- }
65
+ const {url, job} = jobLocator(locator);
62
66
  const values = flags(rest, verbFlags[verb]);
63
- const base = { schema: JOB_API_SCHEMA, verb, jobId: match[1], requestId: values.get('request-id') ?? randomUUID() };
67
+ const base = { schema: JOB_API_SCHEMA, verb, jobId: job, requestId: values.get('request-id') ?? randomUUID() };
64
68
  let payload: unknown;
65
69
  if (verb === 'next') {
66
70
  payload = { ...base, after: values.get('after') ?? null, waitMs: Number(values.get('wait-ms') ?? '0') };
@@ -85,10 +89,202 @@ export function parseJobCLI(args: readonly string[]): { readonly endpoint: strin
85
89
  }
86
90
  const request = parseJobRequest(payload);
87
91
  if (request.verb === 'fetch-act') throw new JobError('JOB_AUTHORITY_REFUSED');
88
- return { endpoint: `${url.origin}/jobs/${match[1]}/api`, request };
92
+ return { endpoint: `${url.origin}/jobs/${job}/api`, request };
93
+ }
94
+
95
+ function jobLocator(locator: string): {url: URL; job: string} {
96
+ let url: URL;
97
+ try { url = new URL(locator); }
98
+ catch { throw new JobError('JOB_REQUEST_INVALID'); }
99
+ const match = /^\/jobs\/([A-Za-z0-9][A-Za-z0-9._-]*)\/?$/.exec(url.pathname);
100
+ if (url.protocol !== 'http:' || url.hostname !== '127.0.0.1' || url.username || url.password || url.search || url.hash || !match) {
101
+ throw new JobError('JOB_LOOPBACK_REQUIRED');
102
+ }
103
+ return {url, job: match[1]};
104
+ }
105
+
106
+ async function consumerBytes(stream: ReadableStream<Uint8Array> | null, maximum: number, signal?: AbortSignal): Promise<Buffer> {
107
+ if (!stream) throw new JobError('JOB_REQUEST_INVALID');
108
+ const reader = stream.getReader();
109
+ let timer: ReturnType<typeof setTimeout> | undefined;
110
+ let abort: (() => void) | undefined;
111
+ const interrupted = new Promise<never>((_resolve, reject) => {
112
+ abort = () => reject(new JobError('JOB_REQUEST_INVALID'));
113
+ timer = setTimeout(abort, 10_000);
114
+ signal?.addEventListener('abort', abort, {once: true});
115
+ if (signal?.aborted) abort();
116
+ });
117
+ try {
118
+ const chunks: Uint8Array[] = [];
119
+ let length = 0;
120
+ for (;;) {
121
+ const {done, value} = await Promise.race([reader.read(), interrupted]);
122
+ if (done) break;
123
+ length += value.byteLength;
124
+ if (length > maximum) throw new JobError('JOB_BODY_LIMIT');
125
+ chunks.push(value);
126
+ }
127
+ return Buffer.concat(chunks, length);
128
+ } catch (error) {
129
+ void reader.cancel().catch(() => {});
130
+ if (error instanceof JobError) throw error;
131
+ throw new JobError('JOB_REQUEST_INVALID');
132
+ } finally {
133
+ clearTimeout(timer);
134
+ if (abort) signal?.removeEventListener('abort', abort);
135
+ reader.releaseLock();
136
+ }
137
+ }
138
+
139
+ function parseConsumerAct(bytes: Buffer, job: string, actId: string): JobAct {
140
+ let value: unknown;
141
+ try { value = JSON.parse(new TextDecoder('utf-8', {fatal: true}).decode(bytes)); }
142
+ catch { throw new JobError('JOB_REQUEST_INVALID'); }
143
+ const act = jobObject(value, ['schema', 'actId', 'jobId', 'askId', 'publicationId', 'kind', 'authority', 'at', 'source', 'value', 'still']);
144
+ if (act.jobId !== job || act.actId !== actId || (act.schema !== JOB_ACT_SCHEMA && act.schema !== JOB_RIG_REVIEW_ACT_SCHEMA)) {
145
+ throw new JobError('JOB_ACT_INVALID');
146
+ }
147
+ if (act.schema === JOB_RIG_REVIEW_ACT_SCHEMA) {
148
+ if (act.kind !== 'review-verdict' || (act.value as {stage?: unknown})?.stage !== 'rig-review') throw new JobError('JOB_ACT_INVALID');
149
+ const still = jobObject(act.still, ['path', 'sha256', 'camera', 'frame', 'animation']);
150
+ if (typeof still.sha256 !== 'string' || !/^[a-f0-9]{64}$/.test(still.sha256) ||
151
+ still.path !== still.sha256 + '.png' || still.camera !== 'fixed' ||
152
+ (still.frame === 'setup' ? still.animation !== undefined :
153
+ typeof still.frame !== 'number' || !Number.isFinite(still.frame) || still.frame < 0 ||
154
+ typeof still.animation !== 'string' || !still.animation)) throw new JobError('JOB_ACT_INVALID');
155
+ } else if (act.still !== undefined) throw new JobError('JOB_ACT_INVALID');
156
+ return act as unknown as JobAct;
157
+ }
158
+
159
+ function unlinkOwned(path: string, identity: {dev: number; ino: number}): void {
160
+ try {
161
+ const info = lstatSync(path);
162
+ if (info.dev === identity.dev && info.ino === identity.ino) unlinkSync(path);
163
+ } catch (error) {
164
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw new JobError('JOB_STILL_OUTPUT_FAILED');
165
+ }
166
+ }
167
+
168
+ function outputConsumerAct(actBytes: Buffer, png: Buffer | undefined, act: JobAct, destination: string | undefined, options: JobCLIOptions): void {
169
+ let temporary: string | undefined;
170
+ let temporaryIdentity: {dev: number; ino: number} | undefined;
171
+ let installed: string | undefined;
172
+ let installedIdentity: {dev: number; ino: number} | undefined;
173
+ let lock: string | undefined;
174
+ let lockDescriptor: number | undefined;
175
+ let emitted = 0;
176
+ try {
177
+ if (png && destination && act.schema === JOB_RIG_REVIEW_ACT_SCHEMA) {
178
+ const directory = destinationDirectory(destination, 'JOB_STILL_OUTPUT_FAILED', false);
179
+ lock = join(directory, '.rig-review-still.lock');
180
+ lockDescriptor = openSync(lock, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600);
181
+ const target = join(directory, act.still.path);
182
+ let existing = false;
183
+ try {
184
+ const descriptor = openSync(target, constants.O_RDONLY | constants.O_NOFOLLOW);
185
+ try {
186
+ const info = fstatSync(descriptor);
187
+ if (!info.isFile() || info.size > jobStillByteLimit || jobHash(readFileSync(descriptor)) !== act.still.sha256) {
188
+ throw new JobError('JOB_STILL_OUTPUT_FAILED');
189
+ }
190
+ existing = true;
191
+ } finally { closeSync(descriptor); }
192
+ } catch (error) {
193
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
194
+ }
195
+ if (!existing) {
196
+ temporary = join(directory, '.rig-review-still-' + randomUUID() + '.tmp');
197
+ const descriptor = openSync(temporary, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600);
198
+ try {
199
+ const owned = fstatSync(descriptor);
200
+ temporaryIdentity = {dev: owned.dev, ino: owned.ino};
201
+ let offset = 0;
202
+ while (offset < png.byteLength) {
203
+ const written = writeSync(descriptor, png, offset, png.byteLength - offset);
204
+ if (written <= 0) throw new JobError('JOB_STILL_OUTPUT_FAILED');
205
+ offset += written;
206
+ }
207
+ fsyncSync(descriptor);
208
+ const info = fstatSync(descriptor);
209
+ installedIdentity = {dev: info.dev, ino: info.ino};
210
+ } finally { closeSync(descriptor); }
211
+ renameSync(temporary, target);
212
+ temporary = undefined;
213
+ installed = target;
214
+ }
215
+ }
216
+ if (options.write && !options.writeBytes) {
217
+ // A legacy callback cannot report partial progress, so preserve an installed PNG on a thrown write.
218
+ emitted = actBytes.byteLength;
219
+ options.write(actBytes.toString('utf8'));
220
+ } else {
221
+ const write = options.writeBytes ?? (bytes => writeSync(1, bytes));
222
+ while (emitted < actBytes.byteLength) {
223
+ const written = write(actBytes.subarray(emitted));
224
+ if (!Number.isSafeInteger(written) || written <= 0 || written > actBytes.byteLength - emitted) throw new JobError('JOB_STILL_OUTPUT_FAILED');
225
+ emitted += written;
226
+ }
227
+ }
228
+ } catch {
229
+ if (emitted === 0 && installed && installedIdentity) {
230
+ unlinkOwned(installed, installedIdentity);
231
+ }
232
+ throw new JobError('JOB_STILL_OUTPUT_FAILED');
233
+ } finally {
234
+ if (temporary && temporaryIdentity) unlinkOwned(temporary, temporaryIdentity);
235
+ if (lockDescriptor !== undefined) {
236
+ const owned = fstatSync(lockDescriptor);
237
+ closeSync(lockDescriptor);
238
+ unlinkOwned(lock!, owned);
239
+ }
240
+ }
241
+ }
242
+
243
+ async function fetchActCommand(args: readonly string[], options: JobCLIOptions): Promise<void> {
244
+ const {url, job} = jobLocator(args[1]);
245
+ const rest = args.slice(2);
246
+ const stdinFlags = rest.filter(value => value === '--consumer-capability-stdin').length;
247
+ if (stdinFlags > 1 || (stdinFlags === 0 && !options.consumerCapability) || (stdinFlags && options.consumerCapability)) throw new JobError('JOB_REQUEST_INVALID');
248
+ const values = flags(rest.filter(value => value !== '--consumer-capability-stdin'), ['act', 'still-out', 'request-id']);
249
+ const actId = jobId(required(values, 'act'));
250
+ const input = options.consumerCapability ?? (await consumerBytes(options.consumerInput ?? Bun.stdin.stream(), 4096, options.signal)).toString('utf8');
251
+ const capability = input.replace(/\r?\n$/, '');
252
+ if (!/^[a-f0-9]{64}$/.test(capability)) throw new JobError('JOB_CAPABILITY_REQUIRED');
253
+ const request = {schema: JOB_API_SCHEMA, verb: 'fetch-act', jobId: job, actId, requestId: values.get('request-id') ?? randomUUID()};
254
+ async function read(accept: string, maximum: number): Promise<Buffer> {
255
+ const response = await (options.fetch ?? fetch)(`${url.origin}/jobs/${job}/api`, {
256
+ method: 'POST', redirect: 'error', signal: options.signal,
257
+ headers: {'Content-Type': 'application/json', Authorization: 'Bearer ' + capability, Accept: accept},
258
+ body: JSON.stringify(request),
259
+ });
260
+ const bytes = await consumerBytes(response.body, maximum, options.signal);
261
+ if (!response.ok) {
262
+ let failure: unknown;
263
+ try { failure = JSON.parse(bytes.toString('utf8')); } catch {}
264
+ const code = (failure as {error?: {code?: unknown}})?.error?.code;
265
+ throw new JobError('JOB_REQUEST_INVALID', typeof code === 'string' && /^JOB_[A-Z_]+$/.test(code) ? code : 'JOB_REQUEST_INVALID');
266
+ }
267
+ if (response.headers.get('content-type')?.split(';')[0] !== accept) throw new JobError('JOB_REQUEST_INVALID');
268
+ return bytes;
269
+ }
270
+ const bytes = await read(jobRawActMediaType, 512 * 1024);
271
+ const act = parseConsumerAct(bytes, job, actId);
272
+ const destination = values.get('still-out');
273
+ if (act.schema === JOB_RIG_REVIEW_ACT_SCHEMA && destination === undefined) throw new JobError('JOB_STILL_OUTPUT_FAILED');
274
+ let png: Buffer | undefined;
275
+ if (destination !== undefined) {
276
+ if (act.schema !== JOB_RIG_REVIEW_ACT_SCHEMA) throw new JobError('JOB_STILL_UNAVAILABLE');
277
+ png = await read('image/png', jobStillByteLimit);
278
+ try {
279
+ if (png.length < 33 || jobHash(png) !== act.still.sha256) throw new Error('hash');
280
+ validatePngBytes(png, png.readUInt32BE(16), png.readUInt32BE(20));
281
+ } catch { throw new JobError('JOB_STILL_CAPTURE_FAILED'); }
282
+ }
283
+ outputConsumerAct(bytes, png, act, destination, options);
89
284
  }
90
285
 
91
286
  export async function jobCommand(args: readonly string[], options: JobCLIOptions = {}): Promise<void> {
287
+ if (args[0] === 'fetch-act') return fetchActCommand(args, options);
92
288
  const write = options.write ?? (text => console.log(text));
93
289
  if (args[0] === 'open') {
94
290
  if (args.length !== 2 || !options.open) throw new JobError('JOB_AUTHORITY_REFUSED', 'Managed job opening requires the Review host');
@@ -13,6 +13,11 @@
13
13
 
14
14
  export const JOB_API_SCHEMA = 'rig-review/job-api@2' as const;
15
15
  export const JOB_ACT_SCHEMA = 'rig-review/act@2' as const;
16
+ /** New rig verdicts only. Store/reuse markers and all other acts retain @2. */
17
+ export const JOB_RIG_REVIEW_ACT_SCHEMA = 'rig-review/act@3' as const;
18
+ export const jobStillByteLimit = 8 * 1024 * 1024;
19
+ export const jobCaptureBodyLimit = 12 * 1024 * 1024;
20
+ export const jobRawActMediaType = 'application/vnd.rig-review.act+json';
16
21
  export const JOB_PARTS_ENUMERATOR_RANGE = '>=2.25.0 <3.0.0' as const;
17
22
 
18
23
  export const JOB_ENABLED_ACT_KINDS = [
@@ -284,7 +289,7 @@ export interface JobActSources {
284
289
  * Checkpoint stage is derived by Create. Plan-bound signoff requirements apply
285
290
  * to every stage in JOB_PLAN_BOUND_SIGNOFF_STAGES before act creation.
286
291
  */
287
- export type JobAct = {
292
+ export type JobLegacyAct = {
288
293
  [Kind in JobEnabledActKind]: {
289
294
  readonly schema: typeof JOB_ACT_SCHEMA;
290
295
  readonly actId: JobActId;
@@ -300,6 +305,50 @@ export type JobAct = {
300
305
  ) : {readonly source: JobActSources[Kind]; readonly value: JobActValues[Kind]});
301
306
  }[JobEnabledActKind];
302
307
 
308
+ export type JobRigStill = {
309
+ readonly path: string;
310
+ readonly sha256: JobSha256;
311
+ readonly camera: 'fixed';
312
+ } & (
313
+ | {readonly frame: 'setup'; readonly animation?: never}
314
+ | {readonly frame: number; readonly animation: string}
315
+ );
316
+
317
+ export type JobRigReviewAct = Omit<Extract<JobLegacyAct, {kind: 'review-verdict'}>, 'schema' | 'source' | 'value'> & {
318
+ readonly schema: typeof JOB_RIG_REVIEW_ACT_SCHEMA;
319
+ readonly source: JobModelSourceBinding & {
320
+ readonly selector: Extract<JobSelector, {kind: 'rig'}>;
321
+ readonly model: JobFileIdentity;
322
+ };
323
+ readonly value: JobModelReviewValue & {readonly stage: 'rig-review'};
324
+ readonly still: JobRigStill;
325
+ };
326
+
327
+ /** Historical @2 rig acts remain readable without being backfilled or relabelled. */
328
+ export type JobAct = JobLegacyAct | JobRigReviewAct;
329
+
330
+ /** Authenticated browser provenance. The daemon validates identity and hashes PNG bytes. */
331
+ export interface JobRigCapture {
332
+ readonly png: string;
333
+ readonly width: number;
334
+ readonly height: number;
335
+ readonly camera: 'fixed';
336
+ readonly framing: 'default';
337
+ readonly view: 'whole-rig';
338
+ readonly frame: 'setup' | number;
339
+ readonly animation?: string;
340
+ readonly playing: boolean;
341
+ readonly binding: {
342
+ readonly publicationId: JobPublicationId;
343
+ readonly instanceKey: string;
344
+ readonly sourceHash: JobSha256;
345
+ readonly pageId: string;
346
+ readonly askId: JobAskId;
347
+ readonly drawGeneration: number;
348
+ readonly playerGeneration: number;
349
+ };
350
+ }
351
+
303
352
  export type JobSubject =
304
353
  | { readonly kind: 'interview-picks'; readonly questionId: string; readonly setId: string }
305
354
  | {
@@ -435,6 +484,12 @@ export const JOB_ERROR_CODES = [
435
484
  'JOB_ACT_KIND_DISABLED',
436
485
  'JOB_ACT_SOURCE_STALE',
437
486
  'JOB_DISPLAY_MISMATCH',
487
+ 'JOB_STILL_CAPTURE_FAILED',
488
+ 'JOB_STILL_CAMERA_NOT_FIXED',
489
+ 'JOB_STILL_VIEW_UNSUPPORTED',
490
+ 'JOB_STILL_BINDING_MISMATCH',
491
+ 'JOB_STILL_UNAVAILABLE',
492
+ 'JOB_STILL_OUTPUT_FAILED',
438
493
  'JOB_CURSOR_INVALID',
439
494
  'JOB_STORAGE_FAILED',
440
495
  'JOB_AGENT_ISOLATION_HOLE',
@@ -502,6 +557,7 @@ export type JobUISubmission = {
502
557
  readonly submissionId: string;
503
558
  readonly kind: Kind;
504
559
  readonly value: JobUIActValues[Kind];
560
+ readonly capture?: Kind extends 'review-verdict' ? JobRigCapture : never;
505
561
  };
506
562
  }[JobEnabledActKind];
507
563
 
package/src/job-host.ts CHANGED
@@ -47,6 +47,10 @@ export type {
47
47
  JobUIActValues,
48
48
  JobActSources,
49
49
  JobAct,
50
+ JobLegacyAct,
51
+ JobRigReviewAct,
52
+ JobRigStill,
53
+ JobRigCapture,
50
54
  JobSubject,
51
55
  JobPendingAsk,
52
56
  JobPublication,
@@ -1,11 +1,11 @@
1
1
  import { randomBytes, randomUUID } from 'node:crypto';
2
2
  import { isAbsolute, relative, sep } from 'node:path';
3
3
  import {
4
- JOB_API_SCHEMA, JOB_ACT_SCHEMA, JOB_CAPABILITIES, JOB_ENABLED_ACT_KINDS, type JobPartsEnumerator, type JobAct, type JobAgentRequest, type JobDisplayAcknowledgment,
4
+ JOB_API_SCHEMA, JOB_ACT_SCHEMA, JOB_RIG_REVIEW_ACT_SCHEMA, jobStillByteLimit, JOB_CAPABILITIES, JOB_ENABLED_ACT_KINDS, type JobPartsEnumerator, type JobAct, type JobAgentRequest, type JobDisplayAcknowledgment,
5
5
  type JobDisplayPublication, type JobDisplayReceipt, type JobEvent, type JobFetchActRequest,
6
6
  type JobNextValue, type JobPendingAsk, type JobPublication, type JobReviewerBinding, type JobStatus,
7
7
  } from './job-contract.ts';
8
- import { bindJobAsk, finalizeJobAct, parseUISubmission } from './job-act.ts';
8
+ import { bindJobAsk, finalizeJobAct, parseUISubmission, prepareJobStill } from './job-act.ts';
9
9
  import { jobHash, jobPartsEnumeratorVersion, jobWaitLimitMs, requestDigest, sameCapability } from './job-api.ts';
10
10
  import {
11
11
  assertJobRoot, assertJobSourceCurrent, captureJobRoot, prepareJobSource, jobSnapshotHash, removeOwnedJobSnapshot,
@@ -397,6 +397,26 @@ export class JobSession {
397
397
  }
398
398
  }
399
399
 
400
+ /** Bounded immutable bytes selected only through the authenticated consumer port. */
401
+ readActExport(actId: string, png: boolean): Buffer {
402
+ const current = this.current();
403
+ if (!current.active) throw new JobError('JOB_CLOSED');
404
+ const act = current.data.acts[actId];
405
+ if (!act) throw new JobError('JOB_ACT_UNKNOWN');
406
+ if (act.schema !== JOB_RIG_REVIEW_ACT_SCHEMA) {
407
+ if (png) throw new JobError('JOB_STILL_UNAVAILABLE');
408
+ return Buffer.from(JSON.stringify(act));
409
+ }
410
+ const stored = this.store.readStill(this.jobId, actId);
411
+ if (!stored || stored.png.byteLength > jobStillByteLimit || stored.actBytes.byteLength > maximumEventBytes ||
412
+ stored.sha256 !== act.still.sha256 || jobHash(stored.png) !== act.still.sha256 ||
413
+ act.still.path !== act.still.sha256 + '.png' ||
414
+ !Buffer.from(stored.actBytes).equals(Buffer.from(JSON.stringify(act)))) {
415
+ throw new JobError('JOB_STILL_CAPTURE_FAILED');
416
+ }
417
+ return Buffer.from(png ? stored.png : stored.actBytes);
418
+ }
419
+
400
420
  ackDisplayed(input: JobDisplayAcknowledgment): JobDisplayReceipt {
401
421
  const current = this.current();
402
422
  let receipt: JobDisplayReceipt;
@@ -434,13 +454,20 @@ export class JobSession {
434
454
  if (!ask) throw new JobError('JOB_ASK_INVALID');
435
455
  const retained = fresh.data.publications[input.publicationId].retained;
436
456
  assertJobSourceCurrent(retained);
437
- act = finalizeJobAct({ jobId: this.jobId, submission: input, ask, retained, reviewer: fresh.data.reviewer });
457
+ const captured = ask.subject.kind === 'review-verdict' && ask.subject.stage === 'rig-review' ?
458
+ prepareJobStill(input, ask, retained) : undefined;
459
+ act = finalizeJobAct({ jobId: this.jobId, submission: input, ask, retained, reviewer: fresh.data.reviewer,
460
+ still: captured?.still });
438
461
  fresh.data.generation++;
439
462
  fresh.data.acts[act.actId] = act;
440
463
  fresh.data.asks[ask.askId] = { ...ask, status: 'answered' };
441
464
  fresh.data.replays[key] = { digest, value: act };
442
465
  this.event(fresh.data, { type: 'act', act } as Omit<JobEvent, 'cursor' | 'jobId' | 'generation'>);
443
- return { data: fresh.data };
466
+ return { data: fresh.data, ...(captured ? {still: {
467
+ actId: act.actId, pageId: input.pageId, submissionId: input.submissionId,
468
+ sha256: captured.still.sha256, binding: JSON.stringify(captured.binding),
469
+ png: captured.bytes, actBytes: Buffer.from(JSON.stringify(act)),
470
+ }} : {}) };
444
471
  }, fresh => {
445
472
  const raced = this.replay(fresh.data, key, digest);
446
473
  if (!raced) return false;
package/src/job-source.ts CHANGED
@@ -323,7 +323,12 @@ export async function prepareJobSource(options: {
323
323
  if (jobHash(bytes) !== record.sha256) throw new JobError('JOB_RECORD_MOVED');
324
324
  try { JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)); }
325
325
  catch { throw new JobError('JOB_RECORD_INCOMPLETE'); }
326
- if (record.path === 'project.json') project = readProject(root.path);
326
+ if (record.path === 'project.json') {
327
+ project = readProject(root.path);
328
+ // #555 owns API@2 diagnostic carriage. Refuse before publication lookup
329
+ // or snapshot writes when this reader's retained records need it.
330
+ if (project.sceneAnswers || project.diagnostics.length) throw new JobError('JOB_RECORD_INCOMPLETE');
331
+ }
327
332
  } else {
328
333
  try { lstatSync(join(root.path, 'project.json')); throw new JobError('JOB_FREEZE_REQUIRED'); }
329
334
  catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; }
package/src/job-store.ts CHANGED
@@ -42,6 +42,16 @@ export interface JobSnapshotTombstone {
42
42
  readonly reason: 'closed' | 'superseded';
43
43
  }
44
44
 
45
+ export interface JobStoredStill {
46
+ readonly actId: string;
47
+ readonly pageId: string;
48
+ readonly submissionId: string;
49
+ readonly sha256: string;
50
+ readonly binding: string;
51
+ readonly png: Uint8Array;
52
+ readonly actBytes: Uint8Array;
53
+ }
54
+
45
55
  interface JobRow {
46
56
  job_id: string;
47
57
  root_key: string;
@@ -143,6 +153,11 @@ export class JobStore<Data> {
143
153
  job_id TEXT NOT NULL, publication_id TEXT NOT NULL, snapshot_hash TEXT NOT NULL,
144
154
  reclaimed_at TEXT NOT NULL, reason TEXT NOT NULL CHECK(reason IN ('closed','superseded')),
145
155
  PRIMARY KEY(job_id, publication_id)
156
+ );
157
+ CREATE TABLE IF NOT EXISTS job_act_stills (
158
+ job_id TEXT NOT NULL, act_id TEXT NOT NULL, page_id TEXT NOT NULL, submission_id TEXT NOT NULL,
159
+ sha256 TEXT NOT NULL, binding TEXT NOT NULL, png BLOB NOT NULL, act_bytes BLOB NOT NULL,
160
+ PRIMARY KEY(job_id, act_id), UNIQUE(job_id, page_id, submission_id)
146
161
  );`);
147
162
  } catch {
148
163
  throw new JobError('JOB_STORAGE_FAILED', 'Private job storage could not be opened');
@@ -207,6 +222,7 @@ export class JobStore<Data> {
207
222
  readonly data: Data;
208
223
  readonly active?: boolean;
209
224
  readonly snapshot?: JobSnapshotOwner;
225
+ readonly still?: JobStoredStill;
210
226
  }, replay?: (current: StoredJob<Data>) => boolean): StoredJob<Data> {
211
227
  return this.transaction(() => {
212
228
  const current = this.get(jobId);
@@ -221,12 +237,24 @@ export class JobStore<Data> {
221
237
  (job_id,publication_id,snapshot_hash,snapshot_root,dev,ino) VALUES(?,?,?,?,?,?)`)
222
238
  .run(jobId, snapshot.publicationId, snapshot.snapshotHash, snapshot.snapshotRoot, snapshot.dev, snapshot.ino);
223
239
  }
240
+ if (next.still) {
241
+ const still = next.still;
242
+ this.db.query(`INSERT INTO job_act_stills
243
+ (job_id,act_id,page_id,submission_id,sha256,binding,png,act_bytes) VALUES(?,?,?,?,?,?,?,?)`)
244
+ .run(jobId, still.actId, still.pageId, still.submissionId, still.sha256, still.binding, still.png, still.actBytes);
245
+ }
224
246
  this.db.query('UPDATE jobs SET revision=?,active=?,document=? WHERE job_id=?')
225
247
  .run(current.revision + 1, active ? 1 : 0, document, jobId);
226
248
  return this.get(jobId);
227
249
  });
228
250
  }
229
251
 
252
+ readStill(jobId: string, actId: string): Pick<JobStoredStill, 'sha256' | 'png' | 'actBytes'> | null {
253
+ return this.db.query<{sha256: string; png: Uint8Array; actBytes: Uint8Array}, [string, string]>(
254
+ 'SELECT sha256,png,act_bytes AS actBytes FROM job_act_stills WHERE job_id=? AND act_id=?',
255
+ ).get(jobId, actId);
256
+ }
257
+
230
258
  /** Close never grows or rewrites the bounded historical document. */
231
259
  sealClose(jobId: string, expectedRevision: number,
232
260
  replay: (current: StoredJob<Data>) => Pick<JobClosure, 'replay'> | null,
package/web/catalog-en.ts CHANGED
@@ -1,4 +1,10 @@
1
1
  export const enCatalog: Readonly<Record<string, string>> = {
2
+ "JOB_STILL_CAPTURE_FAILED": "JOB_STILL_CAPTURE_FAILED · The displayed Rig frame could not be captured. Wait for a successful draw and try again.",
3
+ "JOB_STILL_CAMERA_NOT_FIXED": "JOB_STILL_CAMERA_NOT_FIXED · Restore the default Rig framing before submitting this verdict.",
4
+ "JOB_STILL_VIEW_UNSUPPORTED": "JOB_STILL_VIEW_UNSUPPORTED · Show the whole Rig without solo, highlight or comparison layers before submitting.",
5
+ "JOB_STILL_BINDING_MISMATCH": "JOB_STILL_BINDING_MISMATCH · The displayed source, page or drawn frame changed. Start a new verdict attempt.",
6
+ "JOB_STILL_UNAVAILABLE": "JOB_STILL_UNAVAILABLE · This historical or non-rig act has no retained Rig PNG.",
7
+ "JOB_STILL_OUTPUT_FAILED": "JOB_STILL_OUTPUT_FAILED · The consumer could not finish writing the Rig PNG or act output.",
2
8
  "WORKSPACE_BODY_TIMEOUT": "WORKSPACE_BODY_TIMEOUT",
3
9
  "rig-review-target/1": "rig-review-target/1",
4
10
  "Review workspace": "Review workspace",
@@ -45,7 +51,9 @@ export const enCatalog: Readonly<Record<string, string>> = {
45
51
  "DIRECTION_VERSION_UNAVAILABLE: this draft has no recorded rig review package.": "DIRECTION_VERSION_UNAVAILABLE: this draft has no recorded rig review package.",
46
52
  "PARTS_VERDICT_READ_ONLY: a pending parts review and an explicit verdict output directory are required.": "PARTS_VERDICT_READ_ONLY: a pending parts review and an explicit verdict output directory are required.",
47
53
  "INTERVIEW_OPTIONS_STALE": "INTERVIEW_OPTIONS_STALE: Project or source changed. Reopen the inspection.",
48
- "INTERVIEW_CONTEXT_KIND_UNSUPPORTED": "INTERVIEW_CONTEXT_KIND_UNSUPPORTED: The scene option context is unsupported.",
54
+ "INTERVIEW_CONTEXT_KIND_UNSUPPORTED": "INTERVIEW_CONTEXT_KIND_UNSUPPORTED: This option context kind is unsupported.",
55
+ "INTERVIEW_OPTIONS_SCENE_LEGACY": "INTERVIEW_OPTIONS_SCENE_LEGACY: This earlier scene context remains readable. Redraft against the current context before new work.",
56
+ "interview.historicalIssue": "INTERVIEW_OPTIONS_STALE: The context of this historical record could not be validated.",
49
57
  "interview.joinedDraft": "Draft {0} · project {1} · source {2}",
50
58
  "interview.joined": "Create version {0} · project SHA-256 {1} · inspection SHA-256 {2}",
51
59
  "interview.mismatch": "INTERVIEW_SOURCE_MISMATCH: The inspection does not match the designated Create package.",
package/web/catalog-ko.ts CHANGED
@@ -1,4 +1,10 @@
1
1
  export const koCatalog: Readonly<Record<string, string>> = {
2
+ "JOB_STILL_CAPTURE_FAILED": "JOB_STILL_CAPTURE_FAILED · 표시된 리그 프레임을 캡처하지 못했습니다. 정상적으로 그려진 뒤 다시 시도하세요.",
3
+ "JOB_STILL_CAMERA_NOT_FIXED": "JOB_STILL_CAMERA_NOT_FIXED · 판정을 제출하기 전에 리그를 기본 화면 구도로 되돌리세요.",
4
+ "JOB_STILL_VIEW_UNSUPPORTED": "JOB_STILL_VIEW_UNSUPPORTED · 단독 표시·강조·비교 레이어를 해제하고 전체 리그를 표시한 뒤 제출하세요.",
5
+ "JOB_STILL_BINDING_MISMATCH": "JOB_STILL_BINDING_MISMATCH · 표시된 소스·페이지·그려진 프레임이 바뀌었습니다. 새 판정 시도를 시작하세요.",
6
+ "JOB_STILL_UNAVAILABLE": "JOB_STILL_UNAVAILABLE · 이 과거 기록 또는 리그 외 판정에는 보관된 리그 PNG가 없습니다.",
7
+ "JOB_STILL_OUTPUT_FAILED": "JOB_STILL_OUTPUT_FAILED · 소비자가 리그 PNG 또는 판정 출력을 끝까지 기록하지 못했습니다.",
2
8
  "WORKSPACE_BODY_TIMEOUT": "WORKSPACE_BODY_TIMEOUT",
3
9
  "rig-review-target/1": "rig-review-target/1",
4
10
  "Review workspace": "검토 작업 공간",
@@ -45,7 +51,9 @@ export const koCatalog: Readonly<Record<string, string>> = {
45
51
  "DIRECTION_VERSION_UNAVAILABLE: this draft has no recorded rig review package.": "DIRECTION_VERSION_UNAVAILABLE: 이 초안에는 기록된 리그 검토 패키지가 없습니다.",
46
52
  "PARTS_VERDICT_READ_ONLY: a pending parts review and an explicit verdict output directory are required.": "PARTS_VERDICT_READ_ONLY: 대기 중인 파츠 검토와 명시적으로 지정한 판정 출력 디렉터리가 필요합니다.",
47
53
  "INTERVIEW_OPTIONS_STALE": "INTERVIEW_OPTIONS_STALE: 프로젝트 또는 원본이 바뀌었어요. 검토를 다시 여세요.",
48
- "INTERVIEW_CONTEXT_KIND_UNSUPPORTED": "INTERVIEW_CONTEXT_KIND_UNSUPPORTED: scene 선택지 문맥은 지원하지 않습니다.",
54
+ "INTERVIEW_CONTEXT_KIND_UNSUPPORTED": "INTERVIEW_CONTEXT_KIND_UNSUPPORTED: 지원하지 않는 선택지 문맥 유형입니다.",
55
+ "INTERVIEW_OPTIONS_SCENE_LEGACY": "INTERVIEW_OPTIONS_SCENE_LEGACY: 이전 규칙의 장면 문맥을 읽었습니다. 새 작업 전에 현재 문맥으로 선택지를 다시 준비하세요.",
56
+ "interview.historicalIssue": "INTERVIEW_OPTIONS_STALE: 이 과거 기록의 문맥을 검증할 수 없습니다.",
49
57
  "interview.joinedDraft": "초안 {0} · 프로젝트 {1} · 원본 {2}",
50
58
  "interview.joined": "Create 버전 {0} · 프로젝트 SHA-256 {1} · 검토 SHA-256 {2}",
51
59
  "interview.mismatch": "INTERVIEW_SOURCE_MISMATCH: 검토 대상이 지정한 Create 패키지와 일치하지 않아요.",