@rig-c/review 2.5.0 → 2.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/docs/WORKFLOWS.md CHANGED
@@ -609,13 +609,14 @@ bound has no hardware performance guarantee. Hidden hub members suspend their ev
609
609
 
610
610
  The active Create and Parts inspection cycle uses the semantic job contract in `src/job-contract.ts` (`JOB_API_SCHEMA` set to `rig-review/job-api@2`, `JOB_ACT_SCHEMA` set to `rig-review/act@2`, [Review #484](https://github.com/rig-c/review/issues/484)) together with the implemented backend session/store (`src/job-session.ts`, `src/job-source.ts`, `src/job-act.ts`, `src/job-api.ts`), loopback job front and browser window runtime (`src/job-front.ts`, `web/job-session.ts`), and `rig-review session` CLI (`src/entry.ts`, `src/job-cli.ts`). The public installed managed-host entry is `@rig-c/review/job-host` with frozen exports in [Public API stability](STABILITY.md#managed-owner-host), and Create's production publication reader and writer-owned sibling `fetch-act` readback remain pending [Create #184](https://github.com/rig-c/create/issues/184) (publishing a Create root containing `project.json` without a host `readPublished` callback refuses `JOB_SOURCE_UNRETAINABLE` with `CREATE_PUBLICATION_CONTRACT_UNAVAILABLE`). See [Live job contract](REVIEW_PACKAGE.md#live-job-contract) for the full schema and host seam reference.
611
611
 
612
- Exact CLI usage from `src/entry.ts` and `src/job-cli.ts` (`publish`, `ask`, `next` and `close` also accept optional `--request-id <id>`):
612
+ CLI usage (`publish`, `ask`, `next` and `close` also accept optional `--request-id <id>`).
613
613
 
614
614
  ```text
615
615
  Usage: rig-review session open <root>
616
616
  rig-review session publish <job-url> --generation <n> --key <id> --result <relative-path> --freeze-hold <id> [--selector <JSON>] [--record <path> --record-hash <sha256>]
617
617
  rig-review session ask <job-url> --generation <n> --key <id> --publication <id> --subject <JSON>
618
618
  rig-review session next <job-url> [--after <cursor>] [--wait-ms <n>]
619
+ rig-review session next <job-url> [--after <cursor>] --until act --wait-ms <n>
619
620
  rig-review session close <job-url> --generation <n> --key <id> --reason <words>
620
621
  ```
621
622
 
@@ -642,6 +643,41 @@ rig-review session close http://127.0.0.1:<port>/jobs/<job-id> \
642
643
  --generation <current-generation> --key close-1 --reason "inspection complete"
643
644
  ```
644
645
 
646
+ To wait for a finalized act from another authenticated CLI process, use one call with an explicit
647
+ integer overall wait of 1 through 600000 ms.
648
+
649
+ ```text
650
+ rig-review session next <job-url> --after <accepted-cursor> --until act --wait-ms 600000
651
+ ```
652
+
653
+ `--until` accepts `act` only. Missing, zero, fractional or out-of-range opt-in waits refuse
654
+ `JOB_REQUEST_INVALID` with exit 1 before HTTP. One monotonic deadline covers requests, response-body
655
+ reads, decoding and validation. Existing server waits remain bounded to 30000 ms each and are chained
656
+ inside this call, advancing through unrelated publication and ask events. Only complete responses
657
+ validated within the deadline are accepted. Calls without `--until act` retain their existing wait,
658
+ response and exit behavior, including immediate reads and successful timeout envelopes.
659
+
660
+ Success exits 0 with the whole validated `JobApiResponse` batch containing an act. Process every row
661
+ in `value.events`, including additional acts, before persisting `value.cursor`. Act rows expose
662
+ `act.actId` and `act.kind`. Reads replay events without consuming them. For future acts, pass the last
663
+ accepted cursor. An omitted `--after` starts historical replay. Resume from the last accepted cursor
664
+ and deduplicate by `actId` after retries.
665
+
666
+ On overall expiry, stderr reports CLI-local `JOB_NEXT_TIMEOUT` and exit 3. Stdout contains the last
667
+ accepted complete response envelope, preserving its cursor and status, or stays empty if none was
668
+ accepted. Closure before an act returns the closed response with `JOB_CLOSED` and exit 1. Authentication,
669
+ cursor, storage and caller-cancellation failures retain exit 1.
670
+
671
+ The acceptance bar includes one CLI wait spanning a real finalized UI act submitted after more than
672
+ 30 seconds. Focused validation covers a synthetic normal-CLI wait (`tests/job-next-wait.test.ts`)
673
+ where one `rig-review session next ... --until act --wait-ms 40000` call chains two 30000 ms-bounded
674
+ `next` API requests across ~31 seconds and returns a finalized synthetic UI act committed after 31
675
+ seconds, alongside fast multi-slice and boundary tests; full browser and PR CI acceptance runs
676
+ separately. Standalone legacy
677
+ file-only Save has the separate [save-notification contract](PARTS_VIEW.md#durable-save-notifications).
678
+ Waking this act wait requires a real finalized job act. Consumers use writer-owned `fetch-act` for
679
+ the source-bound result and deduplicate by `actId`.
680
+
645
681
  - **One standing window and visual gate.** Every owner visual, question, choice, correction and verdict goes through one standing Review window/link plus one what-to-look-at line. Internal agent and HQ media stay internal and are never substituted for the owner handoff. When a required visual is missing (`visual.status` set to `'unavailable'` with a named `code`), the agent stops immediately and files a Create on-path Review card rather than falling back to chat text or images.
646
682
  - **Human UI vs agent verbs.** People submit through the Review browser UI (`actor` set to `'human'`, `channel` set to `'review-ui'`). Trusted host bootstrap declares `reviewer` (`id` and `role` as `'owner'` or `'delegate'`), which the browser UI cannot type or override. This binding records bootstrap-declared provenance rather than keyboard-user authentication, and Create maps `role` to its existing `by` authority. Agents use only `publish`, `ask`, `next` and `close` (`JobAgentRequest`), with `expectedGeneration` compare-and-swap (CAS) and `idempotencyKey` on mutations.
647
683
  - **Explicit producer-held freeze and explicit close.** Every `publish` request designates a root-relative `result` (`path` and `selector`, never a command) and carries an explicit producer-held freeze (`freeze.kind` set to `'producer-held'`, `holdId`, `record` as `JobFileIdentity` or `null` for a declared non-Create root) held until acknowledgment. Review validates retained bytes, detects a moved record (`JOB_RECORD_MOVED`, `JOB_RECORD_INCOMPLETE`, `JOB_FREEZE_REQUIRED`, `JOB_SOURCE_MISMATCH`, `JOB_SOURCE_UNRETAINABLE`, `JOB_ROOT_REPLACED`) and commits local generation CAS (`JOB_GENERATION_STALE`, `JOB_IDEMPOTENCY_CONFLICT`). The freeze assertion is a caller obligation rather than a lock Review can impose on independent writers. Review offers no watched-root or automatic-close guarantee, and only explicit `close` ends an active job.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rig-c/review",
3
- "version": "2.5.0",
3
+ "version": "2.7.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();
package/src/job-act.ts CHANGED
@@ -1,12 +1,21 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import {
3
- JOB_ACT_SCHEMA, JOB_RIG_REVIEW_ACT_SCHEMA, jobStillByteLimit, JOB_ENABLED_ACT_KINDS, JOB_PLAN_BOUND_SIGNOFF_STAGES, JOB_RESERVED_ACT_KINDS,
4
- type JobAct, type JobActValues, type JobPendingAsk, type JobReviewerBinding,
3
+ JOB_ACT_SCHEMA, JOB_RECORD_ACT_SCHEMA, JOB_RIG_REVIEW_ACT_SCHEMA, jobStillByteLimit, JOB_ENABLED_ACT_KINDS, JOB_PLAN_BOUND_SIGNOFF_STAGES, JOB_RESERVED_ACT_KINDS,
4
+ type ActV3, type JobAct, type JobActValues, type JobPendingAsk, type JobReviewerBinding,
5
5
  type JobSourceBinding, type JobSubject, type JobUISubmission, type JobRigCapture, type JobRigStill,
6
+ type PendingAskV3, type RecordAct, type RecordSource, type RecordSubject, type SourceV3,
6
7
  } from './job-contract.ts';
7
- import { jobHash, jobId, jobInteger, jobObject, requestDigest } from './job-api.ts';
8
+ import {
9
+ isRecordSource, jobHash, jobId, jobInteger, jobObject,
10
+ parseRecordAct, parseRecordSource, requestDigest, validateRecordAskSubject,
11
+ } from './job-api.ts';
8
12
  import { validatePicks } from './interview-picks.ts';
9
- import type { JobRetainedSource } from './job-source.ts';
13
+ import {
14
+ isRetainedRecordSource,
15
+ type JobRetainedRecordSource,
16
+ type JobRetainedSource,
17
+ type JobRetainedSourceV3,
18
+ } from './job-source.ts';
10
19
  import { JobError } from './job-store.ts';
11
20
  import { checkedPath, readRegular } from './interview-project.ts';
12
21
  import { prepareJobImageSet } from './job-image-set.ts';
@@ -26,7 +35,56 @@ function requirePlan(source: JobSourceBinding): void {
26
35
  if (!source.plan?.steps.length) throw new JobError('JOB_ASK_INVALID', 'Published plan step identities are required');
27
36
  }
28
37
 
29
- export function bindJobAsk(subject: JobSubject, retained: JobRetainedSource): JobSourceBinding {
38
+ export function bindJobRecordAsk(subject: unknown, retained: JobRetainedRecordSource): RecordSource {
39
+ const source = structuredClone(parseRecordSource(retained.source));
40
+ const parsedSubject = validateRecordAskSubject(subject, source);
41
+ if (
42
+ requestDigest(retained.subjects) !== requestDigest(source.subjects) ||
43
+ !retained.subjects.some(candidate => requestDigest(candidate) === requestDigest(parsedSubject))
44
+ ) {
45
+ throw new JobError('JOB_ASK_INVALID');
46
+ }
47
+ switch (parsedSubject.kind) {
48
+ case 'interview-picks': {
49
+ if (source.subject !== 'option-set') throw new JobError('JOB_ASK_INVALID');
50
+ const question = retained.questions.find(
51
+ item => item.editable && item.set.question === parsedSubject.questionId && item.set.id === parsedSubject.setId,
52
+ );
53
+ if (
54
+ !question ||
55
+ question.ref.path !== source.optionSetFile.path ||
56
+ question.ref.sha256 !== source.optionSet.sha256
57
+ ) {
58
+ throw new JobError('JOB_ASK_INVALID');
59
+ }
60
+ return source;
61
+ }
62
+ case 'checkpoint': {
63
+ if (
64
+ source.subject !== 'plan' ||
65
+ !source.plan.steps.length ||
66
+ !source.plan.steps.some(step => step.id === parsedSubject.checkpointId)
67
+ ) {
68
+ throw new JobError('JOB_ASK_INVALID');
69
+ }
70
+ return source;
71
+ }
72
+ case 'signoff': {
73
+ if (source.subject !== 'plan' || !source.plan.steps.length) {
74
+ throw new JobError('JOB_ASK_INVALID');
75
+ }
76
+ return source;
77
+ }
78
+ }
79
+ }
80
+
81
+ export function bindJobAsk(subject: JobSubject, retained: JobRetainedSource): JobSourceBinding;
82
+ export function bindJobAsk(subject: RecordSubject | JobSubject, retained: JobRetainedRecordSource): RecordSource;
83
+ export function bindJobAsk(subject: JobSubject | RecordSubject, retained: JobRetainedSourceV3): SourceV3;
84
+ export function bindJobAsk(subject: JobSubject | RecordSubject, retained: JobRetainedSourceV3): SourceV3 {
85
+ if (isRetainedRecordSource(retained)) {
86
+ return bindJobRecordAsk(subject, retained);
87
+ }
30
88
  const source = structuredClone(retained.source);
31
89
  if (source.subject === 'image-set') {
32
90
  if (subject.kind !== 'review-verdict' || subject.stage !== 'image-review') throw new JobError('JOB_ASK_INVALID');
@@ -47,7 +105,7 @@ export function bindJobAsk(subject: JobSubject, retained: JobRetainedSource): Jo
47
105
  }
48
106
  case 'checkpoint': {
49
107
  requirePlan(source);
50
- const stepId = subject.planStepId ?? subject.checkpointId;
108
+ const stepId = ('planStepId' in subject ? subject.planStepId : undefined) ?? subject.checkpointId;
51
109
  if (!declared || !source.plan!.steps.some(step => step.id === stepId)) throw new JobError('JOB_ASK_INVALID');
52
110
  return source;
53
111
  }
@@ -123,6 +181,207 @@ export function prepareJobStill(input: JobUISubmission, ask: JobPendingAsk, reta
123
181
  return {still, bytes, binding: binding as unknown as JobRigCapture['binding']};
124
182
  }
125
183
 
184
+ function actObject<Key extends string>(value: unknown, allowed: readonly Key[]): Record<Key, unknown> {
185
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
186
+ throw new JobError('JOB_ACT_INVALID');
187
+ }
188
+ for (const key of Object.keys(value)) {
189
+ if (!allowed.includes(key as Key)) throw new JobError('JOB_ACT_INVALID');
190
+ }
191
+ return value as Record<Key, unknown>;
192
+ }
193
+
194
+ function actIdField(value: unknown): string {
195
+ try {
196
+ return jobId(value);
197
+ } catch {
198
+ throw new JobError('JOB_ACT_INVALID');
199
+ }
200
+ }
201
+
202
+ export function prepareJobRecordAct(options: {
203
+ readonly jobId: string;
204
+ readonly submission: JobUISubmission;
205
+ readonly ask: PendingAskV3;
206
+ readonly retained: JobRetainedRecordSource;
207
+ readonly reviewer: JobReviewerBinding;
208
+ readonly still?: unknown;
209
+ readonly actId?: string;
210
+ readonly at?: string;
211
+ }): RecordAct {
212
+ const { submission, ask, retained, reviewer } = options;
213
+ if (!submission || typeof submission !== 'object' || Array.isArray(submission)) {
214
+ throw new JobError('JOB_REQUEST_INVALID');
215
+ }
216
+ const rawSubmission = submission as unknown as Record<string, unknown>;
217
+ if (
218
+ options.still !== undefined ||
219
+ rawSubmission.capture !== undefined ||
220
+ 'authority' in rawSubmission ||
221
+ 'source' in rawSubmission
222
+ ) {
223
+ throw new JobError('JOB_REQUEST_INVALID');
224
+ }
225
+ if ((JOB_RESERVED_ACT_KINDS as readonly unknown[]).includes(rawSubmission.kind)) {
226
+ throw new JobError('JOB_ACT_KIND_DISABLED');
227
+ }
228
+ if (ask.status !== 'pending') throw new JobError('JOB_ASK_SUPERSEDED');
229
+ if (!isRecordSource(ask.source)) throw new JobError('JOB_ACT_SOURCE_STALE');
230
+ let askSubject: RecordSubject;
231
+ try {
232
+ askSubject = validateRecordAskSubject(ask.subject, ask.source);
233
+ } catch {
234
+ throw new JobError('JOB_ACT_SOURCE_STALE');
235
+ }
236
+ if (submission.kind !== askSubject.kind || submission.publicationId !== ask.publicationId) {
237
+ throw new JobError('JOB_ACT_SOURCE_STALE');
238
+ }
239
+ let boundSource: RecordSource;
240
+ try {
241
+ boundSource = bindJobRecordAsk(askSubject, retained);
242
+ } catch {
243
+ throw new JobError('JOB_ACT_SOURCE_STALE');
244
+ }
245
+ if (
246
+ boundSource.sourceHash !== ask.source.sourceHash ||
247
+ requestDigest(boundSource) !== requestDigest(ask.source)
248
+ ) {
249
+ throw new JobError('JOB_ACT_SOURCE_STALE');
250
+ }
251
+ if (
252
+ !reviewer ||
253
+ typeof reviewer !== 'object' ||
254
+ Array.isArray(reviewer) ||
255
+ Object.keys(reviewer).some(key => key !== 'id' && key !== 'role') ||
256
+ typeof reviewer.id !== 'string' ||
257
+ !reviewer.id ||
258
+ (reviewer.role !== 'owner' && reviewer.role !== 'delegate')
259
+ ) {
260
+ throw new JobError('JOB_AUTHORITY_REFUSED');
261
+ }
262
+ const at = options.at ?? new Date().toISOString();
263
+ const actId = options.actId ?? randomUUID();
264
+ const envelope = {
265
+ schema: JOB_RECORD_ACT_SCHEMA,
266
+ actId: actIdField(actId),
267
+ jobId: actIdField(options.jobId),
268
+ askId: actIdField(ask.askId),
269
+ publicationId: actIdField(ask.publicationId),
270
+ authority: {
271
+ actor: 'human' as const,
272
+ channel: 'review-ui' as const,
273
+ reviewer: { id: reviewer.id, role: reviewer.role },
274
+ },
275
+ at,
276
+ };
277
+
278
+ switch (askSubject.kind) {
279
+ case 'interview-picks': {
280
+ if (boundSource.subject !== 'option-set') throw new JobError('JOB_ACT_SOURCE_STALE');
281
+ const value = actObject(submission.value, ['questionId', 'selections', 'note']);
282
+ if (
283
+ !('questionId' in value) ||
284
+ !('selections' in value) ||
285
+ !('note' in value) ||
286
+ value.questionId !== askSubject.questionId ||
287
+ !Array.isArray(value.selections)
288
+ ) {
289
+ throw new JobError('JOB_ACT_INVALID');
290
+ }
291
+ const question = retained.questions.find(
292
+ item => item.editable && item.set.id === askSubject.setId && item.set.question === askSubject.questionId,
293
+ );
294
+ if (!question) throw new JobError('JOB_ACT_SOURCE_STALE');
295
+ const selections = value.selections.map(raw => {
296
+ const item = actObject(raw, ['itemId', 'optionId', 'otherText']);
297
+ if (!('itemId' in item) || !('optionId' in item) || !('otherText' in item)) {
298
+ throw new JobError('JOB_ACT_INVALID');
299
+ }
300
+ if (item.otherText !== null && typeof item.otherText !== 'string') {
301
+ throw new JobError('JOB_ACT_INVALID');
302
+ }
303
+ return {
304
+ itemId: actIdField(item.itemId),
305
+ optionId: actIdField(item.optionId),
306
+ otherText: item.otherText === null ? null : words(item.otherText),
307
+ };
308
+ });
309
+ const note = words(value.note);
310
+ try {
311
+ validatePicks(
312
+ {
313
+ schema: 'rig-review/interview-picks@1',
314
+ set: question.ref,
315
+ by: 'user',
316
+ at,
317
+ picks: selections.map(item => ({
318
+ ask: item.itemId,
319
+ option_id: item.optionId,
320
+ ...(item.otherText === null ? {} : { other_text: item.otherText }),
321
+ })),
322
+ note,
323
+ },
324
+ question,
325
+ );
326
+ } catch {
327
+ throw new JobError('JOB_ACT_INVALID');
328
+ }
329
+ return parseRecordAct({
330
+ ...envelope,
331
+ kind: 'interview-picks',
332
+ source: boundSource,
333
+ value: { questionId: askSubject.questionId, selections, note },
334
+ });
335
+ }
336
+ case 'checkpoint': {
337
+ if (boundSource.subject !== 'plan') throw new JobError('JOB_ACT_SOURCE_STALE');
338
+ const value = actObject(submission.value, ['checkpointId', 'outcome', 'words']);
339
+ if (
340
+ !('checkpointId' in value) ||
341
+ !('outcome' in value) ||
342
+ !('words' in value) ||
343
+ value.checkpointId !== askSubject.checkpointId
344
+ ) {
345
+ throw new JobError('JOB_ACT_INVALID');
346
+ }
347
+ return parseRecordAct({
348
+ ...envelope,
349
+ kind: 'checkpoint',
350
+ source: boundSource,
351
+ value: {
352
+ checkpointId: askSubject.checkpointId,
353
+ planStepId: askSubject.checkpointId,
354
+ outcome: choice(value.outcome, ['pass', 'fail'] as const),
355
+ words: words(value.words),
356
+ },
357
+ });
358
+ }
359
+ case 'signoff': {
360
+ if (boundSource.subject !== 'plan') throw new JobError('JOB_ACT_SOURCE_STALE');
361
+ const value = actObject(submission.value, ['stage', 'decision', 'words']);
362
+ if (
363
+ !('stage' in value) ||
364
+ !('decision' in value) ||
365
+ !('words' in value) ||
366
+ value.stage !== askSubject.stage ||
367
+ value.decision !== 'approved'
368
+ ) {
369
+ throw new JobError('JOB_ACT_INVALID');
370
+ }
371
+ return parseRecordAct({
372
+ ...envelope,
373
+ kind: 'signoff',
374
+ source: boundSource,
375
+ value: {
376
+ stage: askSubject.stage,
377
+ decision: 'approved',
378
+ words: words(value.words),
379
+ },
380
+ });
381
+ }
382
+ }
383
+ }
384
+
126
385
  /** Only the authenticated UI host invokes this adapter. All source and authority
127
386
  * fields are daemon-owned. Empty/whitespace strings remain exact human words.
128
387
  */
@@ -133,8 +392,57 @@ export function finalizeJobAct(options: {
133
392
  readonly retained: JobRetainedSource;
134
393
  readonly reviewer: JobReviewerBinding;
135
394
  readonly still?: JobRigStill;
136
- }): JobAct {
137
- const { submission, ask, retained, reviewer } = options;
395
+ }): JobAct;
396
+ export function finalizeJobAct(options: {
397
+ readonly jobId: string;
398
+ readonly submission: JobUISubmission;
399
+ readonly ask: PendingAskV3;
400
+ readonly retained: JobRetainedRecordSource;
401
+ readonly reviewer: JobReviewerBinding;
402
+ readonly still?: undefined;
403
+ readonly actId?: string;
404
+ readonly at?: string;
405
+ }): RecordAct;
406
+ export function finalizeJobAct(options: {
407
+ readonly jobId: string;
408
+ readonly submission: JobUISubmission;
409
+ readonly ask: JobPendingAsk | PendingAskV3;
410
+ readonly retained: JobRetainedSourceV3;
411
+ readonly reviewer: JobReviewerBinding;
412
+ readonly still?: JobRigStill;
413
+ readonly actId?: string;
414
+ readonly at?: string;
415
+ }): ActV3;
416
+ export function finalizeJobAct(options: {
417
+ readonly jobId: string;
418
+ readonly submission: JobUISubmission;
419
+ readonly ask: JobPendingAsk | PendingAskV3;
420
+ readonly retained: JobRetainedSourceV3;
421
+ readonly reviewer: JobReviewerBinding;
422
+ readonly still?: JobRigStill;
423
+ readonly actId?: string;
424
+ readonly at?: string;
425
+ }): ActV3 {
426
+ if (isRetainedRecordSource(options.retained)) {
427
+ return prepareJobRecordAct({
428
+ jobId: options.jobId,
429
+ submission: options.submission,
430
+ ask: options.ask,
431
+ retained: options.retained,
432
+ reviewer: options.reviewer,
433
+ still: options.still,
434
+ actId: options.actId,
435
+ at: options.at,
436
+ });
437
+ }
438
+ const { submission, ask, retained, reviewer } = options as {
439
+ readonly jobId: string;
440
+ readonly submission: JobUISubmission;
441
+ readonly ask: JobPendingAsk;
442
+ readonly retained: JobRetainedSource;
443
+ readonly reviewer: JobReviewerBinding;
444
+ readonly still?: JobRigStill;
445
+ };
138
446
  if (ask.status !== 'pending') throw new JobError('JOB_ASK_SUPERSEDED');
139
447
  if (submission.kind !== ask.subject.kind || submission.publicationId !== ask.publicationId) throw new JobError('JOB_ACT_SOURCE_STALE');
140
448
  const source = bindJobAsk(ask.subject, retained);