@rig-c/review 2.7.1 → 2.9.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
@@ -1,12 +1,13 @@
1
1
  /** Disjoint live-job routes. The backend receives the original authenticated Request. */
2
- import { JOB_API_SCHEMA, JOB_ACT_SCHEMA, type JobErrorCode, type JobHostPorts, type JobId, type JobResult, type JobReviewerBinding } from './job-contract.ts';
2
+ import { JOB_API_SCHEMA, JOB_ACT_SCHEMA, type JobErrorCode, type JobHostPorts, type JobId, type JobPublicationMode, type JobResult, type JobReviewerBinding } from './job-contract.ts';
3
3
  import { createJobHostPorts, jobBody, jobHash, jobId, jobObject, jobPartsEnumeratorVersion } from './job-api.ts';
4
4
  import { JobSession } from './job-session.ts';
5
- import { assertJobRoot, captureJobRoot, type JobRootIdentity } from './job-source.ts';
5
+ import { assertJobRoot, assertRetainedSnapshotIntact, captureJobRoot, isRetainedRecordSource, type JobRootIdentity } from './job-source.ts';
6
6
  import type { JobWorkerOptions } from './job-worker.ts';
7
7
  import { JobError, JobStore } from './job-store.ts';
8
8
  import { loadReview, safeFile, packagePath, type ReviewPackage } from './manifest.ts';
9
9
  import { serveReference, assertReviewUnchanged } from './reference.ts';
10
+ import {preparePartsComment} from './parts-comment-crops.ts';
10
11
  import { loadPartsView, partsViewJson, servedImage, type PartsViewPackage } from './parts-view.ts';
11
12
  import { destinationDirectory, DestinationDirectoryError } from './destination-directory.ts';
12
13
  import { dirname, isAbsolute, join, relative, sep } from 'node:path';
@@ -22,8 +23,60 @@ const headers = {
22
23
  'Referrer-Policy': 'no-referrer',
23
24
  'Content-Security-Policy': "default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' blob: data:; media-src 'self' blob:; connect-src 'self'; base-uri 'none'; frame-ancestors 'none'; form-action 'none'",
24
25
  };
