rig-review 4.5.0 → 4.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.
@@ -28,7 +28,7 @@ export interface InterviewDiagnostic {
28
28
  code: 'INTERVIEW_OPTIONS_STALE' | 'INTERVIEW_OPTIONS_SCENE_LEGACY';
29
29
  question: string; record: string; ref: SetRef; at?: string;
30
30
  }
31
- export interface InterviewQuestion {ref: SetRef; set: InterviewSet; editable: boolean; images: Image[]; hasParts: boolean; partsUnavailable?: boolean; answer?: RecordData}
31
+ export interface InterviewQuestion {ref: SetRef; set: InterviewSet; editable: boolean; images: Image[]; hasParts: boolean; partsUnavailable?: boolean; scenePicture?: true; missingPicture?: 'rig' | 'scene'; answer?: RecordData}
32
32
  export const digest = (data: Buffer | string) => createHash('sha256').update(data).digest('hex');
33
33
  export const object = (v: unknown): RecordData => v !== null && typeof v === 'object' && !Array.isArray(v) ? v as RecordData : {};
34
34
  const records = (v: unknown) => Array.isArray(v) ? v.map(object) : [];
@@ -174,30 +174,38 @@ function contextAt(project: RecordData, stage: string, at: number): unknown {
174
174
  config: object(rig.provenance).config, parts: draft.parts};
175
175
  }
176
176
 
177
+ /** Resolve the same question-level plates for project and retained record readers. */
178
+ export function inspectSceneQuestion(project: RecordData, ctx: RecordData, set: InterviewSet,
179
+ at: number, read: (ref: SetRef) => RecordData): {images: Image[]; hasParts: false; legacy: boolean} {
180
+ const drafted = date(set.drafted_at);
181
+ if (set.stage !== 'post-interview' || !Number.isFinite(at) || drafted > at ||
182
+ reopened(project, set.stage, drafted, at)) return stale(set.id);
183
+ let legacy = false;
184
+ let scene: RecordData = {};
185
+ for (const instant of [drafted, at]) {
186
+ const selected = sceneAt(project, instant, read);
187
+ if (!selected || !equal(selected.context, ctx)) return stale(set.id);
188
+ if (!selected.current) {
189
+ if (drafted >= Date.parse('2026-11-08T00:00:00Z')) return stale(set.id);
190
+ legacy = true;
191
+ }
192
+ scene = selected.document;
193
+ }
194
+ const images = records(scene.plates).map(plate => ({
195
+ ref: {path: plate.path as string, sha256: plate.sha256 as string}, name: plate.role as string, type: 'image/png',
196
+ }));
197
+ return {images, hasParts: false, legacy};
198
+ }
199
+
177
200
  function inspectContext(root: string, project: RecordData, raw: RecordData, set: InterviewSet, at: number, fresh: boolean): {
178
201
  images: Image[]; hasParts: boolean; partsUnavailable?: boolean; legacy?: boolean;
179
202
  } {
180
- const drafted = date(set.drafted_at);
181
203
  const ctx = object(raw.context);
182
- if (!Number.isFinite(at) || drafted > at || reopened(project, set.stage, drafted, at)) return stale(set.id);
183
204
  if (ctx.kind === 'scene') {
184
- if (set.stage !== 'post-interview') return stale(set.id);
185
- let legacy = false;
186
- let scene: RecordData = {};
187
- for (const instant of [drafted, at]) {
188
- const selected = sceneAt(project, instant, ref => jsonObject(boundBytes(root, ref)));
189
- if (!selected || !equal(selected.context, ctx)) return stale(set.id);
190
- if (!selected.current) {
191
- if (drafted >= Date.parse('2026-11-08T00:00:00Z')) return stale(set.id);
192
- legacy = true;
193
- }
194
- scene = selected.document;
195
- }
196
- const images = records(scene.plates).map(plate => ({
197
- ref: {path: plate.path as string, sha256: plate.sha256 as string}, name: plate.role as string, type: 'image/png',
198
- }));
199
- return {images, hasParts: false, legacy};
205
+ return inspectSceneQuestion(project, ctx, set, at, ref => jsonObject(boundBytes(root, ref)));
200
206
  }
207
+ const drafted = date(set.drafted_at);
208
+ if (!Number.isFinite(at) || drafted > at || reopened(project, set.stage, drafted, at)) return stale(set.id);
201
209
  const expected = contextAt(project, set.stage, drafted);
202
210
  const historicalInputs = !fresh && set.stage === 'interview';
203
211
  const matches = historicalInputs ? ctx.kind === 'inputs' && records(ctx.files).length > 0 &&
@@ -66,28 +66,33 @@ function sorted(value: unknown): unknown {
66
66
  if (data !== value) return value;
67
67
  return Object.fromEntries(Object.keys(data).sort().map(key => [key, sorted(data[key])]));
68
68
  }
69
- function current(project: Data, scene: Data, at: number): boolean {
69
+ /** Resolve the operative human acceptance and its package record from the project alone. */
70
+ export function acceptedRigReview(project: Data, versionNumber: unknown, at: number) {
70
71
  const live = records(project.versions).map((version, index) => ({version, index})).filter(({version}) =>
71
72
  version.kind === 'rig' && date(version.at) <= at && !coveringChange(project, 'rig-review', date(version.at) - 1, at));
72
73
  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
+ if (!latest || latest.version.n !== versionNumber) return undefined;
74
75
  const {version, index} = latest;
75
76
  const verdicts = records(version.verdicts);
76
77
  const operative = verdicts.map((verdict, index) => ({verdict, index})).filter(({verdict}) =>
77
78
  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
+ if (!operative || operative.verdict.verdict !== 'accepted') return undefined;
79
80
  const signature = records(project.signoffs).filter(signoff => signoff.stage === 'rig-review' && signoff.checkpoint === null &&
80
81
  human(signoff.by) && date(signoff.at) <= at && object(signoff.target).version === version.n &&
81
82
  !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
+ if (!signature) return undefined;
83
84
  const target = object(signature.target), pkg = object(version.review_package);
84
85
  const packageHash = createHash('sha256').update(JSON.stringify(sorted({config: pkg.config, files: pkg.files}))).digest('hex');
85
86
  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
- });
87
+ !equal(target.review_package, {path: `versions[${index}].review_package`, sha256: packageHash})) return undefined;
88
+ return {
89
+ pkg,
90
+ acceptance: {
91
+ signoff: {stage: signature.stage, checkpoint: signature.checkpoint, at: signature.at},
92
+ verdict: target.verdict,
93
+ review_package: target.review_package,
94
+ },
95
+ };
91
96
  }
92
97
 
93
98
  export function sceneAt(project: Data, at: number, read: (ref: SetRef) => Data) {
@@ -96,7 +101,7 @@ export function sceneAt(project: Data, at: number, read: (ref: SetRef) => Data)
96
101
  const entries = records(project.scenes);
97
102
  for (const [index, entry] of entries.entries()) {
98
103
  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) ||
104
+ entry.path !== `evidence/scene/s${index + 1}.json` || !hash(entry.sha256) || !(entry.by === 'agent' || human(entry.by)) ||
100
105
  typeof entry.at !== 'string' || !entry.at.endsWith('Z') || !Number.isFinite(date(entry.at))) return stale();
101
106
  }
