@rig-c/review 4.6.0 → 4.8.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-front.ts CHANGED
@@ -5,13 +5,15 @@ import {checkpointEvidenceMetadata, readCheckpointEvidenceBytes} from './job-che
5
5
  import { JOB_API_SCHEMA, JOB_ACT_SCHEMA, type JobErrorCode, type JobHostPorts, type JobId, type JobPublicationMode, type JobResult, type JobReviewerBinding } from './job-contract.ts';
6
6
  import { createJobHostPorts, jobBody, jobHash, jobId, jobObject, jobPartsEnumeratorVersion } from './job-api.ts';
7
7
  import { JobSession } from './job-session.ts';
8
- import { assertJobRoot, assertRetainedSnapshotIntact, captureJobRoot, planTextMetadata, isRetainedRecordSource, loadRetainedJobReview, type JobRootIdentity } from './job-source.ts';
8
+ import { assertJobRoot, assertRetainedSnapshotIntact, captureJobRoot, planTextMetadata, isRetainedRecordSource, loadRetainedJobReview, loadRetainedRecordRig, readPreviousDraftBytes, type JobRootIdentity } from './job-source.ts';
9
+ import { checkedPath } from './interview-project.ts';
9
10
  import type { JobWorkerOptions } from './job-worker.ts';
10
11
  import { JobError, JobStore, jobCropReferences } from './job-store.ts';
11
12
  import { safeFile, packagePath, type ReviewPackage } from './manifest.ts';
12
13
  import { serveReference, assertReviewUnchanged } from './reference.ts';
13
14
  import {preparePartsComment} from './parts-comment-crops.ts';
14
- import { loadPartsView, partsViewJson, partsDifference, servedImage, type PartsViewPackage } from './parts-view.ts';
15
+ import type { DifferenceRaster } from './parts-comparison.ts';
16
+ import { loadPartsView, partsViewJson, partsDifference, previousDraftDifference, servedImage, type PartsViewPackage } from './parts-view.ts';
15
17
  import { destinationDirectory, DestinationDirectoryError } from './destination-directory.ts';
16
18
  import { dirname, extname, isAbsolute, join, relative, sep } from 'node:path';
17
19
  import { constants, openSync, closeSync, readSync, fstatSync, lstatSync, statSync, type Stats } from 'node:fs';