25
- function failure(code: string, status: number): Response {
26
- return Response.json({ ok: false, error: { code, message: code } }, { status, headers });
26
+ interface CropFailureDiagnostic {
27
+ field: string;
28
+ expected: string | number[];
29
+ received: string | number[];
30
+ }
31
+ function failure(code: string, status: number, diagnostic?: CropFailureDiagnostic): Response {
32
+ return Response.json({ ok: false, error: { code, message: code, ...(diagnostic ? {diagnostic} : {}) } }, { status, headers });
33
+ }
34
+
35
+ /** Explain an existing rejection without returning body text, filesystem paths or PNG bytes. */
36
+ function cropFailureDiagnostic(error: unknown, raw: unknown): CropFailureDiagnostic {
37
+ const message = error instanceof Error ? error.message : '';
38
+ const invariants: Record<string, [string, string]> = {
39
+ 'PARTS_COMMENT_RIG_REGION: rig region must be exact placement plus image region': ['rigRegion', 'exact placement plus imageRegion'],
40
+ 'PARTS_COMMENT_OUT_OF_BOUNDS: region exceeds original image': ['imageRegion', 'inside original image bounds'],
41
+ 'PARTS_COMMENT_OUT_OF_BOUNDS: region exceeds union of issue parts': ['rigRegion', 'inside union of bound parts'],
42
+ 'PARTS_CAMERA_RANGE: native zoom below fit/1 minimum': ['view.camera.zoom', 'at least min(fit, 1)'],
43
+ 'PARTS_CAMERA_RANGE: native scale or camera extent': ['view.camera', 'bounded positive zoom and viewport'],
44
+ 'PARTS_COMMENT_IMAGE_SIZE: original dimensions differ from placement': ['part.image.dimensions', 'equal retained placement dimensions'],
45
+ 'PARTS_COMMENT_CROP_INVALID: bounded content-addressed crop': ['crop', 'bounded content-addressed PNG metadata'],
46
+ 'COMMENT_CROP_INVALID: bounded content-addressed PNG required': ['crop', 'bounded content-addressed PNG'],
47
+ 'COMMENT_CROP_INVALID: expected noninterlaced 8-bit RGB/RGBA': ['crop.png.format', 'noninterlaced 8-bit RGB/RGBA'],
48
+ 'COMMENT_CROP_INVALID: truncated PNG chunk': ['crop.png.chunks', 'complete chunks'],
49
+ 'COMMENT_CROP_INVALID: PNG chunk length': ['crop.png.chunk.length', 'inside PNG byte bounds'],
50
+ 'COMMENT_CROP_INVALID: PNG chunk CRC': ['crop.png.chunk.crc', 'matching CRC'],
51
+ 'COMMENT_CROP_INVALID: static PNG required': ['crop.png.animation', 'static PNG'],
52
+ 'COMMENT_CROP_INVALID: PNG end': ['crop.png.end', 'final empty IEND'],
53
+ 'COMMENT_CROP_INVALID: PNG data/end missing': ['crop.png.data', 'IDAT and IEND present'],
54
+ 'COMMENT_CROP_INVALID: bounded PNG data decode': ['crop.png.data', 'bounded decodable scanlines'],
55
+ 'COMMENT_CROP_INVALID: PNG scanlines': ['crop.png.scanlines', 'exact dimensions and valid filters'],
56
+ 'COMMENT_CROP_PATH: existing crop is not the bound regular PNG': ['crop.storage', 'regular file with matching SHA-256'],
57
+ 'COMMENT_CROP_PATH: regular state directory required': ['crop.storage', 'regular state directory'],
58
+ };
59
+ // Inspect metadata only after the existing validator reports this exact invariant.
60
+ if (message === 'COMMENT_CROP_INVALID: PNG signature, dimensions or SHA-256 differ' &&
61
+ raw && typeof raw === 'object' && 'crop' in raw) {
62
+ const crop = raw.crop as {png?: unknown; sha256?: unknown; width?: unknown; height?: unknown} | null;
63
+ if (crop && typeof crop.png === 'string' && crop.png.length <= 200000 &&
64
+ typeof crop.sha256 === 'string' && /^[a-f0-9]{64}$/.test(crop.sha256)) {
65
+ const bytes = Buffer.from(crop.png.slice('data:image/png;base64,'.length), 'base64');
66
+ const hash = jobHash(bytes);
67
+ if (hash !== crop.sha256) return {field: 'crop.sha256', expected: crop.sha256, received: hash};
68
+ if (bytes.length >= 24 && bytes.subarray(0, 8).toString('hex') === '89504e470d0a1a0a' &&
69
+ typeof crop.width === 'number' && typeof crop.height === 'number' &&
70
+ (crop.width !== bytes.readUInt32BE(16) || crop.height !== bytes.readUInt32BE(20))) {
71
+ return {field: 'crop.dimensions', expected: [crop.width, crop.height],
72
+ received: [bytes.readUInt32BE(16), bytes.readUInt32BE(20)]};
73
+ }
74
+ }
75
+ return {field: 'crop.png.signature', expected: 'PNG signature and IHDR', received: 'invalid'};
76
+ }
77
+ const invariant = Object.hasOwn(invariants, message) ? invariants[message] : undefined;
78
+ return invariant ? {field: invariant[0], expected: invariant[1], received: 'rejected by existing validator'} :
79
+ {field: 'partsComment.prepare', expected: 'valid source-bound crop and writable evidence state', received: 'unclassified rejection'};
27
80
  }
28
81
  const errorStatus: Partial<Record<JobErrorCode, number>> = {
29
82
  JOB_REQUEST_INVALID: 400,
@@ -83,8 +136,11 @@ export function createJobFront(options: {
83
136
  return result(await options.ports.ackDisplayed(jobId, request));
84
137
  return result(await options.ports.commitUIAct(jobId, request));
85
138
  }
86
- if (!read)
139
+ const partsCrop = request.method === 'POST' &&
140
+ /^publications\/[A-Za-z0-9][A-Za-z0-9._-]{0,127}\/instances\/[a-f0-9]{64}\/api\/stage-parts\/comment$/.test(route);
141
+ if (!read && !partsCrop)
87
142
  return failure('JOB_REQUEST_INVALID', 405);
143
+ if (partsCrop && sentOrigin !== origin.origin) return failure('JOB_SAME_ORIGIN_REQUIRED', 403);
88
144
  const liveness = await options.ports.jobLiveness(jobId);
89
145
  if (!liveness.ok)
90
146
  return result(liveness);
@@ -172,7 +228,9 @@ export function jobWindowResources() {
172
228
  '<body data-job-window><script type="module" src="job.js"></script></body></html>';
173
229
  }
174
230
  if (name === 'styles.css')
175
- return Bun.file(new URL('../web/styles.css', import.meta.url));
231
+ return (await Bun.file(new URL('../web/styles.css', import.meta.url)).text()) +
232
+ '\n@scope (.job-inspection[data-job-parts-workspace]) {\n' +
233
+ (await Bun.file(new URL('../web/parts.css', import.meta.url)).text()) + '\n}';
176
234
  bundle ??= buildJobWindow();
177
235
  return bundle;
178
236
  };
@@ -194,21 +252,75 @@ interface RetainedView {
194
252
  }
195
253
 
196
254
  /** The host reads only the committed retained snapshot and its sealed file inventory. */
197
- function retainedPublicationRoutes(session: JobSession) {
255
+ export function retainedPublicationRoutes(session: JobSession) {
198
256
  const views = new Map<string, Promise<RetainedView>>();
199
257
  return async (jobId: string, publicationId: string, key: string, path: string, request: Request): Promise<Response> => {
200
258
  if (jobId !== session.jobId) return failure('JOB_UNKNOWN', 404);
201
259
  try {
260
+ const crop = path === 'api/stage-parts/comment' && request.method === 'POST';
261
+ if (crop) session.authorize('ui', request.headers.get('X-Review-Capability'));
202
262
  return await session.readPublicationResponse(publicationId, async retained => {
203
263
  const display = session.displayPublication(publicationId);
204
264
  if (key !== display.publication.instanceKey) return failure('JOB_DISPLAY_MISMATCH', 409);
265
+ if (crop && session.status().publication?.publicationId !== publicationId)
266
+ return failure('JOB_ACT_SOURCE_STALE', 409);
267
+ const json = (value: unknown) => new Response(request.method === 'HEAD' ? null : JSON.stringify(value), {
268
+ headers: {...headers, 'Content-Type': 'application/json'},
269
+ });
270
+ const sealedFile = async (relativePath: string) => {
271
+ const seal = retained.seals.find(file => file.path === relativePath);
272
+ if (!seal) return failure('JOB_SOURCE_UNRETAINABLE', 404);
273
+ const file = await safeFile(retained.snapshotRoot, relativePath);
274
+ return serveReference(request, file, seal.sha256, headers);
275
+ };
276
+ if (isRetainedRecordSource(retained)) {
277
+ if (path === 'api/review') {
278
+ return json({
279
+ recordSource: retained.source,
280
+ sourceHash: retained.source.sourceHash,
281
+ assetsBase: display.routes.assetsBase,
282
+ capabilities: {
283
+ playback: false,
284
+ interview: retained.questions.length > 0,
285
+ preRig: false,
286
+ modeling: false,
287
+ motion: false,
288
+ feedback: true,
289
+ audio: false,
290
+ },
291
+ feedbackCatalog: {slots: null},
292
+ });
293
+ }
294
+ if (path === 'api/interview') {
295
+ return json({questions: retained.questions.map(question => ({...question,
296
+ images: question.images.map((image, index) => ({name: image.name,
297
+ url: `/api/interview/image/${question.ref.sha256}/${index}`})),
298
+ }))});
299
+ }
300
+ const interview = /^api\/interview\/image\/([a-f0-9]{64})\/(0|[1-9]\d*)$/.exec(path);
301
+ if (interview) {
302
+ const image = retained.questions.find(question => question.ref.sha256 === interview[1])?.images[Number(interview[2])];
303
+ if (!image) return failure('JOB_SOURCE_UNRETAINABLE', 404);
304
+ return await sealedFile(image.ref.path);
305
+ }
306
+ return failure('JOB_REQUEST_INVALID', 404);
307
+ }
205
308
  let pending = views.get(publicationId);
206
309
  if (!pending) {
207
310
  pending = (async () => {
208
311
  const review = await loadReview(retained.manifestPath);
209
- const parts = retained.source.parts
210
- ? await loadPartsView(dirname(join(retained.snapshotRoot, retained.source.parts.manifest.path)))
211
- : null;
312
+ const partsRoot = retained.source.parts
313
+ ? dirname(join(retained.snapshotRoot, retained.source.parts.manifest.path)) : null;
314
+ // Forward only retained producer files. Discovery never reads the live draft.
315
+ const retainedFile = (path: string) => retained.seals.some(file =>
316
+ file.path === relative(retained.snapshotRoot, path).split('\\').join('/')) ? path : undefined;
317
+ const rigRoot = review.handoff?.rig ?? partsRoot;
318
+ const parts = partsRoot ? await loadPartsView(partsRoot, {
319
+ rig: rigRoot ? retainedFile(join(rigRoot, 'rig.json')) : undefined,
320
+ meshReport: rigRoot ? retainedFile(join(rigRoot, 'mesh_report.json')) : undefined,
321
+ painting: review.handoff?.source ? retainedFile(review.handoff.source) : undefined,
322
+ paintingRoot: retained.snapshotRoot,
323
+ }) : null;
212
324
  if (parts) {
213
325
  if (parts.items.length !== retained.partIds.length || parts.items.some(item => !retained.partIds.includes(item.name))) {
214
326
  throw new JobError('JOB_SOURCE_MISMATCH');
@@ -226,15 +338,6 @@ function retainedPublicationRoutes(session: JobSession) {
226
338
  }
227
339
  const {review, parts} = await pending;
228
340
  await assertReviewUnchanged(review);
229
- const json = (value: unknown) => new Response(request.method === 'HEAD' ? null : JSON.stringify(value), {
230
- headers: {...headers, 'Content-Type': 'application/json'},
231
- });
232
- const sealedFile = async (relativePath: string) => {
233
- const seal = retained.seals.find(file => file.path === relativePath);
234
- if (!seal) return failure('JOB_SOURCE_UNRETAINABLE', 404);
235
- const file = await safeFile(retained.snapshotRoot, relativePath);
236
- return serveReference(request, file, seal.sha256, headers);
237
- };
238
341
  if (path === 'api/review') {
239
342
  return json({
240
343
  manifest: review.manifest,
@@ -247,15 +350,22 @@ function retainedPublicationRoutes(session: JobSession) {
247
350
  sourcePainting: review.sourcePainting && {...review.sourcePainting, url: '/review-painting'},
248
351
  feedbackCatalog: review.feedbackCatalog,
249
352
  assetsBase: display.routes.assetsBase,
250
- capabilities: {playback: !!review.manifest.model, interview: retained.questions.length > 0,
353
+ capabilities: {playback: !!review.manifest.model,
354
+ interview: retained.questions.length > 0 ||
355
+ (retained.interview?.records.length ?? 0) > 0 ||
356
+ (retained.interview?.diagnostics.length ?? 0) > 0,
251
357
  preRig: retained.source.selector?.kind === 'draft', modeling: false, motion: false, feedback: true, audio: false},
252
358
  });
253
359
  }
254
360
  if (path === 'api/interview') {
255
- return json({questions: retained.questions.map(question => ({...question,
256
- images: question.images.map((image, index) => ({name: image.name,
257
- url: `/api/interview/image/${question.ref.sha256}/${index}`})),
258
- }))});
361
+ const interview = retained.interview !== undefined ? retained.interview : display.publication.interview;
362
+ return json({
363
+ questions: retained.questions.map(question => ({...question,
364
+ images: question.images.map((image, index) => ({name: image.name,
365
+ url: `/api/interview/image/${question.ref.sha256}/${index}`})),
366
+ })),
367
+ ...(interview === undefined ? {} : {interview}),
368
+ });
259
369
  }
260
370
  const interview = /^api\/interview\/image\/([a-f0-9]{64})\/(0|[1-9]\d*)$/.exec(path);
261
371
  if (interview) {
@@ -269,6 +379,29 @@ function retainedPublicationRoutes(session: JobSession) {
269
379
  if (!image) return failure('JOB_SOURCE_UNRETAINABLE', 404);
270
380
  return await sealedFile(image.path);
271
381
  }
382
+ if (crop) {
383
+ if (!parts) return failure('JOB_SOURCE_UNRETAINABLE', 409);
384
+ if (request.headers.get('origin') !== new URL(request.url).origin)
385
+ return failure('JOB_SAME_ORIGIN_REQUIRED', 403);
386
+ const raw = await jobBody(request);
387
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw) ||
388
+ (raw as {sourceHash?: unknown}).sourceHash !== retained.source.sourceHash)
389
+ return failure('JOB_ACT_SOURCE_STALE', 409);
390
+ // Preserve the exact displayed job identity through native evidence validation.
391
+ assertRetainedSnapshotIntact(retained.snapshotRoot, retained.seals);
392
+ let comment;
393
+ try {
394
+ comment = await preparePartsComment(parts, raw, false, {sourceHash: retained.source.sourceHash});
395
+ } catch (error) {
396
+ if (error instanceof JobError ||
397
+ error instanceof Error && error.message.startsWith('PARTS_COMMENT_STALE_SOURCE:')) throw error;
398
+ return failure('JOB_SOURCE_MISMATCH', 409, cropFailureDiagnostic(error, raw));
399
+ }
400
+ assertRetainedSnapshotIntact(retained.snapshotRoot, retained.seals);
401
+ if (session.status().publication?.publicationId !== publicationId)
402
+ return failure('JOB_ACT_SOURCE_STALE', 409);
403
+ return json({comment});
404
+ }
272
405
  if (path === 'api/stage-parts') {
273
406
  if (!parts) return failure('JOB_SOURCE_UNRETAINABLE', 409);
274
407
  return json({...partsViewJson(parts, {verdict: null, stale: null}), sourceHash: retained.source.sourceHash,
@@ -291,7 +424,10 @@ function retainedPublicationRoutes(session: JobSession) {
291
424
  return failure('JOB_REQUEST_INVALID', 404);
292
425
  });
293
426
  } catch (error) {
294
- return failure(error instanceof JobError ? error.code : 'JOB_SOURCE_MISMATCH', 409);
427
+ const code = error instanceof JobError ? error.code :
428
+ error instanceof Error && error.message.startsWith('PARTS_COMMENT_STALE_SOURCE:')
429
+ ? 'PARTS_COMMENT_STALE_SOURCE' : 'JOB_SOURCE_MISMATCH';
430
+ return failure(code, errorStatus[code as JobErrorCode] ?? 409);
295
431
  }
296
432
  };
297
433
  }
@@ -311,6 +447,9 @@ export interface JobHostRecord {
311
447
  /** Absent on older records whose hook identity cannot be established. */
312
448
  readerId?: string | null;
313
449
  bindingId?: string | null;
450
+ /** Present when the host runs in record-and-package mode. */
451
+ publicationMode?: JobPublicationMode;
452
+ recordReaderId?: string | null;
314
453
  }
315
454
 
316
455
  export type JobHostListenerIncarnation = string;
@@ -497,11 +636,43 @@ function freezeExpectation(value: JobHostReuseExpectation): JobHostReuseExpectat
497
636
  }
498
637
 
499
638
  export function jobHostIdentity(startup: JobHostOptions) {
500
- const readerId = declaredHostId('readPublished', startup.readPublished, startup.readerId);
639
+ if (startup.publicationMode !== undefined && startup.publicationMode !== 'package-only' && startup.publicationMode !== 'record-and-package') {
640
+ throw new JobHostOptionError('JOB_HOST_OPTION_ID_INVALID', 'readPublished', null, String(startup.publicationMode));
641
+ }
642
+ const isRecordMode = startup.publicationMode === 'record-and-package' || startup.readRecordPublished !== undefined;
643
+ let readerId: string | null;
644
+ let recordReaderId: string | null;
645
+ let publicationMode: JobPublicationMode;
646
+ if (isRecordMode) {
647
+ if (startup.publicationMode === 'package-only') {
648
+ throw new JobHostOptionError('JOB_HOST_OPTION_ID_INVALID', 'readPublished', 'package-only', startup.recordReaderId ?? startup.readerId);
649
+ }
650
+ if (typeof startup.readRecordPublished !== 'function') {
651
+ throw new JobHostOptionError('JOB_HOST_OPTION_ID_INVALID', 'readPublished', null, startup.recordReaderId ?? startup.readerId);
652
+ }
653
+ if (startup.recordReaderId !== undefined) {
654
+ recordReaderId = declaredHostId('readPublished', startup.readRecordPublished, startup.recordReaderId);
655
+ readerId = declaredHostId('readPublished', startup.readPublished, startup.readerId);
656
+ } else {
657
+ recordReaderId = declaredHostId('readPublished', startup.readRecordPublished, startup.readerId);
658
+ if (startup.readPublished !== undefined && typeof startup.readPublished !== 'function') {
659
+ throw new JobHostOptionError('JOB_HOST_OPTION_ID_INVALID', 'readPublished', null, startup.readerId);
660
+ }
661
+ readerId = startup.readPublished ? recordReaderId : null;
662
+ }
663
+ publicationMode = 'record-and-package';
664
+ } else {
665
+ if (startup.recordReaderId !== undefined) {
666
+ throw new JobHostOptionError('JOB_HOST_OPTION_ID_INVALID', 'readPublished', null, startup.recordReaderId);
667
+ }
668
+ readerId = declaredHostId('readPublished', startup.readPublished, startup.readerId);
669
+ recordReaderId = null;
670
+ publicationMode = 'package-only';
671
+ }
501
672
  const bindingId = declaredHostId('installWriterBinding', startup.installWriterBinding, startup.bindingId);
502
673
  const partsEnumeratorId = declaredHostId('partsEnumerator', startup.partsEnumerator?.enumerate, startup.partsEnumeratorId);
503
674
  const partsEnumeratorVersion = startup.partsEnumerator?.version ?? null;
504
- return {readerId, bindingId, partsEnumeratorId, partsEnumeratorVersion};
675
+ return {readerId, bindingId, partsEnumeratorId, partsEnumeratorVersion, publicationMode, recordReaderId};
505
676
  }
506
677
 
507
678
  export async function installJobWriterBinding(session: JobSession, startup: JobHostOptions, origin: string): Promise<void> {
@@ -510,6 +681,19 @@ export async function installJobWriterBinding(session: JobSession, startup: JobH
510
681
  }
511
682
 
512
683
  export function assertJobHostCompatible(record: JobHostRecord, identity: ReturnType<typeof jobHostIdentity>): void {
684
+ const recordMode: JobPublicationMode = record.publicationMode ?? 'package-only';
685
+ const recordReaderId = record.recordReaderId ?? null;
686
+ if (recordMode !== identity.publicationMode) {
687
+ throw new JobHostOptionError(
688
+ 'JOB_HOST_REUSE_MISMATCH',
689
+ 'readPublished',
690
+ recordReaderId ?? record.readerId ?? recordMode,
691
+ identity.recordReaderId ?? identity.readerId ?? identity.publicationMode,
692
+ );
693
+ }
694
+ if (recordReaderId !== identity.recordReaderId) {
695
+ throw new JobHostOptionError('JOB_HOST_REUSE_MISMATCH', 'readPublished', recordReaderId, identity.recordReaderId);
696
+ }
513
697
  for (const [option, actual, requested] of [
514
698
  ['readPublished', record.readerId, identity.readerId],
515
699
  ['installWriterBinding', record.bindingId, identity.bindingId],
@@ -531,7 +715,12 @@ function buildAttachment(session: JobSession, origin: string, listenerIncarnatio
531
715
  if (live.status !== 'active') throw new JobHostAttachError('closed', 'acceptance');
532
716
  return freezeExpectation({jobId: session.jobId, origin, listenerIncarnation, binding: {
533
717
  root: live.root.path, stateDir: live.stateDir, fingerprint: live.fingerprint,
534
- reviewer: live.reviewer, ...identity, apiSchema: live.apiSchema, actSchema: live.actSchema,
718
+ reviewer: live.reviewer,
719
+ readerId: identity.readerId ?? identity.recordReaderId,
720
+ bindingId: identity.bindingId,
721
+ partsEnumeratorId: identity.partsEnumeratorId,
722
+ partsEnumeratorVersion: identity.partsEnumeratorVersion,
723
+ apiSchema: live.apiSchema, actSchema: live.actSchema,
535
724
  }});
536
725
  }
537
726
 
@@ -598,8 +787,23 @@ export function createJobRequestContext(session: JobSession, startup: JobHostOpt
598
787
  listenerIncarnation: string = hubIncarnation ?? randomUUID(), accepting: () => boolean = () => true) {
599
788
  const ports = createJobHostPorts(session, new URL(origin).origin);
600
789
  // This legacy GET projection and its property order are deliberately unchanged.
601
- const record: JobHostRecord = {schema: 'rig-review-job-host/1', apiSchema: JOB_API_SCHEMA, actSchema: JOB_ACT_SCHEMA,
602
- ...identity, jobId: session.jobId, origin, fingerprint: startup.fingerprint, pid: process.pid};
790
+ const record: JobHostRecord = {
791
+ schema: 'rig-review-job-host/1',
792
+ apiSchema: JOB_API_SCHEMA,
793
+ actSchema: JOB_ACT_SCHEMA,
794
+ readerId: identity.readerId,
795
+ bindingId: identity.bindingId,
796
+ partsEnumeratorId: identity.partsEnumeratorId,
797
+ partsEnumeratorVersion: identity.partsEnumeratorVersion,
798
+ ...(identity.publicationMode === 'record-and-package' ? {
799
+ publicationMode: identity.publicationMode,
800
+ recordReaderId: identity.recordReaderId,
801
+ } : {}),
802
+ jobId: session.jobId,
803
+ origin,
804
+ fingerprint: startup.fingerprint,
805
+ pid: process.pid,
806
+ };
603
807
  const front = createJobFront({origin, ports, resource, hubIncarnation, publication: retainedPublicationRoutes(session)});
604
808
  let requests = 0, stopped = false, published = false;
605
809
  let captured: ObservedFiles;
@@ -824,7 +1028,13 @@ async function attachJobHost(options: JobHostOptions): Promise<JobOwnerHost> {
824
1028
  fingerprint,
825
1029
  reviewer,
826
1030
  ...(port !== undefined ? { port } : {}),
1031
+ ...(options.publicationMode !== undefined ? { publicationMode: options.publicationMode } : {}),
827
1032
  ...(options.readPublished ? { readPublished: options.readPublished, readerId: identity.readerId! } : {}),
1033
+ ...(options.readRecordPublished ? {
1034
+ readRecordPublished: options.readRecordPublished,
1035
+ recordReaderId: identity.recordReaderId!,
1036
+ ...(options.readerId !== undefined && !options.readPublished ? { readerId: options.readerId } : {}),
1037
+ } : {}),
828
1038
  ...(options.installWriterBinding ? { installWriterBinding: options.installWriterBinding, bindingId: identity.bindingId! } : {}),
829
1039
  ...(options.partsEnumerator ? { partsEnumerator: {...options.partsEnumerator}, partsEnumeratorId: identity.partsEnumeratorId! } : {}),
830
1040
  ...(options.afterSnapshot ? { afterSnapshot: options.afterSnapshot } : {}),
@@ -870,7 +1080,10 @@ async function attachJobHost(options: JobHostOptions): Promise<JobOwnerHost> {
870
1080
  if (fingerprint !== expected.binding.fingerprint) throw reuseMismatch('fingerprint', expected.binding.fingerprint, fingerprint);
871
1081
  if (reviewer.id !== expected.binding.reviewer.id) throw reuseMismatch('reviewer.id', expected.binding.reviewer.id, reviewer.id);
872
1082
  if (reviewer.role !== expected.binding.reviewer.role) throw reuseMismatch('reviewer.role', expected.binding.reviewer.role, reviewer.role);
873
- if (identity.readerId !== expected.binding.readerId) throw reuseMismatch('readerId', expected.binding.readerId, identity.readerId);
1083
+ const requestedBindingReaderId = identity.readerId ?? identity.recordReaderId;
1084
+ if (requestedBindingReaderId !== expected.binding.readerId) {
1085
+ throw reuseMismatch('readerId', expected.binding.readerId, requestedBindingReaderId);
1086
+ }
874
1087
  if (identity.bindingId !== expected.binding.bindingId) throw reuseMismatch('bindingId', expected.binding.bindingId, identity.bindingId);
875
1088
  if (identity.partsEnumeratorId !== expected.binding.partsEnumeratorId) {
876
1089
  throw reuseMismatch('partsEnumeratorId', expected.binding.partsEnumeratorId, identity.partsEnumeratorId);
@@ -996,15 +1209,37 @@ async function attachJobHost(options: JobHostOptions): Promise<JobOwnerHost> {
996
1209
  if (descriptor.fingerprint !== expected.binding.fingerprint) {
997
1210
  throw reuseMismatch('fingerprint', expected.binding.fingerprint, descriptor.fingerprint);
998
1211
  }
1212
+ const descriptorMode = Object.hasOwn(descriptor, 'publicationMode') ? descriptor.publicationMode : 'package-only';
1213
+ if (descriptorMode !== 'package-only' && descriptorMode !== 'record-and-package') {
1214
+ throw new JobHostAttachError('read', 'record');
1215
+ }
1216
+ const descriptorRecordReaderId = Object.hasOwn(descriptor, 'recordReaderId') ? descriptor.recordReaderId : null;
1217
+ if (descriptorRecordReaderId !== null && (typeof descriptorRecordReaderId !== 'string' || !descriptorRecordReaderId)) {
1218
+ throw new JobHostAttachError('read', 'record');
1219
+ }
1220
+ if (descriptorMode === 'package-only' && descriptorRecordReaderId !== null ||
1221
+ descriptorMode === 'record-and-package' && descriptorRecordReaderId === null) {
1222
+ throw new JobHostAttachError('read', 'record');
1223
+ }
999
1224
  for (const field of ['readerId', 'bindingId', 'partsEnumeratorId', 'partsEnumeratorVersion'] as const) {
1000
1225
  const val = descriptor[field];
1001
1226
  if (!Object.hasOwn(descriptor, field) || val !== null && (typeof val !== 'string' || !val)) {
1002
1227
  throw new JobHostAttachError('read', 'record');
1003
1228
  }
1004
- if (val !== expected.binding[field]) {
1005
- throw reuseMismatch(field, expected.binding[field], (val ?? null) as string | null);
1229
+ const compareVal = field === 'readerId' ? (val ?? descriptorRecordReaderId) : val;
1230
+ if (compareVal !== expected.binding[field]) {
1231
+ throw reuseMismatch(field, expected.binding[field], (compareVal ?? null) as string | null);
1006
1232
  }
1007
1233
  }
1234
+ if (descriptorMode !== identity.publicationMode ||
1235
+ descriptor.readerId !== identity.readerId ||
1236
+ descriptorRecordReaderId !== identity.recordReaderId) {
1237
+ throw reuseMismatch(
1238
+ 'readerId',
1239
+ (descriptor.readerId ?? descriptorRecordReaderId ?? descriptorMode) as string | null,
1240
+ identity.readerId ?? identity.recordReaderId ?? identity.publicationMode,
1241
+ );
1242
+ }
1008
1243
  for (const field of ['apiSchema', 'actSchema'] as const) {
1009
1244
  const val = descriptor[field];
1010
1245
  if (typeof val !== 'string' || !val) {
@@ -1109,7 +1344,8 @@ function validatedHostRefusal(raw: unknown, status: number): Error | null {
1109
1344
  function snapshotHostOptions(options: JobHostOptions): JobHostOptions {
1110
1345
  const copy = ownData(options);
1111
1346
  if (copy.reuseOnly !== undefined && Object.keys(copy).some(key => ![
1112
- 'root', 'stateDir', 'fingerprint', 'reviewer', 'readPublished', 'readerId', 'installWriterBinding',
1347
+ 'root', 'stateDir', 'fingerprint', 'reviewer', 'publicationMode', 'readPublished', 'readerId',
1348
+ 'readRecordPublished', 'recordReaderId', 'installWriterBinding',
1113
1349
  'bindingId', 'partsEnumerator', 'partsEnumeratorId', 'port', 'reuseOnly', 'afterSnapshot', 'afterDirectorySync',
1114
1350
  ].includes(key))) throw new JobError('JOB_REQUEST_INVALID');
1115
1351
  if (copy.partsEnumerator !== undefined) copy.partsEnumerator = {...exactKeys(copy.partsEnumerator, ['version', 'enumerate'])};
package/src/job-host.ts CHANGED
@@ -13,11 +13,24 @@ export type {
13
13
  } from './job-front.ts';
14
14
  export type {JobSessionOptions, JobSession} from './job-session.ts';
15
15
  export type {JobWorkerOptions} from './job-worker.ts';
16
- export type {JobPublicationReader, JobPublishedContext} from './job-source.ts';
16
+ export {prepareJobRecordSource} from './job-source.ts';
17
+ export type {
18
+ JobPublicationReader,
19
+ JobPublishedContext,
20
+ JobRetainedRecordSource,
21
+ JobRetainedSource,
22
+ JobRetainedSourceV3,
23
+ JobRootIdentity,
24
+ } from './job-source.ts';
25
+ export {parseRecordAct} from './job-api.ts';
26
+ export {prepareJobRecordAct} from './job-act.ts';
17
27
  export {
18
28
  JOB_CAPABILITIES,
19
29
  JOB_API_SCHEMA,
30
+ JOB_API_V3_SCHEMA,
20
31
  JOB_ACT_SCHEMA,
32
+ JOB_RECORD_ACT_SCHEMA,
33
+ JOB_RECORD_READER_ID,
21
34
  JOB_PARTS_ENUMERATOR_RANGE,
22
35
  JOB_ENABLED_ACT_KINDS,
23
36
  JOB_RESERVED_ACT_KINDS,
@@ -26,6 +39,16 @@ export {
26
39
  JOB_ERROR_CODES,
27
40
  } from './job-contract.ts';
28
41
  export type {
42
+ ActV3,
43
+ AgentRequestV3,
44
+ ApiResponseV3,
45
+ AskRequestV3,
46
+ CloseRequestV3,
47
+ DisplayPublicationV3,
48
+ EventV3,
49
+ FetchActRequestV3,
50
+ JobCapabilitiesV3,
51
+ JobDisplayPublicationV3,
29
52
  JobEnabledActKind,
30
53
  JobReservedActKind,
31
54
  JobActKind,
@@ -55,33 +78,132 @@ export type {
55
78
  JobUIActValues,
56
79
  JobActSources,
57
80
  JobAct,
81
+ JobActV3,
58
82
  JobLegacyAct,
59
83
  JobRigReviewAct,
84
+ JobPartsVerdictAct,
85
+ JobLegacyPartsVerdictValue,
86
+ PartsVerdictValue,
87
+ JobPanelComposition,
88
+ PanelComponent,
60
89
  JobRigStill,
61
90
  JobRigCapture,
62
91
  JobSubject,
63
92
  JobPendingAsk,
93
+ JobPendingAskV3,
94
+ JobProjectRecord,
95
+ JobInterviewJson,
96
+ JobInterviewRecord,
97
+ JobInterviewDiagnostic,
98
+ JobInterviewDiagnostics,
64
99
  JobPublication,
100
+ JobPublicationMode,
101
+ JobPublicationV3,
65
102
  JobStatus,
103
+ JobStatusV3,
104
+ JobPublishResultV3,
66
105
  JobPublishRequest,
106
+ JobPublishRequestV3,
67
107
  JobAskRequest,
108
+ JobAskRequestV3,
68
109
  JobNextRequest,
110
+ JobNextRequestV3,
69
111
  JobCloseRequest,
112
+ JobCloseRequestV3,
70
113
  JobAgentRequest,
114
+ JobAgentRequestV3,
71
115
  JobFetchActRequest,
116
+ JobFetchActRequestV3,
72
117
  JobErrorCode,
73
118
  JobFailure,
74
119
  JobResult,
75
120
  JobEvent,
121
+ JobEventV3,
76
122
  JobNextValue,
123
+ JobNextValueV3,
124
+ JobOptionContext,
125
+ JobOptionSource,
126
+ JobPlanContext,
127
+ JobPlanSource,
128
+ JobRecordAct,
129
+ JobRecordActKind,
130
+ JobRecordCheckpointSubject,
131
+ JobRecordContextBase,
132
+ JobRecordFreeze,
133
+ JobRecordHostHooks,
134
+ JobRecordOptionResult,
135
+ JobRecordPartsIdentity,
136
+ JobRecordPicksSubject,
137
+ JobRecordPlanResult,
138
+ JobRecordPlanSubject,
139
+ JobRecordPublicationReader,
140
+ JobRecordPublishedContext,
141
+ JobRecordReaderInput,
142
+ JobRecordReopenSubject,
143
+ JobRecordReopenValue,
144
+ JobRecordResult,
145
+ JobRecordSignoffStage,
146
+ JobRecordSignoffSubject,
147
+ JobRecordSignoffValue,
148
+ JobRecordSource,
149
+ JobRecordSourceBase,
150
+ JobRecordSubject,
151
+ JobRecordUIActValues,
152
+ JobRecordUISubmission,
77
153
  JobResponseValues,
154
+ JobResponseValuesV3,
78
155
  JobApiResponse,
156
+ JobApiResponseV3,
157
+ JobSourceV3,
79
158
  JobUISubmission,
159
+ JobUISubmissionV3,
80
160
  JobDisplayAcknowledgment,
81
161
  JobDisplayReceipt,
82
162
  JobDisplayPublication,
83
163
  JobHostPorts,
84
164
  JobConsumerGrant,
165
+ NextRequestV3,
166
+ NextValueV3,
167
+ OptionContext,
168
+ OptionSource,
169
+ PackageResultV3,
170
+ PendingAskV3,
171
+ PlanContext,
172
+ PlanSource,
173
+ ProjectRecord,
174
+ PublicationV3,
175
+ PublishRequestV3,
176
+ PublishResultV3,
177
+ ReaderValue,
178
+ RecordAct,
179
+ RecordActKind,
180
+ RecordCheckpointSubject,
181
+ RecordContextBase,
182
+ RecordFreeze,
183
+ RecordHostHooks,
184
+ RecordOptionResult,
185
+ RecordPartsIdentity,
186
+ RecordPicksSubject,
187
+ RecordPlanResult,
188
+ RecordPlanSubject,
189
+ RecordPublicationReader,
190
+ RecordPublishedContext,
191
+ RecordReaderInput,
192
+ RecordReopenSubject,
193
+ RecordReopenValue,
194
+ RecordResult,
195
+ RecordSignoffStage,
196
+ RecordSignoffSubject,
197
+ RecordSignoffValue,
198
+ RecordSource,
199
+ RecordSourceBase,
200
+ RecordSubject,
201
+ RecordUIActValues,
202
+ RecordUISubmission,
203
+ ResponseValuesV3,
204
+ SourceV3,
205
+ StatusV3,
206
+ UISubmissionV3,
85
207
  } from './job-contract.ts';
86
208
 
87
209
  export {assertJobImageSetCapability} from './job-image-set.ts';