102
107
  const candidate = entries.filter(entry => date(entry.at) <= at).at(-1);
@@ -105,5 +110,7 @@ export function sceneAt(project: Data, at: number, read: (ref: SetRef) => Data)
105
110
  let scene: Data;
106
111
  try {scene = read(reference);} catch {return stale();}
107
112
  if (!sceneDocumentShape(scene, candidate.n)) return stale();
108
- return {context: {kind: 'scene', scene: reference}, current: current(project, scene, at), document: scene};
113
+ const rig = object(scene.rig);
114
+ const accepted = acceptedRigReview(project, rig.version, at);
115
+ return {context: {kind: 'scene', scene: reference}, current: equal(rig.acceptance, accepted?.acceptance), document: scene};
109
116
  }
package/src/job-act.ts CHANGED
@@ -1,14 +1,14 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import {
3
3
  JOB_ACT_SCHEMA, JOB_API_SCHEMA, JOB_COMMENTS_ACT_SCHEMA, JOB_API_V3_SCHEMA, JOB_RECORD_ACT_KINDS, JOB_RECORD_ACT_SCHEMA, jobStillByteLimit, JOB_ENABLED_ACT_KINDS, JOB_PLAN_BOUND_SIGNOFF_STAGES, JOB_RESERVED_ACT_KINDS,
4
- type ActV3, type JobAct, type JobCommentsAct, type JobApiSchema, type JobPendingAsk, type JobPublicationMode, type JobReviewerBinding,
4
+ type ActV3, type JobAct, type JobComment, type JobCommentsAct, type JobApiSchema, type JobPendingAsk, type JobPublicationMode, 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, type UISubmissionV3,
6
+ type JobMeshEdit, type PendingAskV3, type RecordAct, type RecordSource, type RecordSubject, type SourceV3, type UISubmissionV3,
7
7
  } from './job-contract.ts';
8
8
  import { parsePartsIssue, type PartsIssue } from './parts-comment.ts';
9
9
  import {
10
10
  isRecordSource, jobHash, jobId, jobInteger, jobObject,
11
- parseCommentsAct, parseRecordAct, parseRecordSource, requestDigest, validateRecordAskSubject,
11
+ meshEditsActForEmission, parseCommentsAct, parseMeshEdits, parseRecordAct, parseRecordSource, requestDigest, validateRecordAskSubject,
12
12
  } from './job-api.ts';
13
13
  import { checkpointNoteComments, feedbackItemComments, noteComments, partsIssueComments } from './feedback-export.ts';
14
14
  import type { Feedback } from './session.ts';