@@ -258,9 +260,60 @@ export function retainedPublicationRoutes(session: JobSession) {
258
260
  const sealedFile = async (relativePath: string) => {
259
261
  const seal = retained.seals.find(file => file.path === relativePath);
260
262
  if (!seal) return failure('JOB_SOURCE_UNRETAINABLE', 404);
263
+ let literal: string | undefined;
264
+ if (isRetainedRecordSource(retained)) {
265
+ try {literal = checkedPath(retained.snapshotRoot, relativePath);}
266
+ catch {return failure('JOB_SOURCE_UNRETAINABLE', 404);}
267
+ }
261
268
  const file = await safeFile(retained.snapshotRoot, relativePath);
269
+ if (literal !== undefined && literal !== file)
270
+ return failure('JOB_SOURCE_UNRETAINABLE', 404);
262
271
  return serveReference(request, file, seal.sha256, headers);
263
272
  };
273
+ const reviewMetadata = (review: ReviewPackage | null) => json({
274
+ ...checkpointEvidenceMetadata(retained.snapshotRoot, retained.source.checkpointEvidence),
275
+ ...(isRetainedRecordSource(retained) ? {recordSource: retained.source} : {}),
276
+ sourceHash: retained.source.sourceHash,
277
+ assetsBase: display.routes.assetsBase,
278
+ ...(review ? {
279
+ manifest: review.manifest,
280
+ reviewedSource: review.reviewedSource,
281
+ initialAnimation: null,
282
+ setsHash: review.setsHash,
283
+ direction: review.direction && {...review.direction, ...(retained.source.selector?.kind==='post'?{postVersion:retained.source.selector.version}:{})},
284
+ scene: review.scene,
285
+ referenceHashes: review.referenceHashes,
286
+ sourcePainting: review.sourcePainting && {...review.sourcePainting, url: '/review-painting'},
287
+ } : {}),
288
+ feedbackCatalog: review?.feedbackCatalog ?? {slots: null},
289
+ capabilities: {playback: !!review?.manifest.model,
290
+ interview: questions.length > 0 || (retained.interview?.records.length ?? 0) > 0 ||
291
+ (retained.interview?.diagnostics.length ?? 0) > 0,
292
+ preRig: retained.source.selector?.kind === 'draft', modeling: false, motion: false, feedback: true, audio: false},
293
+ });
294
+ const interviewMetadata = (rigPicture = false) => {
295
+ const interview = isRetainedRecordSource(retained) ? undefined :
296
+ retained.interview !== undefined ? retained.interview : display.publication.interview;
297
+ return json({
298
+ questions: questions.map(question => ({...question,
299
+ ...(rigPicture && question.missingPicture === 'rig' ? {missingPicture: undefined} : {}),
300
+ images: question.images.map((image, index) => ({name: image.name,
301
+ url: `/api/interview/image/${question.ref.sha256}/${index}`})),
302
+ })),
303
+ ...(interview === undefined ? {} : {interview}),
304
+ });
305
+ };
306
+ const interview = /^api\/interview\/image\/([a-f0-9]{64})\/(0|[1-9]\d*)$/.exec(path);
307
+ const interviewImage = (match: RegExpExecArray) => {
308
+ const image = retained.questions.find(question => question.ref.sha256 === match[1])?.images[Number(match[2])];
309
+ return image ? sealedFile(image.ref.path) : failure('JOB_SOURCE_UNRETAINABLE', 404);
310
+ };
311
+ const reviewAsset = (review: ReviewPackage | null) => {
312
+ if (!review) return failure('JOB_SOURCE_UNRETAINABLE', 404);
313
+ const asset = packagePath(decodeURIComponent(path.slice('assets/'.length)));
314
+ if (!review.files.has(asset)) return failure('JOB_SOURCE_UNRETAINABLE', 404);
315
+ return sealedFile(relative(retained.snapshotRoot, join(review.root, asset)).split('\\').join('/'));
316
+ };
264
317
  const evidenceRoute = /^api\/checkpoint-evidence\/([A-Za-z0-9][A-Za-z0-9._-]*)\/(table|tiles\/(0|[1-9]\d*))$/.exec(path);
265
318
  if (evidenceRoute) {
266
319
  const packet = retained.source.checkpointEvidence?.find(item => item.checkpointId === evidenceRoute[1]);
@@ -296,36 +349,22 @@ export function retainedPublicationRoutes(session: JobSession) {
296
349
  const file = servedImage(parts, image[1] as 'image'|'page', Number(image[2]));
297
350
  return file ? await sealedFile(relative(retained.snapshotRoot,file).split('\\').join('/')) : failure('JOB_SOURCE_UNRETAINABLE',404);
298
351
  }
299
- if (path === 'api/review') {
300
- return json({
301
- ...checkpointEvidenceMetadata(retained.snapshotRoot, retained.source.checkpointEvidence),
302
- recordSource: retained.source,
303
- sourceHash: retained.source.sourceHash,
304
- assetsBase: display.routes.assetsBase,
305
- capabilities: {
306
- playback: false,
307
- interview: retained.questions.length > 0,
308
- preRig: false,
309
- modeling: false,
310
- motion: false,
311
- feedback: true,
312
- audio: false,
313
- },
314
- feedbackCatalog: {slots: null},
315
- });
316
- }
317
- if (path === 'api/interview') {
318
- return json({questions: questions.map(question => ({...question,
319
- images: question.images.map((image, index) => ({name: image.name,
320
- url: `/api/interview/image/${question.ref.sha256}/${index}`})),
321
- }))});
322
- }
323
- const interview = /^api\/interview\/image\/([a-f0-9]{64})\/(0|[1-9]\d*)$/.exec(path);
324
- if (interview) {
325
- const image = retained.questions.find(question => question.ref.sha256 === interview[1])?.images[Number(interview[2])];
326
- if (!image) return failure('JOB_SOURCE_UNRETAINABLE', 404);
327
- return await sealedFile(image.ref.path);
352
+ if (path === 'api/review' || path === 'api/interview' || path.startsWith('assets/')) {
353
+ let review: ReviewPackage | null = null;
354
+ if (!question) {
355
+ let pending = views.get(publicationId);
356
+ if (!pending) {
357
+ pending = loadRetainedRecordRig(retained).then(review => ({review, parts: null}));
358
+ views.set(publicationId, pending);
359
+ }
360
+ ({review} = await pending);
361
+ }
362
+ if (path === 'api/review') return reviewMetadata(review);
363
+ if (path === 'api/interview') return interviewMetadata(!!review);
364
+ try {return await reviewAsset(review);}
365
+ catch {return failure('JOB_SOURCE_UNRETAINABLE', 404);}
328
366
  }
367
+ if (interview) return await interviewImage(interview);
329
368
  return failure('JOB_REQUEST_INVALID', 404);
330
369
  }
331
370
  let pending = views.get(publicationId);
@@ -368,43 +407,9 @@ export function retainedPublicationRoutes(session: JobSession) {
368
407
  if (retained.checkpointEvidencePackageHash !== undefined && retained.checkpointEvidencePackageHash !== review.sourceHash) {
369
408
  throw new JobError('JOB_SOURCE_MISMATCH');
370
409
  }
371
- if (path === 'api/review') {
372
- return json({
373
- ...checkpointEvidenceMetadata(retained.snapshotRoot, retained.source.checkpointEvidence),
374
- manifest: review.manifest,
375
- sourceHash: retained.source.sourceHash,
376
- reviewedSource: review.reviewedSource,
377
- initialAnimation: null,
378
- setsHash: review.setsHash,
379
- direction: review.direction && {...review.direction, ...(retained.source.selector?.kind==='post'?{postVersion:retained.source.selector.version}:{})},
380
- scene: review.scene,
381
- referenceHashes: review.referenceHashes,
382
- sourcePainting: review.sourcePainting && {...review.sourcePainting, url: '/review-painting'},
383
- feedbackCatalog: review.feedbackCatalog,
384
- assetsBase: display.routes.assetsBase,
385
- capabilities: {playback: !!review.manifest.model,
386
- interview: retained.questions.length > 0 ||
387
- (retained.interview?.records.length ?? 0) > 0 ||
388
- (retained.interview?.diagnostics.length ?? 0) > 0,
389
- preRig: retained.source.selector?.kind === 'draft', modeling: false, motion: false, feedback: true, audio: false},
390
- });
391
- }
392
- if (path === 'api/interview') {
393
- const interview = retained.interview !== undefined ? retained.interview : display.publication.interview;
394
- return json({
395
- questions: questions.map(question => ({...question,
396
- images: question.images.map((image, index) => ({name: image.name,
397
- url: `/api/interview/image/${question.ref.sha256}/${index}`})),
398
- })),
399
- ...(interview === undefined ? {} : {interview}),
400
- });
401
- }
402
- const interview = /^api\/interview\/image\/([a-f0-9]{64})\/(0|[1-9]\d*)$/.exec(path);
403
- if (interview) {
404
- const image = retained.questions.find(question => question.ref.sha256 === interview[1])?.images[Number(interview[2])];
405
- if (!image) return failure('JOB_SOURCE_UNRETAINABLE', 404);
406
- return await sealedFile(image.ref.path);
407
- }
410
+ if (path === 'api/review') return reviewMetadata(review);
411
+ if (path === 'api/interview') return interviewMetadata();
412
+ if (interview) return await interviewImage(interview);
408
413
  if (crop) {
409
414
  if (!parts) return failure('JOB_SOURCE_UNRETAINABLE', 409);
410
415
  if (request.headers.get('origin') !== new URL(request.url).origin)
@@ -417,7 +422,9 @@ export function retainedPublicationRoutes(session: JobSession) {
417
422
  assertRetainedSnapshotIntact(retained.snapshotRoot, retained.seals);
418
423
  let comment;
419
424
  try {
420
- comment = await preparePartsComment(parts, raw, false, {sourceHash: retained.source.sourceHash});
425
+ comment = await preparePartsComment(parts, raw, false, {
426
+ sourceHash: retained.source.sourceHash, previousDraft: retained.source.previousDraft,
427
+ });
421
428
  } catch (error) {
422
429
  if (error instanceof JobError ||
423
430
  error instanceof Error && error.message.startsWith('PARTS_COMMENT_STALE_SOURCE:')) throw error;
@@ -430,16 +437,34 @@ export function retainedPublicationRoutes(session: JobSession) {
430
437
  }
431
438
  if (path === 'api/stage-parts') {
432
439
  if (!parts) return failure('JOB_SOURCE_UNRETAINABLE', 409);
433
- return json({...partsViewJson(parts, {verdict: null, stale: null}), sourceHash: retained.source.sourceHash,
440
+ return json({...partsViewJson(parts, {verdict: null, stale: null}, retained.source.previousDraft?.draft), sourceHash: retained.source.sourceHash,
434
441
  inspectionSourceHash: retained.source.sourceHash, readOnly: true});
435
442
  }
436
443
  const difference=/^api\/stage-parts\/difference\/(0|[1-9]\d*)$/.exec(path);
437
444
  if(difference&&parts){
438
- const url=new URL(request.url),threshold=url.searchParams.get('threshold'),footprints=url.searchParams.get('footprints');
445
+ const query=new URL(request.url).searchParams,threshold=query.get('threshold'),footprints=query.get('footprints');
446
+ const operand=query.get('operand');
439
447
  if(!threshold||!/^\d{1,3}$/.test(threshold)||!['true','false'].includes(footprints??''))return failure('JOB_REQUEST_INVALID',400);
448
+ // The existing route's 0 address plus this operand names the whole canvas.
449
+ if(operand!==null&&(operand!=='previous-draft'||difference[1]!=='0'||footprints!=='false'||query.size!==3))
450
+ return failure('JOB_REQUEST_INVALID',400);
440
451
  try {
441
- const raster=await partsDifference(parts,Number(difference[1]),Number(threshold),footprints==='true'),png=new PNG({width:raster.width,height:raster.height});png.data=Buffer.from(raster.data);
442
- return new Response(request.method==='HEAD'?null:new Uint8Array(PNG.sync.write(png)),{headers:{...headers,'Content-Type':'image/png','X-Difference-Count':String(raster.count),'X-Difference-Covered':String(raster.covered),'X-Difference-Compared':String(raster.compared)}});
452
+ const previous=operand==='previous-draft'?retained.source.previousDraft:undefined;
453
+ if(operand!==null&&!previous)return failure('PARTS_DIFFERENCE_UNAVAILABLE',400);
454
+ const responseHeaders:Record<string,string>={...headers,'Content-Type':'image/png'};
455
+ let raster:DifferenceRaster;
456
+ if(previous){
457
+ raster=previousDraftDifference(parts,readPreviousDraftBytes(retained.snapshotRoot,previous.composites.current,'current'),
458
+ readPreviousDraftBytes(retained.snapshotRoot,previous.composites.previous,'previous'),Number(threshold));
459
+ }else{
460
+ const painting=await partsDifference(parts,Number(difference[1]),Number(threshold),footprints==='true');
461
+ raster=painting;
462
+ responseHeaders['X-Difference-Count']=String(painting.count);
463
+ responseHeaders['X-Difference-Covered']=String(painting.covered);
464
+ responseHeaders['X-Difference-Compared']=String(painting.compared);
465
+ }
466
+ const png=new PNG({width:raster.width,height:raster.height});png.data=Buffer.from(raster.data);
467
+ return new Response(request.method==='HEAD'?null:new Uint8Array(PNG.sync.write(png)),{headers:responseHeaders});
443
468
  } catch (error) {
444
469
  const code = error instanceof Error ? /^(PARTS_DIFFERENCE_UNAVAILABLE|PARTS_DIFFERENCE_PNG):/.exec(error.message)?.[1] : undefined;
445
470
  if (code) return failure(code, 400);
@@ -455,11 +480,7 @@ export function retainedPublicationRoutes(session: JobSession) {
455
480
  if (path === 'review-painting' && review.sourcePainting && review.handoff?.source) {
456
481
  return await sealedFile(relative(retained.snapshotRoot, review.handoff.source).split('\\').join('/'));
457
482
  }
458
- if (path.startsWith('assets/')) {
459
- const asset = packagePath(decodeURIComponent(path.slice('assets/'.length)));
460
- if (!review.files.has(asset)) return failure('JOB_SOURCE_UNRETAINABLE', 404);
461
- return await sealedFile(relative(retained.snapshotRoot, join(review.root, asset)).split('\\').join('/'));
462
- }
483
+ if (path.startsWith('assets/')) return await reviewAsset(review);
463
484
  return failure('JOB_REQUEST_INVALID', 404);
464
485
  });
465
486
  } catch (error) {
@@ -467,6 +488,7 @@ export function retainedPublicationRoutes(session: JobSession) {
467
488
  error instanceof Error && error.message.startsWith('PARTS_COMMENT_STALE_SOURCE:')
468
489
  ? 'PARTS_COMMENT_STALE_SOURCE' : 'JOB_SOURCE_MISMATCH';
469
490
  const message = error instanceof JobError && (/^(CHECKPOINT_EVIDENCE|PLAN_TEXT)_[A-Z_]+$/.test(error.message) ||
491
+ /^PREVIOUS_DRAFT_[A-Z_]+(?: |$)/.test(error.message) ||
470
492
  error.code === 'JOB_SOURCE_UNRETAINABLE' && error.message.startsWith('snapshot reload '))
471
493
  ? error.message : undefined;
472
494
  return failure(code, errorStatus[code as JobErrorCode] ?? 409, undefined, message);
package/src/job-host.ts CHANGED
@@ -21,19 +21,20 @@ export type {
21
21
  JobRootIdentity,
22
22
  } from './job-source.ts';
23
23
  export {parseRecordAct} from './job-api.ts';
24
- export {parseCommentsAct, parseContextCommentsAct} from './job-api.ts';
24
+ export {parseCommentsAct, parseContextCommentsAct, parseMeshEditsAct} from './job-api.ts';
25
25
  export {projectComments} from './stage-comment.ts';
26
26
  export {parseCommentsSession} from './session.ts';
27
27
  export {parseCommentsCompareSession} from './compare-session.ts';
28
28
  export {parseCommentsPartsVerdict} from './parts-view.ts';
29
29
  export {projectSelectedCommentsFeedback} from './feedback-export.ts';
30
30
  export {
31
- JOB_COMMENTS_ACT_SCHEMA, JOB_COMMENT_CONTEXT_ACT_SCHEMA, REVIEW_COMMENTS_SESSION_SCHEMA,
31
+ JOB_COMMENTS_ACT_SCHEMA, JOB_COMMENT_CONTEXT_ACT_SCHEMA, JOB_MESH_EDITS_ACT_SCHEMA, REVIEW_COMMENTS_SESSION_SCHEMA,
32
32
  REVIEW_COMMENTS_COMPARE_SESSION_SCHEMA, PARTS_COMMENTS_VERDICT_SCHEMA,
33
33
  } from './job-contract.ts';
34
34
  export type {
35
35
  JobComment, JobCommentAnchor, JobCommentFeedbackAnchor, JobCommentPartsAnchor, JobCommentImageAnchor,
36
36
  JobCommentsAct, JobCommentsActValues, ReviewCommentsSession,
37
+ JobMeshEditValue, JobMeshEdit, JobMeshEditsAct,
37
38
  JobCommentContext, JobContextComment, JobContextCommentsAct, CompareCommentsSession, PartsCommentsVerdict,
38
39
  } from './job-contract.ts';
39
40
  export {prepareJobRecordAct} from './job-act.ts';
@@ -45,6 +46,7 @@ export {
45
46
  JOB_RECORD_ACT_SCHEMA,
46
47
  JOB_RECORD_READER_ID,
47
48
  JOB_PARTS_ENUMERATOR_RANGE,
49
+ JOB_PREVIOUS_DRAFT_SCHEMA,
48
50
  JOB_ENABLED_ACT_KINDS,
49
51
  JOB_RESERVED_ACT_KINDS,
50
52
  JOB_PLAN_BOUND_SIGNOFF_STAGES,
@@ -55,6 +57,8 @@ export type {
55
57
  ActV3,
56
58
  AgentRequestV3,
57
59
  ApiResponseV3,
60
+ AskBatchRequestV3,
61
+ AskBatchValueV3,
58
62
  AskRequestV3,
59
63
  CloseRequestV3,
60
64
  DisplayPublicationV3,
@@ -77,6 +81,7 @@ export type {
77
81
  JobPartsManifestPath,
78
82
  JobPartImagePath,
79
83
  JobPartsIdentity,
84
+ JobPreviousDraft,
80
85
  JobPartsRole,
81
86
  JobPartsFileReference,
82
87
  JobPartsEnumerator,
@@ -119,6 +124,8 @@ export type {
119
124
  JobPublishRequestV3,
120
125
  JobAskRequest,
121
126
  JobAskRequestV3,
127
+ JobAskBatchRequestV3,
128
+ JobAskBatchValueV3,
122
129
  JobNextRequest,
123
130
  JobNextRequestV3,
124
131
  JobCloseRequest,
@@ -0,0 +1,37 @@
1
+ import {exactObject, jobId, jobSha, parseFileRow} from './job-api.ts';
2
+ import {JOB_PREVIOUS_DRAFT_SCHEMA, type JobFileIdentity, type JobPreviousDraft, type JobSelector} from './job-contract.ts';
3
+ import {JobError} from './job-store.ts';
4
+
5
+ function parsePreviousDraft(value: unknown): JobPreviousDraft {
6
+ try {
7
+ const item = exactObject(value, ['schema', 'draft', 'composites'], 'JOB_SOURCE_MISMATCH', ['diff']);
8
+ if (item.schema !== JOB_PREVIOUS_DRAFT_SCHEMA) throw new Error('schema');
9
+ const draft = exactObject(item.draft, ['id', 'revision'], 'JOB_SOURCE_MISMATCH');
10
+ const composites = exactObject(item.composites, ['current', 'previous'], 'JOB_SOURCE_MISMATCH');
11
+ return {schema: JOB_PREVIOUS_DRAFT_SCHEMA, draft: {id: jobId(draft.id), revision: jobSha(draft.revision)},
12
+ composites: {current: parseFileRow(composites.current, 'JOB_SOURCE_MISMATCH'),
13
+ previous: parseFileRow(composites.previous, 'JOB_SOURCE_MISMATCH')},
14
+ ...('diff' in item ? {diff: parseFileRow(item.diff, 'JOB_SOURCE_MISMATCH')} : {})};
15
+ } catch {
16
+ throw new JobError('JOB_SOURCE_MISMATCH', 'PREVIOUS_DRAFT_INVALID');
17
+ }
18
+ }
19
+
20
+ /** The decoder checks the declaration. Admission additionally supplies the actual files closure. */
21
+ export function previousDraftFields(holder: object, selector: JobSelector | null,
22
+ files?: readonly JobFileIdentity[]): {previousDraft?: JobPreviousDraft} {
23
+ if (!('previousDraft' in holder)) return {};
24
+ if (selector?.kind !== 'draft') throw new JobError('JOB_SOURCE_MISMATCH', 'PREVIOUS_DRAFT_SELECTOR');
25
+ const previousDraft = parsePreviousDraft(holder.previousDraft);
26
+ if (previousDraft.draft.id === selector.id) throw new JobError('JOB_SOURCE_MISMATCH', 'PREVIOUS_DRAFT_SELF');
27
+ if (Buffer.byteLength(JSON.stringify(previousDraft)) > 4096) {
28
+ throw new JobError('JOB_SOURCE_UNRETAINABLE', 'PREVIOUS_DRAFT_LIMIT operand=declaration');
29
+ }
30
+ const operands = {...previousDraft.composites, diff: previousDraft.diff};
31
+ for (const [operand, file] of Object.entries(operands)) {
32
+ if (file && files && !files.some(seal => seal.path === file.path && seal.sha256 === file.sha256)) {
33
+ throw new JobError('JOB_SOURCE_MISMATCH', `PREVIOUS_DRAFT_UNSEALED operand=${operand}`);
34
+ }
35
+ }
36
+ return {previousDraft};
37
+ }
@@ -1,14 +1,14 @@
1
1
  import { randomBytes, randomUUID } from 'node:crypto';
2
2
  import { dirname, isAbsolute, join, relative, sep } from 'node:path';
3
3
  import {
4
- JOB_API_SCHEMA, JOB_API_V3_SCHEMA, JOB_ACT_SCHEMA, JOB_COMMENTS_ACT_SCHEMA, JOB_PARTS_VERDICT_ACT_SCHEMA, JOB_RIG_REVIEW_ACT_SCHEMA, JOB_RECORD_READER_ID, jobStillByteLimit, jobActDeliveryLimit, JOB_CAPABILITIES, JOB_CAPABILITIES_V3, JOB_ENABLED_ACT_KINDS,
4
+ JOB_API_SCHEMA, JOB_API_V3_SCHEMA, JOB_ACT_SCHEMA, JOB_COMMENTS_ACT_SCHEMA, JOB_COMMENT_CONTEXT_ACT_SCHEMA, JOB_MESH_EDITS_ACT_SCHEMA, JOB_PARTS_VERDICT_ACT_SCHEMA, JOB_RIG_REVIEW_ACT_SCHEMA, JOB_RECORD_READER_ID, jobStillByteLimit, jobActDeliveryLimit, JOB_CAPABILITIES, JOB_CAPABILITIES_V3, JOB_ENABLED_ACT_KINDS,
5
5
  type ActV3, type AgentRequestV3, type EventV3, type JobPartsEnumerator, type JobAct, type JobAgentRequest, type JobDisplayAcknowledgment,
6
6
  type JobDisplayPublication, type JobDisplayPublicationV3, type JobDisplayReceipt, type JobEvent, type JobFetchActRequest, type JobFetchActRequestV3,
7
7
  type JobNextValue, type JobPendingAsk, type JobPublication, type JobPublicationMode, type JobReviewerBinding,
8
- type NextValueV3, type PendingAskV3, type PublicationV3, type RecordPublicationReader, type RecordSubject, type StatusV3,
8
+ type JobSubject, type NextValueV3, type PendingAskV3, type PublicationV3, type RecordPublicationReader, type RecordSubject, type StatusV3,
9
9
  } from './job-contract.ts';
10
10
  import { bindJobAsk, bindJobRecordAsk, finalizeJobAct, parseUISubmission, prepareJobRecordAct, prepareJobStill } from './job-act.ts';
11
- import { isRecordSource, parseRecordSource, parseCommentsAct, jobApiSchemaForMode, jobHash, jobPartsEnumeratorVersion, jobWaitLimitMs, requestDigest, sameCapability } from './job-api.ts';
11
+ import { atSubject, isRecordSource, parseRecordSource, parseCommentsAct, parseContextCommentsAct, parseMeshEditsAct, jobApiSchemaForMode, jobHash, jobPartsEnumeratorVersion, jobWaitLimitMs, requestDigest, sameCapability } from './job-api.ts';
12
12
  import {
13
13
  assertStoredCheckpointEvidence, assertJobRoot, assertJobSourceCurrent, assertRetainedSnapshotIntact, captureJobRoot, isRetainedRecordSource, loadRetainedJobReview, prepareJobSource, jobSnapshotHash, removeOwnedJobSnapshot, verifyJobRecordSourceFresh,
14
14
  type JobPublicationReader, type JobRetainedSource, type JobRetainedSourceV3, type JobRootIdentity,
@@ -80,7 +80,7 @@ function assertStoredSchemas(data: JobData): void {
80
80
  assertStoredEvidence(data);
81
81
  }
82
82
 
83
- /** Check only the new extension and its durable copies, including committed replay values. */
83
+ /** Check optional evidence declarations and their durable copies, including committed replay values. */
84
84
  function assertStoredEvidence(data: JobData): void {
85
85
  for (const stored of Object.values(data.publications)) {
86
86
  assertStoredCheckpointEvidence(stored.retained);
@@ -93,7 +93,16 @@ function assertStoredEvidence(data: JobData): void {
93
93
  if (event.type === 'pending') assertStoredEvidenceCopy(event.ask, data);
94
94
  if (event.type === 'act') assertStoredEvidenceCopy(event.act, data);
95
95
  }
96
- for (const replay of Object.values(data.replays)) assertStoredEvidenceCopy(replay.value, data);
96
+ for (const replay of Object.values(data.replays)) {
97
+ // An ask-batch receipt wraps its asks; each one is a durable copy like a single ask's receipt.
98
+ const asks = (replay.value as {asks?: unknown} | null)?.asks;
99
+ if (Array.isArray(asks)) for (const ask of asks) assertStoredEvidenceCopy(ask, data);
100
+ else assertStoredEvidenceCopy(replay.value, data);
101
+ }
102
+ }
103
+
104
+ function hasStoredEvidence(source: object | undefined): boolean {
105
+ return !!source && ('checkpointEvidence' in source || 'previousDraft' in source);
97
106
  }
98
107
 
99
108
  function assertStoredEvidenceCopy(value: unknown, data: JobData): void {
@@ -101,12 +110,16 @@ function assertStoredEvidenceCopy(value: unknown, data: JobData): void {
101
110
  const copy = value as {publicationId: string; source: JobPublication['source'] | PublicationV3['source']};
102
111
  const stored = data.publications[copy.publicationId];
103
112
  const bound = stored?.retained.source;
104
- if (!('source' in value) && !(bound && 'checkpointEvidence' in bound)) return;
113
+ if (!('source' in value) && !hasStoredEvidence(bound)) return;
105
114
  if (!copy.source || typeof copy.source !== 'object' || Array.isArray(copy.source)) throw new JobError('JOB_SOURCE_MISMATCH');
106
- if (!('checkpointEvidence' in copy.source) && !(bound && 'checkpointEvidence' in bound)) return;
115
+ if (!hasStoredEvidence(copy.source) && !hasStoredEvidence(bound)) return;
116
+ const copyDraft = 'previousDraft' in copy.source ? copy.source.previousDraft : undefined;
117
+ const boundDraft = bound && 'previousDraft' in bound ? bound.previousDraft : undefined;
107
118
  if (!bound || copy.source.sourceHash !== bound.sourceHash ||
119
+ ('previousDraft' in copy.source) !== ('previousDraft' in bound) ||
120
+ requestDigest(copyDraft ?? null) !== requestDigest(boundDraft ?? null) ||
108
121
  requestDigest(copy.source.checkpointEvidence ?? null) !== requestDigest(bound.checkpointEvidence ?? null) ||
109
- requestDigest(copy.source.plan) !== requestDigest(bound.plan)) throw new JobError('JOB_SOURCE_MISMATCH');
122
+ !('plan' in copy.source) || requestDigest(copy.source.plan) !== requestDigest(bound.plan)) throw new JobError('JOB_SOURCE_MISMATCH');
110
123
  if (isRecordSource(copy.source)) parseRecordSource(copy.source);
111
124
  }
112
125
 
@@ -412,6 +425,27 @@ export class JobSession {
412
425
  return event;
413
426
  }
414
427
 
428
+ /** The committed head's retained source, re-checked against the work root and its sealed snapshot. */
429
+ private headRetained(data: JobData, publicationId: string): JobRetainedSourceV3 {
430
+ if (data.head !== publicationId) throw new JobError('JOB_ACT_SOURCE_STALE');
431
+ const retained = data.publications[publicationId].retained;
432
+ assertJobSourceCurrent(retained);
433
+ if (isRetainedRecordSource(retained) || hasStoredEvidence(retained.source)) {
434
+ assertRetainedSnapshotIntact(retained.snapshotRoot, retained.seals, retained.snapshotIdentity, 'JOB_SOURCE_UNRETAINABLE');
435
+ }
436
+ return retained;
437
+ }
438
+
439
+ /** Bind one subject to the retained source, store its pending ask and write its `pending` event. */
440
+ private addAsk(data: JobData, publicationId: string, subject: JobSubject | RecordSubject, retained: JobRetainedSourceV3): JobPendingAsk | PendingAskV3 {
441
+ const ask: JobPendingAsk | PendingAskV3 = isRetainedRecordSource(retained)
442
+ ? { askId: randomUUID(), publicationId, subject, source: bindJobRecordAsk(subject, retained), status: 'pending' }
443
+ : { askId: randomUUID(), publicationId, subject, source: bindJobAsk(subject, retained), status: 'pending' };
444
+ data.asks[ask.askId] = ask;
445
+ this.event(data, { type: 'pending', ask });
446
+ return ask;
447
+ }
448
+
415
449
  private notify(): void { for (const listener of this.listeners) listener(); }
416
450
 
417
451
  async execute(input: JobAgentRequest | AgentRequestV3 | JobFetchActRequest | JobFetchActRequestV3, signal: AbortSignal): Promise<unknown> {
@@ -511,6 +545,21 @@ export class JobSession {
511
545
  });
512
546
  }
513
547
  }
548
+ } else if (input.verb === 'ask-batch') {
549
+ // One freshness read for the whole batch; every subject binds and validates against it (#963).
550
+ if (current.data.head !== input.publicationId) throw new JobError('JOB_ACT_SOURCE_STALE');
551
+ const retained = current.data.publications[input.publicationId].retained;
552
+ if (!isRetainedRecordSource(retained)) throw new JobError('JOB_REQUEST_INVALID', 'ask-batch requires a record publication');
553
+ input.subjects.forEach((subject, index) => atSubject(index, () => bindJobRecordAsk(subject, retained)));
554
+ if (!this.options.readRecordPublished) {
555
+ throw new JobError('JOB_SOURCE_UNRETAINABLE', 'Record publication requires a trusted record reader');
556
+ }
557
+ await verifyJobRecordSourceFresh({
558
+ retained,
559
+ readRecordPublished: this.options.readRecordPublished,
560
+ phase: 'ask',
561
+ subjects: input.subjects as readonly RecordSubject[],
562
+ });
514
563
  }
515
564
  if (signal.aborted) throw new JobError('JOB_REQUEST_INVALID', 'Request cancelled');
516
565
  current = this.current();
@@ -523,7 +572,7 @@ export class JobSession {
523
572
  switch (input.verb) {
524
573
  case 'publish': {
525
574
  assertJobSourceCurrent(candidate!);
526
- if (isRetainedRecordSource(candidate!) || candidate!.source.checkpointEvidence) {
575
+ if (isRetainedRecordSource(candidate!) || hasStoredEvidence(candidate!.source)) {
527
576
  assertRetainedSnapshotIntact(
528
577
  candidate!.snapshotRoot,
529
578
  candidate!.seals,
@@ -548,35 +597,17 @@ export class JobSession {
548
597
  break;
549
598
  }
550
599
  case 'ask': {
551
- if (data.head !== input.publicationId) throw new JobError('JOB_ACT_SOURCE_STALE');
552
- const retained = data.publications[input.publicationId].retained;
553
- assertJobSourceCurrent(retained);
554
- if (isRetainedRecordSource(retained) || retained.source.checkpointEvidence) {
555
- assertRetainedSnapshotIntact(
556
- retained.snapshotRoot,
557
- retained.seals,
558
- retained.snapshotIdentity,
559
- 'JOB_SOURCE_UNRETAINABLE',
560
- );
561
- }
562
- const ask: JobPendingAsk | PendingAskV3 = isRetainedRecordSource(retained)
563
- ? {
564
- askId: randomUUID(),
565
- publicationId: input.publicationId,
566
- subject: input.subject,
567
- source: bindJobRecordAsk(input.subject, retained),
568
- status: 'pending',
569
- }
570
- : {
571
- askId: randomUUID(),
572
- publicationId: input.publicationId,
573
- subject: input.subject,
574
- source: bindJobAsk(input.subject, retained),
575
- status: 'pending',
576
- };
577
- data.asks[ask.askId] = ask;
578
- this.event(data, { type: 'pending', ask });
579
- result = ask;
600
+ result = this.addAsk(data, input.publicationId, input.subject, this.headRetained(data, input.publicationId));
601
+ break;
602
+ }
603
+ case 'ask-batch': {
604
+ // One head/source/snapshot re-check, then every ask under its own generation and pending event.
605
+ const retained = this.headRetained(data, input.publicationId);
606
+ const asks = input.subjects.map((subject, index) => {
607
+ if (index > 0) data.generation++;
608
+ return atSubject(index, () => this.addAsk(data, input.publicationId, subject, retained));
609
+ });
610
+ result = { asks };
580
611
  break;
581
612
  }
582
613
  }
@@ -606,7 +637,9 @@ export class JobSession {
606
637
  const storedAct = current.data.acts[actId];
607
638
  if (!storedAct) throw new JobError('JOB_ACT_UNKNOWN');
608
639
  // Validation must not replace the stored representation or reorder its keys.
609
- if ((storedAct as {schema: string}).schema === JOB_COMMENTS_ACT_SCHEMA) parseCommentsAct(storedAct);
640
+ if (storedAct.schema === JOB_COMMENTS_ACT_SCHEMA) parseCommentsAct(storedAct);
641
+ if (storedAct.schema === JOB_COMMENT_CONTEXT_ACT_SCHEMA) parseContextCommentsAct(storedAct);
642
+ if (storedAct.schema === JOB_MESH_EDITS_ACT_SCHEMA) parseMeshEditsAct(storedAct);
610
643
  const still = 'still' in storedAct ? storedAct.still : undefined;
611
644
  const actBytes = Buffer.from(JSON.stringify(storedAct));
612
645
  if (storedAct.schema !== JOB_RIG_REVIEW_ACT_SCHEMA && !still) {
@@ -699,7 +732,9 @@ export class JobSession {
699
732
  const pkg = await loadPartsView(dirname(join(retained.snapshotRoot, retained.source.parts.manifest.path)),
700
733
  {painting: sealedPainting, paintingRoot: retained.snapshotRoot});
701
734
  for (const issue of issues) {
702
- await validateStoredPartsComment(pkg, issue, false, {sourceHash: retained.source.sourceHash});
735
+ await validateStoredPartsComment(pkg, issue, false, {
736
+ sourceHash: retained.source.sourceHash, previousDraft: retained.source.previousDraft,
737
+ });
703
738
  }
704
739
  } catch (error) {
705
740
  if (error instanceof JobError) throw error;
@@ -729,7 +764,7 @@ export class JobSession {
729
764
  if (!ask) throw new JobError('JOB_ASK_INVALID');
730
765
  const retained = fresh.data.publications[input.publicationId].retained;
731
766
  assertJobSourceCurrent(retained);
732
- if (isRetainedRecordSource(retained) || retained.source.checkpointEvidence || input.kind === 'parts-verdict') {
767
+ if (isRetainedRecordSource(retained) || hasStoredEvidence(retained.source) || input.kind === 'parts-verdict') {
733
768
  assertRetainedSnapshotIntact(
734
769
  retained.snapshotRoot,
735
770
  retained.seals,