@@ -22,6 +22,9 @@ import {
22
22
  import { JobError } from './job-store.ts';
23
23
  import { checkedPath, readRegular } from './interview-project.ts';
24
24
  import {validatePngBytes} from './comment-crops.ts';
25
+ import {EMIT_UNPINNED_CREATE_FIELDS} from './create-pin-gate.ts';
26
+ import {applyMeshOps, attachmentHashText, MESH_EDIT_CODES} from './mesh-edit.ts';
27
+ import {readStoredSetupMesh} from './setup-mesh.ts';
25
28
 
26
29
  function words(value: unknown): string {
27
30
  if (typeof value !== 'string' || value.length > 10_000) throw new JobError('JOB_ACT_INVALID');
@@ -34,6 +37,56 @@ function commentsAct(act: JobCommentsAct): JobCommentsAct {
34
37
  return act;
35
38
  }
36
39
 
40
+ function hasMeshSubmission(kind: unknown, value: unknown): boolean {
41
+ if (value === null || typeof value !== 'object' || !Object.hasOwn(value, 'meshEdits')) return false;
42
+ const {stage, verdict} = value as {stage?: unknown; verdict?: unknown};
43
+ if (kind !== 'review-verdict' || stage !== 'rig-review' || verdict !== 'changes-requested') {
44
+ throw new JobError('JOB_ACT_INVALID');
45
+ }
46
+ return true;
47
+ }
48
+
49
+ function validateRetainedMeshEdits(retained: JobRetainedSource, edits: readonly JobMeshEdit[]): void {
50
+ const binding = retained.source.model;
51
+ if (!binding) throw new JobError('JOB_ACT_SOURCE_STALE');
52
+ let model: {stage?: {width?: number; height?: number}};
53
+ try {
54
+ const bytes = readRegular(checkedPath(retained.snapshotRoot, binding.path), 64 * 1024 * 1024);
55
+ if (jobHash(bytes) !== binding.sha256) throw new Error('model hash differs');
56
+ model = JSON.parse(bytes.toString('utf8'));
57
+ } catch {
58
+ throw new JobError('JOB_ACT_SOURCE_STALE');
59
+ }
60
+ for (const {edit} of edits) {
61
+ const read = readStoredSetupMesh(model, edit.slot, edit, MESH_EDIT_CODES);
62
+ if (!read.ok || jobHash(attachmentHashText(read.mesh.entry)) !== edit.source.hash) throw new JobError('JOB_ACT_SOURCE_STALE');
63
+ const {mesh} = read;
64
+ const {frame, positions, vertexCount, triangleCount, hullLength, hash} = edit.source;
65
+ const uvs = mesh.entry.uvs;
66
+ if (mesh.linked || !Array.isArray(uvs) || uvs.length !== vertexCount * 2 ||
67
+ mesh.vertices.length !== vertexCount || positions.length !== vertexCount ||
68
+ mesh.triangles.length !== triangleCount * 3 || mesh.hull !== hullLength ||
69
+ model.stage?.width !== frame.width || model.stage?.height !== frame.height) {
70
+ throw new JobError('JOB_ACT_INVALID');
71
+ }
72
+ try {
73
+ applyMeshOps({slot: edit.slot, attachment: edit.attachment, skin: edit.skin,
74
+ vertices: positions, triangles: mesh.triangles, hull: hullLength, hash}, edit.ops);
75
+ } catch {
76
+ throw new JobError('JOB_ACT_INVALID');
77
+ }
78
+ }
79
+ }
80
+
81
+ function generalComments(value: unknown): JobComment[] {
82
+ if (value === undefined) return [];
83
+ if (!Array.isArray(value)) throw new JobError('JOB_ACT_INVALID');
84
+ return Array.from(value, (text: unknown) => {
85
+ if (typeof text !== 'string') throw new JobError('JOB_ACT_INVALID');
86
+ return {text};
87
+ });
88
+ }
89
+
37
90
  function choice<Value extends string>(value: unknown, allowed: readonly Value[]): Value {
38
91
  if (!allowed.includes(value as Value)) throw new JobError('JOB_ACT_INVALID');
39
92
  return value as Value;
@@ -157,6 +210,9 @@ export function parseUISubmission(
157
210
  if (!allowed) {
158
211
  throw new JobError('JOB_ACT_INVALID');
159
212
  }
213
+ if (hasMeshSubmission(item.kind, item.value) && !EMIT_UNPINNED_CREATE_FIELDS) {
214
+ throw new JobError('JOB_ACT_KIND_DISABLED');
215
+ }
160
216
  if (item.capture !== undefined && (item.kind !== 'review-verdict' ||
161
217
  (item.value as {stage?: unknown} | null)?.stage !== 'rig-review')) throw new JobError('JOB_REQUEST_INVALID');
162
218
  return item as unknown as UISubmissionV3;
@@ -457,6 +513,7 @@ export function finalizeJobAct(options: {
457
513
  readonly still?: JobRigStill;
458
514
  readonly actId?: string;
459
515
  readonly at?: string;
516
+ readonly emitUnpinned?: boolean;
460
517
  }): ActV3;
461
518
  export function finalizeJobAct(options: {
462
519
  readonly jobId: string;
@@ -467,7 +524,15 @@ export function finalizeJobAct(options: {
467
524
  readonly still?: JobRigStill;
468
525
  readonly actId?: string;
469
526
  readonly at?: string;
527
+ readonly emitUnpinned?: boolean;
470
528
  }): ActV3 {
529
+ const meshSubmission = hasMeshSubmission(options.submission.kind, options.submission.value);
530
+ if (meshSubmission && (isRetainedRecordSource(options.retained) ||
531
+ options.ask.subject.kind !== 'review-verdict' || options.ask.subject.stage !== 'rig-review')) {
532
+ throw new JobError('JOB_ACT_INVALID');
533
+ }
534
+ const emitUnpinned = options.emitUnpinned ?? EMIT_UNPINNED_CREATE_FIELDS;
535
+ if (meshSubmission && !emitUnpinned) throw new JobError('JOB_ACT_KIND_DISABLED');
471
536
  if (isRetainedRecordSource(options.retained)) {
472
537
  return prepareJobRecordAct({
473
538
  jobId: options.jobId,
@@ -537,7 +602,7 @@ export function finalizeJobAct(options: {
537
602
  } });
538
603
  }
539
604
  case 'parts-verdict': {
540
- const value = jobObject(submission.value, ['verdict', 'issues', 'words']);
605
+ const value = jobObject(submission.value, ['verdict', 'issues', 'words', 'general']);
541
606
  const verdict = choice(value.verdict, ['approved', 'changes-requested'] as const);
542
607
  if (
543
608
  !Array.isArray(value.issues) ||
@@ -577,14 +642,23 @@ export function finalizeJobAct(options: {
577
642
  selector: source.selector as Extract<NonNullable<JobSourceBinding['selector']>, { kind: 'draft' }>,
578
643
  parts: source.parts!,
579
644
  },
580
- value: { verdict, comments: [...partsIssueComments(issues), ...noteComments(words(value.words))] },
645
+ value: {
646
+ verdict,
647
+ comments: [...partsIssueComments(issues), ...noteComments(words(value.words)), ...generalComments(value.general)],
648
+ },
581
649
  });
582
650
  }
583
651
  case 'review-verdict': {
584
652
  const value = jobObject(submission.value, ['stage', 'verdict', 'words',
585
- ...(ask.subject.kind === 'review-verdict' && ask.subject.stage === 'rig-review' ? ['feedback'] : [])]);
653
+ ...(ask.subject.kind === 'review-verdict' && ask.subject.stage === 'rig-review' ? ['feedback', 'general', 'meshEdits'] : [])]);
586
654
  if (ask.subject.kind !== 'review-verdict' || ask.subject.stage === 'image-review' || value.stage !== ask.subject.stage) throw new JobError('JOB_ACT_INVALID');
587
655
  if (ask.subject.stage === 'rig-review') {
656
+ const verdict = choice(value.verdict, ['pending', 'approved', 'changes-requested'] as const);
657
+ let meshEdits: readonly JobMeshEdit[] | undefined;
658
+ if (meshSubmission) {
659
+ meshEdits = parseMeshEdits(value.meshEdits);
660
+ validateRetainedMeshEdits(retained, meshEdits);
661
+ }
588
662
  if (!options.still) throw new JobError('JOB_STILL_CAPTURE_FAILED');
589
663
  const note = words(value.words);
590
664
  if (value.feedback !== undefined && !Array.isArray(value.feedback)) throw new JobError('JOB_ACT_INVALID');
@@ -592,10 +666,12 @@ export function finalizeJobAct(options: {
592
666
  try {
593
667
  verdictComments = value.feedback === undefined ? noteComments(note) : feedbackItemComments(value.feedback as Feedback[]);
594
668
  } catch { throw new JobError('JOB_ACT_INVALID'); }
595
- return commentsAct({...comments, kind: 'review-verdict',
669
+ const act = {...comments, kind: 'review-verdict' as const,
596
670
  source: {...source, model: source.model!, selector: source.selector as Extract<NonNullable<JobSourceBinding['selector']>, {kind: 'rig'}>},
597
- value: {stage: 'rig-review', verdict: choice(value.verdict, ['pending', 'approved', 'changes-requested'] as const), comments: verdictComments},
598
- still: options.still});
671
+ value: {stage: 'rig-review' as const, verdict, comments: [...verdictComments, ...generalComments(value.general)]},
672
+ still: options.still};
673
+ if (meshEdits) return meshEditsActForEmission({...act, value: {...act.value, meshEdits}}, emitUnpinned);
674
+ return commentsAct(act);
599
675
  }
600
676
  return commentsAct({ ...comments, kind: 'review-verdict', source: { ...source, model: source.model!,
601
677
  selector: source.selector as Extract<NonNullable<JobSourceBinding['selector']>, { kind: 'rig' | 'post' }> }, value: {
package/src/job-api.ts CHANGED
@@ -1,13 +1,16 @@
1
1
  import {checkpointEvidenceFields} from './job-checkpoint-evidence.ts';
2
+ import {previousDraftFields} from './job-previous-draft.ts';
2
3
  import { createHash, timingSafeEqual } from 'node:crypto';
3
4
  import {
4
5
  JOB_ACT_SCHEMA, JOB_API_SCHEMA, JOB_API_V3_SCHEMA, JOB_ENABLED_ACT_KINDS, JOB_PARTS_ENUMERATOR_RANGE,
5
6
  JOB_PLAN_BOUND_SIGNOFF_STAGES, JOB_RECORD_SIGNOFF_STAGES, JOB_RECORD_ACT_SCHEMA, JOB_RECORD_INSTANCE_SCHEMA, JOB_RECORD_SOURCE_SCHEMA,
6
7
  JOB_RESERVED_ACT_KINDS,
8
+ JOB_MESH_EDITS_ACT_SCHEMA,
7
9
  type AgentRequestV3, type FetchActRequestV3, type JobAgentRequest, type JobApiSchema,
8
10
  type JobCheckpointEvidence, type JobDisplayAcknowledgment, type JobErrorCode, type JobFetchActRequest, type JobFileIdentity,
9
11
  type JobHostPorts, type JobHumanAuthority, type JobInterviewDiagnostic, type JobInterviewDiagnostics,
10
12
  type JobInterviewJson, type JobInterviewRecord, type JobPlanIdentity, type JobPublicationMode,
13
+ type JobAct, type JobMeshEdit, type JobMeshEditsAct, type JobMeshEditValue,
11
14
  type JobPublishRequest, type JobResult, type JobSelector, type JobSha256, type JobSubject,
12
15
  type OptionContext, type OptionSource, type PlanContext, type PlanSource, type ProjectRecord,
13
16
  type PublishRequestV3, type PublishResultV3, type RecordAct, type RecordFreeze,
@@ -27,6 +30,8 @@ import { validatePngCrop, validatePngCropMetadata } from './comment-crops.ts';
27
30
  import {parseJobPartsIdentity} from './job-source.ts';
28
31
  import {parseControlPart, parseControlView} from './control.ts';
29
32
  import {EMIT_UNPINNED_CREATE_FIELDS} from './create-pin-gate.ts';
33
+ import {canonicalJson} from './canonical-json.ts';
34
+ import {MESH_EDIT_MAX_OPS, type Vec} from './mesh-edit.ts';
30
35
 
31
36
  export type {
32
37
  JobInterviewJson,
@@ -37,23 +42,17 @@ export type {
37
42
 
38
43
  export const jobBodyLimit = 256 * 1024;
39
44
  export const jobWaitLimitMs = 30_000;
45
+ /** Subjects one `ask-batch` request may list (#963). */
46
+ export const jobAskBatchLimit = 64;
40
47
  const requestDeadlineMs = 10_000;
41
48
 
42
49
  export function jobHash(value: string | Uint8Array): string {
43
50
  return createHash('sha256').update(value).digest('hex');
44
51
  }
45
52
 
46
- /** Private replay digests only. This is not a mesh payload/source hash format. */
53
+ /** Private replay digest. Preserve the original serializer for persisted request identity. */
47
54
  export function requestDigest(value: unknown): string {
48
- const sorted = (item: unknown): unknown => {
49
- if (Array.isArray(item)) return item.map(sorted);
50
- if (item !== null && typeof item === 'object') {
51
- return Object.fromEntries(Object.entries(item).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)
52
- .map(([key, child]) => [key, sorted(child)]));
53
- }
54
- return item;
55
- };
56
- return jobHash(JSON.stringify(sorted(value)));
55
+ return jobHash(canonicalJson(value));
57
56
  }
58
57
 
59
58
  export function sameCapability(given: string | null, expected: string): boolean {
@@ -285,7 +284,7 @@ export function parseJobRequest(
285
284
  ): JobAgentRequest | JobFetchActRequest | AgentRequestV3 | FetchActRequestV3 {
286
285
  const item = jobObject(value, [
287
286
  'schema', 'jobId', 'requestId', 'verb', 'expectedGeneration', 'idempotencyKey',
288
- 'result', 'freeze', 'publicationId', 'subject', 'after', 'waitMs', 'reason', 'actId',
287
+ 'result', 'freeze', 'publicationId', 'subject', 'subjects', 'after', 'waitMs', 'reason', 'actId',
289
288
  ]);
290
289
  const targetSchema = mode === 'package-only' || mode === 'record-and-package'
291
290
  ? jobApiSchemaForMode(mode)
@@ -332,18 +331,26 @@ export function parseJobRequest(
332
331
  }
333
332
  case 'ask': {
334
333
  jobObject(item, ['schema', 'jobId', 'requestId', 'verb', 'expectedGeneration', 'idempotencyKey', 'publicationId', 'subject']);
335
- const isReopenSubject =
336
- item.subject !== null &&
337
- typeof item.subject === 'object' &&
338
- !Array.isArray(item.subject) &&
339
- (item.subject as { kind?: unknown }).kind === 'reopen';
340
334
  return {
341
335
  ...mutation,
342
336
  verb: 'ask',
343
337
  publicationId: jobId(item.publicationId),
344
- subject: isReopenSubject ? parseRecordSubject(item.subject) : parseJobSubject(item.subject),
338
+ subject: parseAskSubjectV3(item.subject),
345
339
  };
346
340
  }
341
+ case 'ask-batch': {
342
+ jobObject(item, ['schema', 'jobId', 'requestId', 'verb', 'expectedGeneration', 'idempotencyKey', 'publicationId', 'subjects']);
343
+ const listed = item.subjects;
344
+ if (!Array.isArray(listed) || listed.length < 1 || listed.length > jobAskBatchLimit) throw new JobError('JOB_REQUEST_INVALID');
345
+ const seen = new Map<string, number>();
346
+ const subjects = Array.from(listed, (value: unknown, index) => atSubject(index, () => {
347
+ const subject = parseAskSubjectV3(value), digest = requestDigest(subject), first = seen.get(digest);
348
+ if (first !== undefined) throw new JobError('JOB_REQUEST_INVALID', `duplicate of subjects[${first}]`);
349
+ seen.set(digest, index);
350
+ return subject;
351
+ }));
352
+ return { ...mutation, verb: 'ask-batch', publicationId: jobId(item.publicationId), subjects };
353
+ }
347
354
  case 'close':
348
355
  jobObject(item, ['schema', 'jobId', 'requestId', 'verb', 'expectedGeneration', 'idempotencyKey', 'reason']);
349
356
  return { ...mutation, verb: 'close', reason: jobText(item.reason, 1024) };
@@ -386,6 +393,23 @@ export function parseJobRequest(
386
393
  throw new JobError('JOB_REQUEST_INVALID');
387
394
  }
388
395
 
396
+ /** The single V3 `ask` subject parser; `ask-batch` parses each listed subject through it. */
397
+ function parseAskSubjectV3(value: unknown): JobSubject | RecordSubject {
398
+ const isReopenSubject =
399
+ value !== null && typeof value === 'object' && !Array.isArray(value) && (value as { kind?: unknown }).kind === 'reopen';
400
+ return isReopenSubject ? parseRecordSubject(value) : parseJobSubject(value);
401
+ }
402
+
403
+ /** `ask-batch` refuses with the subject's own code, its message prefixed by the subject's request index. */
404
+ export function atSubject<Value>(index: number, fn: () => Value): Value {
405
+ try {
406
+ return fn();
407
+ } catch (error) {
408
+ if (error instanceof JobError) throw new JobError(error.code, `subjects[${index}]: ${error.message}`);
409
+ throw error;
410
+ }
411
+ }
412
+
389
413
  export function parseJobRequestV3(value: unknown): AgentRequestV3 | FetchActRequestV3 {
390
414
  return parseJobRequest(value, JOB_API_V3_SCHEMA);
391
415
  }
@@ -415,7 +439,7 @@ export function exactObject(
415
439
  return item;
416
440
  }
417
441
 
418
- function parseFileRow(value: unknown, code: JobErrorCode): JobFileIdentity {
442
+ export function parseFileRow(value: unknown, code: JobErrorCode): JobFileIdentity {
419
443
  const item = exactObject(value, ['path', 'sha256'], code);
420
444
  return asCode(() => ({ path: jobPath(item.path), sha256: jobSha(item.sha256) }), code);
421
445
  }
@@ -710,6 +734,7 @@ export function parseRecordPublishedContext(
710
734
  ): OptionContext | PlanContext {
711
735
  const selection = parseRecordResult(result);
712
736
  const checkedRecord = record === undefined ? undefined : parseProjectRecord(record, 'JOB_SOURCE_MISMATCH');
737
+ if (value && typeof value === 'object') previousDraftFields(value, null);
713
738
  const item = exactObject(value, ['label', 'parts', 'inputs', 'files', 'plan', 'subjects'], 'JOB_SOURCE_MISMATCH', ['checkpointEvidence']);
714
739
  const label = asCode(() => jobText(item.label), 'JOB_SOURCE_MISMATCH');
715
740
  const parts = parseRecordPartsIdentity(item.parts, 'JOB_SOURCE_MISMATCH');
@@ -1218,6 +1243,11 @@ function parseCommentAnchor(raw: unknown, text: string, source?: SourceV3 | stri
1218
1243
  if ('schema' in item) {
1219
1244
  commentsObject(item, ['schema', 'id', 'parts', 'sourceHash', 'rigRegion', 'imageRegion', 'view', 'crop', 'nativeCrop']);
1220
1245
  const issue = parsePartsIssue({...item, summary: text}, true, false, false);
1246
+ const comparison = issue.view.comparison;
1247
+ if (comparison?.mode === 'difference' && comparison.operand === 'previous-draft' &&
1248
+ (issue.view.mode !== 'assembled' || !source || typeof source === 'string' || 'record' in source || !source.previousDraft)) {
1249
+ throw new JobError('JOB_ACT_INVALID');
1250
+ }
1221
1251
  if (issue.crop.png !== undefined) validatePngCrop(issue.crop as Parameters<typeof validatePngCrop>[0]);
1222
1252
  if (sourceHash && issue.sourceHash !== sourceHash) throw new JobError('JOB_ACT_SOURCE_STALE');
1223
1253
  if (source && typeof source !== 'string' && !('record' in source)) {
@@ -1364,11 +1394,13 @@ function commentsSource(raw: unknown): Exclude<SourceV3, OptionSource> {
1364
1394
  return record;
1365
1395
  }
1366
1396
  const common = ['sourceHash', 'projectHash', 'package', 'direction', 'optionSet', 'appliedResult', 'plan', 'parts'];
1367
- const item = commentsObject(raw, [...common, 'selector', 'model'], ['checkpointEvidence']);
1397
+ const item = commentsObject(raw, [...common, 'selector', 'model'], ['checkpointEvidence', 'previousDraft']);
1368
1398
  jobSha(item.sourceHash); if (item.projectHash !== null) jobSha(item.projectHash);
1369
1399
  const pkg = commentsObject(item.package, ['id', 'revision']); jobText(pkg.id); jobText(pkg.revision);
1370
1400
  for (const key of ['direction', 'model']) if (item[key] !== null) parseFileRow(item[key], 'JOB_ACT_INVALID');
1371
- parseJobSelector(item.selector);
1401
+ const selector = parseJobSelector(item.selector);
1402
+ const previousDraft = previousDraftFields(item, selector);
1403
+ if (previousDraft.previousDraft && item.parts === null) throw new JobError('JOB_ACT_INVALID');
1372
1404
  if (item.optionSet !== null) {
1373
1405
  const set = commentsObject(item.optionSet, ['id', 'sha256']); jobId(set.id); jobSha(set.sha256);
1374
1406
  }
@@ -1396,12 +1428,104 @@ function commentsSource(raw: unknown): Exclude<SourceV3, OptionSource> {
1396
1428
 
1397
1429
  /** Public @6 decoder. The UI finalizers write checkpoint, parts, rig/post verdict and signoff acts at @6 (#713). */
1398
1430
  export function parseCommentsAct(raw: unknown): JobCommentsAct {
1399
- return decodeCommentsAct(raw, false) as JobCommentsAct;
1431
+ return decodeCommentsAct(raw, JOB_COMMENTS_ACT_SCHEMA) as JobCommentsAct;
1400
1432
  }
1401
1433
 
1402
1434
  /** Public @7 decoder: the @6 rules plus an optional `context` on each comment. @6 input refuses. */
1403
1435
  export function parseContextCommentsAct(raw: unknown): JobContextCommentsAct {
1404
- return decodeCommentsAct(raw, true) as JobContextCommentsAct;
1436
+ return decodeCommentsAct(raw, JOB_COMMENT_CONTEXT_ACT_SCHEMA) as JobContextCommentsAct;
1437
+ }
1438
+
1439
+ /** Public @8 decoder. Model freshness and topology are checked by the writer. */
1440
+ export function parseMeshEditsAct(raw: unknown): JobMeshEditsAct {
1441
+ return decodeCommentsAct(raw, JOB_MESH_EDITS_ACT_SCHEMA) as JobMeshEditsAct;
1442
+ }
1443
+
1444
+ export function meshEditDigest(edit: JobMeshEditValue): JobSha256 {
1445
+ return jobHash(canonicalJson(edit));
1446
+ }
1447
+
1448
+ function meshNumber(raw: unknown): number {
1449
+ if (typeof raw !== 'number' || !Number.isFinite(raw) || Object.is(raw, -0)) throw new JobError('JOB_ACT_INVALID');
1450
+ return raw;
1451
+ }
1452
+
1453
+ function meshPair(raw: unknown, parse: (value: unknown) => number): Vec {
1454
+ if (!Array.isArray(raw) || raw.length !== 2) throw new JobError('JOB_ACT_INVALID');
1455
+ return [parse(raw[0]), parse(raw[1])];
1456
+ }
1457
+
1458
+ function roundedMeshPair(raw: unknown): void {
1459
+ const pair = meshPair(raw, meshNumber);
1460
+ // A multiply-round-divide pass can change an already rounded large double.
1461
+ if (pair.some(n => Number(n.toFixed(2)) !== n)) throw new JobError('JOB_ACT_INVALID');
1462
+ }
1463
+
1464
+ const meshIndex = (raw: unknown): number => jobInteger(meshNumber(raw));
1465
+
1466
+ function validateMeshOp(raw: unknown): void {
1467
+ const op = (raw as {op?: unknown} | null)?.op;
1468
+ switch (op) {
1469
+ case 'move': {
1470
+ const move = commentsObject(raw, ['op', 'v', 'from', 'to']);
1471
+ meshIndex(move.v); meshPair(move.from, meshNumber); roundedMeshPair(move.to);
1472
+ break;
1473
+ }
1474
+ case 'add': {
1475
+ const add = commentsObject(raw, ['op', 'at'], ['onEdge']);
1476
+ roundedMeshPair(add.at);
1477
+ if (Object.hasOwn(add, 'onEdge')) meshPair(add.onEdge, meshIndex);
1478
+ break;
1479
+ }
1480
+ case 'remove':
1481
+ meshIndex(commentsObject(raw, ['op', 'v']).v);
1482
+ break;
1483
+ case 'edge':
1484
+ case 'unedge': {
1485
+ const edge = commentsObject(raw, ['op', 'a', 'b']);
1486
+ meshIndex(edge.a); meshIndex(edge.b);
1487
+ break;
1488
+ }
1489
+ default:
1490
+ throw new JobError('JOB_ACT_INVALID');
1491
+ }
1492
+ }
1493
+
1494
+ function validateMeshEdit(raw: unknown): asserts raw is JobMeshEditValue {
1495
+ const edit = commentsObject(raw, ['slot', 'skin', 'attachment', 'basis', 'source', 'ops']);
1496
+ if (edit.basis !== 'setup' || [edit.slot, edit.skin, edit.attachment].some(name => typeof name !== 'string' || !name)) {
1497
+ throw new JobError('JOB_ACT_INVALID');
1498
+ }
1499
+ const source = commentsObject(edit.source, ['vertexCount', 'triangleCount', 'hullLength', 'hash', 'frame', 'positions']);
1500
+ const vertexCount = meshIndex(source.vertexCount);
1501
+ meshIndex(source.triangleCount); meshIndex(source.hullLength); jobSha(source.hash);
1502
+ const frame = commentsObject(source.frame, ['width', 'height']);
1503
+ if (meshNumber(frame.width) <= 0 || meshNumber(frame.height) <= 0 ||
1504
+ !Array.isArray(source.positions) || source.positions.length !== vertexCount) throw new JobError('JOB_ACT_INVALID');
1505
+ for (const position of source.positions) meshPair(position, meshNumber);
1506
+ if (!Array.isArray(edit.ops) || !edit.ops.length || edit.ops.length > MESH_EDIT_MAX_OPS) throw new JobError('JOB_ACT_INVALID');
1507
+ for (const op of edit.ops) validateMeshOp(op);
1508
+ }
1509
+
1510
+ /** Structures and digests only. The retained model is the writer's source of topology and freshness. */
1511
+ export function parseMeshEdits(raw: unknown): readonly JobMeshEdit[] {
1512
+ return asCode(() => {
1513
+ if (!Array.isArray(raw) || !raw.length) throw new JobError('JOB_ACT_INVALID');
1514
+ const seen = new Set<string>();
1515
+ let previousOrder: string | undefined;
1516
+ for (const item of raw) {
1517
+ const {edit, sha256} = commentsObject(item, ['edit', 'sha256']);
1518
+ validateMeshEdit(edit);
1519
+ const identity = [edit.skin, edit.slot, edit.attachment];
1520
+ const order = identity.join('/'), key = JSON.stringify(identity);
1521
+ if (seen.has(key) || (previousOrder !== undefined && order < previousOrder) || jobSha(sha256) !== meshEditDigest(edit)) {
1522
+ throw new JobError('JOB_ACT_INVALID');
1523
+ }
1524
+ seen.add(key);
1525
+ previousOrder = order;
1526
+ }
1527
+ return structuredClone(raw) as JobMeshEdit[];
1528
+ }, 'JOB_ACT_INVALID');
1405
1529
  }
1406
1530
 
1407
1531
  /** The comments act a writer sends. With EMIT_UNPINNED_CREATE_FIELDS off, contexts are dropped and @6 goes out. */
@@ -1414,10 +1538,23 @@ export function commentsActForEmission(act: JobCommentsAct | JobContextCommentsA
1414
1538
  return schema === JOB_COMMENTS_ACT_SCHEMA ? parseCommentsAct(next) : parseContextCommentsAct(next);
1415
1539
  }
1416
1540
 
1417
- function decodeCommentsAct(raw: unknown, withContext: boolean): JobCommentsAct | JobContextCommentsAct {
1541
+ /** A writer must opt in to the Create pin gate before it can project mesh evidence. */
1542
+ export function meshEditsActForEmission(act: JobCommentsAct | (Extract<JobCommentsAct, {kind: 'review-verdict'}> & {
1543
+ readonly value: {readonly meshEdits: readonly JobMeshEdit[]};
1544
+ }), emitMeshEdits: boolean): JobCommentsAct | Extract<JobAct, {schema: typeof JOB_MESH_EDITS_ACT_SCHEMA}> {
1545
+ if (!Object.hasOwn(act.value, 'meshEdits')) {
1546
+ parseCommentsAct(act);
1547
+ return act;
1548
+ }
1549
+ if (!emitMeshEdits) throw new JobError('JOB_ACT_KIND_DISABLED');
1550
+ return parseMeshEditsAct({...act, schema: JOB_MESH_EDITS_ACT_SCHEMA}) as Extract<JobAct, {schema: typeof JOB_MESH_EDITS_ACT_SCHEMA}>;
1551
+ }
1552
+
1553
+ function decodeCommentsAct(raw: unknown, schema: JobCommentsAct['schema'] | JobContextCommentsAct['schema'] | JobMeshEditsAct['schema']):
1554
+ JobCommentsAct | JobContextCommentsAct | JobMeshEditsAct {
1418
1555
  return asCode(() => {
1419
1556
  const item = commentsObject(raw, ['schema', 'actId', 'jobId', 'askId', 'publicationId', 'kind', 'authority', 'at', 'source', 'value'], ['still']);
1420
- if (item.schema !== (withContext ? JOB_COMMENT_CONTEXT_ACT_SCHEMA : JOB_COMMENTS_ACT_SCHEMA)) throw new JobError('JOB_ACT_INVALID');
1557
+ if (item.schema !== schema) throw new JobError('JOB_ACT_INVALID');
1421
1558
  for (const key of ['actId', 'jobId', 'askId', 'publicationId']) jobId(item[key]);
1422
1559
  parseHumanAuthority(item.authority, 'JOB_ACT_INVALID');
1423
1560
  if (typeof item.at !== 'string' || !Number.isFinite(Date.parse(item.at))) throw new JobError('JOB_ACT_INVALID');
@@ -1429,8 +1566,9 @@ function decodeCommentsAct(raw: unknown, withContext: boolean): JobCommentsAct |
1429
1566
  };
1430
1567
  const keys = typeof item.kind === 'string' && Object.hasOwn(fields, item.kind) ? fields[item.kind] : undefined;
1431
1568
  if (!keys) throw new JobError('JOB_ACT_INVALID');
1432
- const value = commentsObject(item.value, keys);
1433
- const comments = withContext ? decodeComments(value.comments, source, true) : parseComments(value.comments, source);
1569
+ const at8 = schema === JOB_MESH_EDITS_ACT_SCHEMA;
1570
+ const value = commentsObject(item.value, keys, at8 && item.kind === 'review-verdict' ? ['meshEdits'] : []);
1571
+ const comments = schema === JOB_COMMENTS_ACT_SCHEMA ? parseComments(value.comments, source) : decodeComments(value.comments, source, true);
1434
1572
  if (comments.some(comment => comment.anchor && 'side' in comment.anchor)) throw new JobError('JOB_ACT_INVALID');
1435
1573
  if ((comments as readonly JobContextComment[]).some(comment => comment.context?.subject &&
1436
1574
  comment.context.subject.ask.kind !== item.kind)) throw new JobError('JOB_ACT_INVALID');
@@ -1456,13 +1594,22 @@ function decodeCommentsAct(raw: unknown, withContext: boolean): JobCommentsAct |
1456
1594
  if ('record' in source) validateRecordAskSubject(item.kind === 'checkpoint' ? {kind: item.kind, checkpointId: value.checkpointId} :
1457
1595
  {kind: item.kind, stage: value.stage}, source);
1458
1596
  const rig = item.kind === 'review-verdict' && value.stage === 'rig-review';
1597
+ let meshEdits: readonly JobMeshEdit[] | undefined;
1598
+ if (at8 && Object.hasOwn(value, 'meshEdits')) {
1599
+ if (!rig || value.verdict !== 'changes-requested') throw new JobError('JOB_ACT_INVALID');
1600
+ meshEdits = parseMeshEdits(value.meshEdits);
1601
+ }
1602
+ if (at8 && item.kind === 'review-verdict' && value.verdict === 'changes-requested' && !comments.length && !meshEdits) {
1603
+ throw new JobError('JOB_ACT_INVALID');
1604
+ }
1459
1605
  if (rig) {
1460
1606
  const still = commentsObject(item.still, ['path', 'sha256', 'camera', 'frame'], ['animation']);
1461
1607
  if (still.path !== jobSha(still.sha256) + '.png' || still.camera !== 'fixed' ||
1462
1608
  (still.frame === 'setup' ? 'animation' in still : typeof still.frame !== 'number' || !Number.isFinite(still.frame) ||
1463
1609
  still.frame < 0 || typeof still.animation !== 'string' || !still.animation)) throw new JobError('JOB_ACT_INVALID');
1464
1610
  } else if ('still' in item) throw new JobError('JOB_ACT_INVALID');
1465
- return {...structuredClone(item), source, value: {...value, comments}} as unknown as JobCommentsAct | JobContextCommentsAct;
1611
+ return {...structuredClone(item), source, value: {...value, comments, ...(meshEdits ? {meshEdits} : {})}} as unknown as
1612
+ JobCommentsAct | JobContextCommentsAct | JobMeshEditsAct;
1466
1613
  }, 'JOB_ACT_INVALID');
1467
1614
  }
1468
1615
 
@@ -1491,12 +1638,16 @@ export async function jobBody(request: Request, maximum = jobBodyLimit): Promise
1491
1638
  chunks.push(value);
1492
1639
  }
1493
1640
  const value = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks)));
1494
- const hasCommentImages = ['parts-verdict', 'review-verdict', 'checkpoint', 'signoff', 'reopen'].includes(value?.kind) &&
1495
- /"png":"data:image\/png;base64,/.test(JSON.stringify(value?.value));
1496
- const rigCapture = value?.kind === 'review-verdict' && value?.value?.stage === 'rig-review' && value.capture;
1497
- if (size > jobBodyLimit && !(maximum > jobBodyLimit && (rigCapture || hasCommentImages))) {
1641
+ if (value?.value != null && Object.hasOwn(value.value, 'meshEdits') &&
1642
+ Buffer.byteLength(canonicalJson(value.value.meshEdits)) > jobBodyLimit) {
1498
1643
  throw new JobError('JOB_BODY_LIMIT');
1499
1644
  }
1645
+ if (size > jobBodyLimit) {
1646
+ const hasCommentImages = ['parts-verdict', 'review-verdict', 'checkpoint', 'signoff', 'reopen'].includes(value?.kind) &&
1647
+ /"png":"data:image\/png;base64,/.test(JSON.stringify(value?.value));
1648
+ const rigCapture = value?.kind === 'review-verdict' && value?.value?.stage === 'rig-review' && value.capture;
1649
+ if (!(maximum > jobBodyLimit && (rigCapture || hasCommentImages))) throw new JobError('JOB_BODY_LIMIT');
1650
+ }
1500
1651
  return value;
1501
1652
  } catch (error) {
1502
1653
  void reader.cancel().catch(() => {});