@rig-c/review 2.8.0 → 2.10.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.
@@ -12,6 +12,7 @@
12
12
  */
13
13
 
14
14
  import type { JobPublicationReader } from './job-source.ts';
15
+ import type { PartsIssue } from './parts-comment.ts';
15
16
 
16
17
  export const JOB_API_SCHEMA = 'rig-review/job-api@2' as const;
17
18
  export const JOB_API_V3_SCHEMA = 'rig-review/job-api@3' as const;
@@ -20,6 +21,65 @@ export const JOB_ACT_SCHEMA = 'rig-review/act@2' as const;
20
21
  export const JOB_RIG_REVIEW_ACT_SCHEMA = 'rig-review/act@3' as const;
21
22
  /** Record-source acts only under opt-in API@3. Package/image acts retain @2/@3. */
22
23
  export const JOB_RECORD_ACT_SCHEMA = 'rig-review/act@4' as const;
24
+ /** New parts verdicts only. Historical @2 parts-verdict acts remain readable. */
25
+ export const JOB_PARTS_VERDICT_ACT_SCHEMA = 'rig-review/act@5' as const;
26
+ export const JOB_PANEL_COMPOSITION_SCHEMA = 'rig-review/panels@1' as const;
27
+
28
+ export type PanelSlot = 'left' | 'stage' | 'toolbar' | 'side';
29
+ export const PANEL_COMPONENTS = [
30
+ 'parts.canvas', 'parts.list', 'parts.issues', 'parts.layers', 'act.submit',
31
+ 'interview.picks', 'plan.body', 'rig.playback', 'scene.composite', 'images.set',
32
+ ] as const;
33
+ export type PanelComponent = typeof PANEL_COMPONENTS[number];
34
+ export interface JobPanelComposition {
35
+ readonly schema: typeof JOB_PANEL_COMPOSITION_SCHEMA;
36
+ readonly left?: readonly PanelComponent[];
37
+ readonly stage?: readonly PanelComponent[];
38
+ readonly toolbar?: readonly PanelComponent[];
39
+ readonly side?: readonly PanelComponent[];
40
+ }
41
+ export function isPanelComponent(value: string): value is PanelComponent {
42
+ return (PANEL_COMPONENTS as readonly string[]).includes(value);
43
+ }
44
+
45
+ export function parsePanelComposition(input: unknown): JobPanelComposition {
46
+ if (input === null || typeof input !== 'object' || Array.isArray(input) || Object.getPrototypeOf(input) !== Object.prototype) {
47
+ throw new Error('JOB_PANELS_INVALID: panels must be a plain object');
48
+ }
49
+ const p = input as Record<string, unknown>;
50
+ if (p.schema !== JOB_PANEL_COMPOSITION_SCHEMA) {
51
+ throw new Error(`JOB_PANELS_INVALID: panels.schema must be ${JOB_PANEL_COMPOSITION_SCHEMA}`);
52
+ }
53
+ for (const key of Object.keys(p)) {
54
+ if (!['schema', 'left', 'stage', 'toolbar', 'side'].includes(key)) {
55
+ throw new Error(`JOB_PANELS_INVALID: unknown panel slot ${key}`);
56
+ }
57
+ }
58
+ const slot = (value: unknown, field: string): PanelComponent[] => {
59
+ if (!Array.isArray(value) || value.length > 32) {
60
+ throw new Error(`JOB_PANELS_INVALID: ${field} must be an array of at most 32 components`);
61
+ }
62
+ return value.map((item, index) => {
63
+ if (typeof item !== 'string' || !item.trim() || item.length > 128 || /[\r\n\0]/.test(item)) {
64
+ throw new Error(`JOB_PANELS_INVALID: ${field}[${index}] must be a nonblank component id`);
65
+ }
66
+ // Unknown component IDs are preserved in their declared slot so the host renders JOB_PANEL_UNKNOWN: <id>.
67
+ return item as PanelComponent;
68
+ });
69
+ };
70
+ const stage = slot(p.stage, 'panels.stage');
71
+ const side = slot(p.side, 'panels.side');
72
+ if (stage.length !== 1 || side.length < 1 || side[side.length - 1] !== 'act.submit') {
73
+ throw new Error('JOB_PANELS_INVALID: stage must have exactly one component and side must end with act.submit');
74
+ }
75
+ return {
76
+ schema: JOB_PANEL_COMPOSITION_SCHEMA,
77
+ ...(p.left === undefined ? {} : { left: slot(p.left, 'panels.left') }),
78
+ stage,
79
+ ...(p.toolbar === undefined ? {} : { toolbar: slot(p.toolbar, 'panels.toolbar') }),
80
+ side,
81
+ };
82
+ }
23
83
  export const JOB_RECORD_READER_ID = 'rig-create/publication-reader/2' as const;
24
84
  export const JOB_RECORD_SOURCE_SCHEMA = 'rig-review-job-record-source/1' as const;
25
85
  export const JOB_RECORD_INSTANCE_SCHEMA = 'rig-review-job-record-instance/1' as const;
@@ -87,6 +147,23 @@ export interface JobFileIdentity {
87
147
  readonly sha256: JobSha256;
88
148
  }
89
149
 
150
+ /** Optional sealed decision material, bound verbatim to the published source. */
151
+ export interface JobCheckpointEvidence {
152
+ readonly schema: 'rig-review-checkpoint-evidence/1';
153
+ readonly checkpointId: string;
154
+ readonly planStepId: string;
155
+ readonly tiles: readonly (JobFileIdentity & {readonly id: string; readonly label: string})[];
156
+ readonly table: JobFileIdentity & {readonly label?: string};
157
+ readonly routesText: string;
158
+ readonly recommendationText: string;
159
+ }
160
+
161
+ export interface JobCheckpointTable {
162
+ readonly schema: 'rig-review-checkpoint-table/1';
163
+ readonly columns: readonly string[];
164
+ readonly rows: readonly (readonly (string | number | boolean | null)[])[];
165
+ }
166
+
90
167
  /** IDs and existing step hashes published by Create #184 for the displayed plan.
91
168
  * Review retains these values without importing or computing Create's internal
92
169
  * stepHash. Create validates them with its existing writer. No plan revision
@@ -151,6 +228,7 @@ export type JobSelector =
151
228
  * provide trusted source hashes or transfer old approval onto a new binding.
152
229
  */
153
230
  export interface JobModelSourceBinding {
231
+ readonly checkpointEvidence?: readonly JobCheckpointEvidence[];
154
232
  readonly subject?: never;
155
233
  readonly imageSet?: never;
156
234
  readonly imageSetDigest?: never;
@@ -184,7 +262,8 @@ export interface JobImageSet {
184
262
  }
185
263
 
186
264
  export interface JobImageSourceBinding extends Omit<JobModelSourceBinding,
187
- 'subject' | 'model' | 'selector' | 'imageSet' | 'imageSetDigest' | 'duplicateHashes'> {
265
+ 'subject' | 'model' | 'selector' | 'imageSet' | 'imageSetDigest' | 'duplicateHashes' | 'checkpointEvidence'> {
266
+ readonly checkpointEvidence?: never;
188
267
  readonly subject: 'image-set';
189
268
  readonly model?: never;
190
269
  readonly selector?: never;
@@ -228,6 +307,22 @@ export type JobVerdict = 'pending' | 'approved' | 'changes-requested';
228
307
  export type JobPartOutcome = 'pending' | 'clean' | 'flagged';
229
308
  export type JobReviewStage = 'rig-review' | 'direction-review' | 'image-review';
230
309
 
310
+ export type PartsVerdictValue = {
311
+ readonly verdict: 'approved' | 'changes-requested';
312
+ readonly issues: readonly PartsIssue[];
313
+ readonly words: string;
314
+ };
315
+
316
+ export interface JobLegacyPartsVerdictValue {
317
+ readonly verdict: JobVerdict;
318
+ readonly parts: readonly {
319
+ readonly partId: string;
320
+ readonly part: { readonly outcome: JobPartOutcome; readonly note: string };
321
+ readonly mesh: { readonly outcome: JobPartOutcome; readonly note: string };
322
+ }[];
323
+ readonly words: string;
324
+ }
325
+
231
326
  export interface JobActValues {
232
327
  readonly 'interview-picks': {
233
328
  readonly questionId: string;
@@ -251,15 +346,7 @@ export interface JobActValues {
251
346
  */
252
347
  readonly words: string;
253
348
  };
254
- readonly 'parts-verdict': {
255
- readonly verdict: JobVerdict;
256
- readonly parts: readonly {
257
- readonly partId: string;
258
- readonly part: { readonly outcome: JobPartOutcome; readonly note: string };
259
- readonly mesh: { readonly outcome: JobPartOutcome; readonly note: string };
260
- }[];
261
- readonly words: string;
262
- };
349
+ readonly 'parts-verdict': PartsVerdictValue;
263
350
  readonly 'review-verdict': JobModelReviewValue | JobImageReviewValue;
264
351
  readonly signoff: {
265
352
  /** An explicitly declared Create stage. Validation belongs to its writer. */
@@ -321,7 +408,8 @@ export type JobLegacyAct = {
321
408
  } & (Kind extends 'review-verdict' ? (
322
409
  | {readonly source: Exclude<JobActSources['review-verdict'], JobImageSourceBinding>; readonly value: JobModelReviewValue}
323
410
  | {readonly source: JobImageSourceBinding; readonly value: JobImageReviewValue}
324
- ) : {readonly source: JobActSources[Kind]; readonly value: JobActValues[Kind]});
411
+ ) : Kind extends 'parts-verdict' ? {readonly source: JobActSources['parts-verdict']; readonly value: JobLegacyPartsVerdictValue}
412
+ : {readonly source: JobActSources[Kind]; readonly value: JobActValues[Kind]});
325
413
  }[JobEnabledActKind];
326
414
 
327
415
  export type JobRigStill = {
@@ -343,8 +431,13 @@ export type JobRigReviewAct = Omit<Extract<JobLegacyAct, {kind: 'review-verdict'
343
431
  readonly still: JobRigStill;
344
432
  };
345
433
 
346
- /** Historical @2 rig acts remain readable without being backfilled or relabelled. */
347
- export type JobAct = JobLegacyAct | JobRigReviewAct;
434
+ export type JobPartsVerdictAct = Omit<Extract<JobLegacyAct, {kind: 'parts-verdict'}>, 'schema' | 'value'> & {
435
+ readonly schema: typeof JOB_PARTS_VERDICT_ACT_SCHEMA;
436
+ readonly value: PartsVerdictValue;
437
+ };
438
+
439
+ /** Historical @2 acts remain readable without being backfilled or relabelled. */
440
+ export type JobAct = JobLegacyAct | JobRigReviewAct | JobPartsVerdictAct;
348
441
 
349
442
  /** Authenticated browser provenance. The daemon validates identity and hashes PNG bytes. */
350
443
  export interface JobRigCapture {
@@ -803,11 +896,13 @@ export interface RecordContextBase {
803
896
  }
804
897
 
805
898
  export type OptionContext = RecordContextBase & {
899
+ readonly checkpointEvidence?: never;
806
900
  readonly plan: null;
807
901
  readonly subjects: readonly [RecordPicksSubject];
808
902
  };
809
903
 
810
904
  export type PlanContext = RecordContextBase & {
905
+ readonly checkpointEvidence?: readonly JobCheckpointEvidence[];
811
906
  readonly plan: JobPlanIdentity;
812
907
  readonly subjects: readonly RecordPlanSubject[];
813
908
  };
@@ -854,6 +949,7 @@ export interface RecordSourceBase {
854
949
  }
855
950
 
856
951
  export type OptionSource = RecordSourceBase & {
952
+ readonly checkpointEvidence?: never;
857
953
  readonly subject: 'option-set';
858
954
  readonly selection: RecordOptionResult;
859
955
  readonly optionSet: { readonly id: string; readonly sha256: JobSha256 };
@@ -863,6 +959,7 @@ export type OptionSource = RecordSourceBase & {
863
959
  };
864
960
 
865
961
  export type PlanSource = RecordSourceBase & {
962
+ readonly checkpointEvidence?: readonly JobCheckpointEvidence[];
866
963
  readonly subject: 'plan';
867
964
  readonly selection: RecordPlanResult;
868
965
  readonly optionSet: null;
package/src/job-front.ts CHANGED
@@ -1,12 +1,14 @@
1
+ import {checkpointEvidenceMetadata, readCheckpointEvidenceBytes} from './job-checkpoint-evidence.ts';
1
2
  /** Disjoint live-job routes. The backend receives the original authenticated Request. */
2
3
  import { JOB_API_SCHEMA, JOB_ACT_SCHEMA, type JobErrorCode, type JobHostPorts, type JobId, type JobPublicationMode, type JobResult, type JobReviewerBinding } from './job-contract.ts';
3
4
  import { createJobHostPorts, jobBody, jobHash, jobId, jobObject, jobPartsEnumeratorVersion } from './job-api.ts';
4
5
  import { JobSession } from './job-session.ts';
5
- import { assertJobRoot, captureJobRoot, isRetainedRecordSource, type JobRootIdentity } from './job-source.ts';
6
+ import { assertJobRoot, assertRetainedSnapshotIntact, captureJobRoot, isRetainedRecordSource, type JobRootIdentity } from './job-source.ts';
6
7
  import type { JobWorkerOptions } from './job-worker.ts';
7
8
  import { JobError, JobStore } from './job-store.ts';
8
9
  import { loadReview, safeFile, packagePath, type ReviewPackage } from './manifest.ts';
9
10
  import { serveReference, assertReviewUnchanged } from './reference.ts';
11
+ import {preparePartsComment} from './parts-comment-crops.ts';
10
12
  import { loadPartsView, partsViewJson, servedImage, type PartsViewPackage } from './parts-view.ts';
11
13
  import { destinationDirectory, DestinationDirectoryError } from './destination-directory.ts';
12
14
  import { dirname, isAbsolute, join, relative, sep } from 'node:path';
@@ -22,8 +24,60 @@ const headers = {
22
24
  'Referrer-Policy': 'no-referrer',
23
25
  '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
26
  };
25
- function failure(code: string, status: number): Response {
26
- return Response.json({ ok: false, error: { code, message: code } }, { status, headers });
27
+ interface CropFailureDiagnostic {
28
+ field: string;
29
+ expected: string | number[];
30
+ received: string | number[];
31
+ }
32
+ function failure(code: string, status: number, diagnostic?: CropFailureDiagnostic, message = code): Response {
33
+ return Response.json({ ok: false, error: { code, message, ...(diagnostic ? {diagnostic} : {}) } }, { status, headers });
34
+ }
35
+
36
+ /** Explain an existing rejection without returning body text, filesystem paths or PNG bytes. */
37
+ function cropFailureDiagnostic(error: unknown, raw: unknown): CropFailureDiagnostic {
38
+ const message = error instanceof Error ? error.message : '';
39
+ const invariants: Record<string, [string, string]> = {
40
+ 'PARTS_COMMENT_RIG_REGION: rig region must be exact placement plus image region': ['rigRegion', 'exact placement plus imageRegion'],
41
+ 'PARTS_COMMENT_OUT_OF_BOUNDS: region exceeds original image': ['imageRegion', 'inside original image bounds'],
42
+ 'PARTS_COMMENT_OUT_OF_BOUNDS: region exceeds union of issue parts': ['rigRegion', 'inside union of bound parts'],
43
+ 'PARTS_CAMERA_RANGE: native zoom below fit/1 minimum': ['view.camera.zoom', 'at least min(fit, 1)'],
44
+ 'PARTS_CAMERA_RANGE: native scale or camera extent': ['view.camera', 'bounded positive zoom and viewport'],
45
+ 'PARTS_COMMENT_IMAGE_SIZE: original dimensions differ from placement': ['part.image.dimensions', 'equal retained placement dimensions'],
46
+ 'PARTS_COMMENT_CROP_INVALID: bounded content-addressed crop': ['crop', 'bounded content-addressed PNG metadata'],
47
+ 'COMMENT_CROP_INVALID: bounded content-addressed PNG required': ['crop', 'bounded content-addressed PNG'],
48
+ 'COMMENT_CROP_INVALID: expected noninterlaced 8-bit RGB/RGBA': ['crop.png.format', 'noninterlaced 8-bit RGB/RGBA'],
49
+ 'COMMENT_CROP_INVALID: truncated PNG chunk': ['crop.png.chunks', 'complete chunks'],
50
+ 'COMMENT_CROP_INVALID: PNG chunk length': ['crop.png.chunk.length', 'inside PNG byte bounds'],
51
+ 'COMMENT_CROP_INVALID: PNG chunk CRC': ['crop.png.chunk.crc', 'matching CRC'],
52
+ 'COMMENT_CROP_INVALID: static PNG required': ['crop.png.animation', 'static PNG'],
53
+ 'COMMENT_CROP_INVALID: PNG end': ['crop.png.end', 'final empty IEND'],
54
+ 'COMMENT_CROP_INVALID: PNG data/end missing': ['crop.png.data', 'IDAT and IEND present'],
55
+ 'COMMENT_CROP_INVALID: bounded PNG data decode': ['crop.png.data', 'bounded decodable scanlines'],
56
+ 'COMMENT_CROP_INVALID: PNG scanlines': ['crop.png.scanlines', 'exact dimensions and valid filters'],
57
+ 'COMMENT_CROP_PATH: existing crop is not the bound regular PNG': ['crop.storage', 'regular file with matching SHA-256'],
58
+ 'COMMENT_CROP_PATH: regular state directory required': ['crop.storage', 'regular state directory'],
59
+ };
60
+ // Inspect metadata only after the existing validator reports this exact invariant.
61
+ if (message === 'COMMENT_CROP_INVALID: PNG signature, dimensions or SHA-256 differ' &&
62
+ raw && typeof raw === 'object' && 'crop' in raw) {
63
+ const crop = raw.crop as {png?: unknown; sha256?: unknown; width?: unknown; height?: unknown} | null;
64
+ if (crop && typeof crop.png === 'string' && crop.png.length <= 200000 &&
65
+ typeof crop.sha256 === 'string' && /^[a-f0-9]{64}$/.test(crop.sha256)) {
66
+ const bytes = Buffer.from(crop.png.slice('data:image/png;base64,'.length), 'base64');
67
+ const hash = jobHash(bytes);
68
+ if (hash !== crop.sha256) return {field: 'crop.sha256', expected: crop.sha256, received: hash};
69
+ if (bytes.length >= 24 && bytes.subarray(0, 8).toString('hex') === '89504e470d0a1a0a' &&
70
+ typeof crop.width === 'number' && typeof crop.height === 'number' &&
71
+ (crop.width !== bytes.readUInt32BE(16) || crop.height !== bytes.readUInt32BE(20))) {
72
+ return {field: 'crop.dimensions', expected: [crop.width, crop.height],
73
+ received: [bytes.readUInt32BE(16), bytes.readUInt32BE(20)]};
74
+ }
75
+ }
76
+ return {field: 'crop.png.signature', expected: 'PNG signature and IHDR', received: 'invalid'};
77
+ }
78
+ const invariant = Object.hasOwn(invariants, message) ? invariants[message] : undefined;
79
+ return invariant ? {field: invariant[0], expected: invariant[1], received: 'rejected by existing validator'} :
80
+ {field: 'partsComment.prepare', expected: 'valid source-bound crop and writable evidence state', received: 'unclassified rejection'};
27
81
  }
28
82
  const errorStatus: Partial<Record<JobErrorCode, number>> = {
29
83
  JOB_REQUEST_INVALID: 400,
@@ -83,8 +137,11 @@ export function createJobFront(options: {
83
137
  return result(await options.ports.ackDisplayed(jobId, request));
84
138
  return result(await options.ports.commitUIAct(jobId, request));
85
139
  }
86
- if (!read)
140
+ const partsCrop = request.method === 'POST' &&
141
+ /^publications\/[A-Za-z0-9][A-Za-z0-9._-]{0,127}\/instances\/[a-f0-9]{64}\/api\/stage-parts\/comment$/.test(route);
142
+ if (!read && !partsCrop)
87
143
  return failure('JOB_REQUEST_INVALID', 405);
144
+ if (partsCrop && sentOrigin !== origin.origin) return failure('JOB_SAME_ORIGIN_REQUIRED', 403);
88
145
  const liveness = await options.ports.jobLiveness(jobId);
89
146
  if (!liveness.ok)
90
147
  return result(liveness);
@@ -172,7 +229,9 @@ export function jobWindowResources() {
172
229
  '<body data-job-window><script type="module" src="job.js"></script></body></html>';
173
230
  }
174
231
  if (name === 'styles.css')
175
- return Bun.file(new URL('../web/styles.css', import.meta.url));
232
+ return (await Bun.file(new URL('../web/styles.css', import.meta.url)).text()) +
233
+ '\n@scope (.job-inspection[data-job-parts-workspace]) {\n' +
234
+ (await Bun.file(new URL('../web/parts.css', import.meta.url)).text()) + '\n}';
176
235
  bundle ??= buildJobWindow();
177
236
  return bundle;
178
237
  };
@@ -199,9 +258,13 @@ export function retainedPublicationRoutes(session: JobSession) {
199
258
  return async (jobId: string, publicationId: string, key: string, path: string, request: Request): Promise<Response> => {
200
259
  if (jobId !== session.jobId) return failure('JOB_UNKNOWN', 404);
201
260
  try {
261
+ const crop = path === 'api/stage-parts/comment' && request.method === 'POST';
262
+ if (crop) session.authorize('ui', request.headers.get('X-Review-Capability'));
202
263
  return await session.readPublicationResponse(publicationId, async retained => {
203
264
  const display = session.displayPublication(publicationId);
204
265
  if (key !== display.publication.instanceKey) return failure('JOB_DISPLAY_MISMATCH', 409);
266
+ if (crop && session.status().publication?.publicationId !== publicationId)
267
+ return failure('JOB_ACT_SOURCE_STALE', 409);
205
268
  const json = (value: unknown) => new Response(request.method === 'HEAD' ? null : JSON.stringify(value), {
206
269
  headers: {...headers, 'Content-Type': 'application/json'},
207
270
  });
@@ -211,9 +274,19 @@ export function retainedPublicationRoutes(session: JobSession) {
211
274
  const file = await safeFile(retained.snapshotRoot, relativePath);
212
275
  return serveReference(request, file, seal.sha256, headers);
213
276
  };
277
+ const evidenceRoute = /^api\/checkpoint-evidence\/([A-Za-z0-9][A-Za-z0-9._-]*)\/(table|tiles\/(0|[1-9]\d*))$/.exec(path);
278
+ if (evidenceRoute) {
279
+ const packet = retained.source.checkpointEvidence?.find(item => item.checkpointId === evidenceRoute[1]);
280
+ const isTable = evidenceRoute[2] === 'table';
281
+ const member = isTable ? packet?.table : packet?.tiles[Number(evidenceRoute[3])];
282
+ if (!member) return failure('JOB_SOURCE_UNRETAINABLE', 404);
283
+ readCheckpointEvidenceBytes(retained.snapshotRoot, member, isTable ? 256 * 1024 : 8 * 1024 * 1024);
284
+ return await sealedFile(member.path);
285
+ }
214
286
  if (isRetainedRecordSource(retained)) {
215
287
  if (path === 'api/review') {
216
288
  return json({
289
+ ...checkpointEvidenceMetadata(retained.snapshotRoot, retained.source.checkpointEvidence),
217
290
  recordSource: retained.source,
218
291
  sourceHash: retained.source.sourceHash,
219
292
  assetsBase: display.routes.assetsBase,
@@ -247,9 +320,18 @@ export function retainedPublicationRoutes(session: JobSession) {
247
320
  if (!pending) {
248
321
  pending = (async () => {
249
322
  const review = await loadReview(retained.manifestPath);
250
- const parts = retained.source.parts
251
- ? await loadPartsView(dirname(join(retained.snapshotRoot, retained.source.parts.manifest.path)))
252
- : null;
323
+ const partsRoot = retained.source.parts
324
+ ? dirname(join(retained.snapshotRoot, retained.source.parts.manifest.path)) : null;
325
+ // Forward only retained producer files. Discovery never reads the live draft.
326
+ const retainedFile = (path: string) => retained.seals.some(file =>
327
+ file.path === relative(retained.snapshotRoot, path).split('\\').join('/')) ? path : undefined;
328
+ const rigRoot = review.handoff?.rig ?? partsRoot;
329
+ const parts = partsRoot ? await loadPartsView(partsRoot, {
330
+ rig: rigRoot ? retainedFile(join(rigRoot, 'rig.json')) : undefined,
331
+ meshReport: rigRoot ? retainedFile(join(rigRoot, 'mesh_report.json')) : undefined,
332
+ painting: review.handoff?.source ? retainedFile(review.handoff.source) : undefined,
333
+ paintingRoot: retained.snapshotRoot,
334
+ }) : null;
253
335
  if (parts) {
254
336
  if (parts.items.length !== retained.partIds.length || parts.items.some(item => !retained.partIds.includes(item.name))) {
255
337
  throw new JobError('JOB_SOURCE_MISMATCH');
@@ -267,8 +349,12 @@ export function retainedPublicationRoutes(session: JobSession) {
267
349
  }
268
350
  const {review, parts} = await pending;
269
351
  await assertReviewUnchanged(review);
352
+ if (retained.checkpointEvidencePackageHash !== undefined && retained.checkpointEvidencePackageHash !== review.sourceHash) {
353
+ throw new JobError('JOB_SOURCE_MISMATCH');
354
+ }
270
355
  if (path === 'api/review') {
271
356
  return json({
357
+ ...checkpointEvidenceMetadata(retained.snapshotRoot, retained.source.checkpointEvidence),
272
358
  manifest: review.manifest,
273
359
  sourceHash: retained.source.sourceHash,
274
360
  reviewedSource: review.reviewedSource,
@@ -308,6 +394,29 @@ export function retainedPublicationRoutes(session: JobSession) {
308
394
  if (!image) return failure('JOB_SOURCE_UNRETAINABLE', 404);
309
395
  return await sealedFile(image.path);
310
396
  }
397
+ if (crop) {
398
+ if (!parts) return failure('JOB_SOURCE_UNRETAINABLE', 409);
399
+ if (request.headers.get('origin') !== new URL(request.url).origin)
400
+ return failure('JOB_SAME_ORIGIN_REQUIRED', 403);
401
+ const raw = await jobBody(request);
402
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw) ||
403
+ (raw as {sourceHash?: unknown}).sourceHash !== retained.source.sourceHash)
404
+ return failure('JOB_ACT_SOURCE_STALE', 409);
405
+ // Preserve the exact displayed job identity through native evidence validation.
406
+ assertRetainedSnapshotIntact(retained.snapshotRoot, retained.seals);
407
+ let comment;
408
+ try {
409
+ comment = await preparePartsComment(parts, raw, false, {sourceHash: retained.source.sourceHash});
410
+ } catch (error) {
411
+ if (error instanceof JobError ||
412
+ error instanceof Error && error.message.startsWith('PARTS_COMMENT_STALE_SOURCE:')) throw error;
413
+ return failure('JOB_SOURCE_MISMATCH', 409, cropFailureDiagnostic(error, raw));
414
+ }
415
+ assertRetainedSnapshotIntact(retained.snapshotRoot, retained.seals);
416
+ if (session.status().publication?.publicationId !== publicationId)
417
+ return failure('JOB_ACT_SOURCE_STALE', 409);
418
+ return json({comment});
419
+ }
311
420
  if (path === 'api/stage-parts') {
312
421
  if (!parts) return failure('JOB_SOURCE_UNRETAINABLE', 409);
313
422
  return json({...partsViewJson(parts, {verdict: null, stale: null}), sourceHash: retained.source.sourceHash,
@@ -330,7 +439,12 @@ export function retainedPublicationRoutes(session: JobSession) {
330
439
  return failure('JOB_REQUEST_INVALID', 404);
331
440
  });
332
441
  } catch (error) {
333
- return failure(error instanceof JobError ? error.code : 'JOB_SOURCE_MISMATCH', 409);
442
+ const code = error instanceof JobError ? error.code :
443
+ error instanceof Error && error.message.startsWith('PARTS_COMMENT_STALE_SOURCE:')
444
+ ? 'PARTS_COMMENT_STALE_SOURCE' : 'JOB_SOURCE_MISMATCH';
445
+ const message = error instanceof JobError && /^CHECKPOINT_EVIDENCE_[A-Z_]+$/.test(error.message)
446
+ ? error.message : undefined;
447
+ return failure(code, errorStatus[code as JobErrorCode] ?? 409, undefined, message);
334
448
  }
335
449
  };
336
450
  }
package/src/job-host.ts CHANGED
@@ -81,6 +81,11 @@ export type {
81
81
  JobActV3,
82
82
  JobLegacyAct,
83
83
  JobRigReviewAct,
84
+ JobPartsVerdictAct,
85
+ JobLegacyPartsVerdictValue,
86
+ PartsVerdictValue,
87
+ JobPanelComposition,
88
+ PanelComponent,
84
89
  JobRigStill,
85
90
  JobRigCapture,
86
91
  JobSubject,
@@ -203,3 +208,5 @@ export type {
203
208
 
204
209
  export {assertJobImageSetCapability} from './job-image-set.ts';
205
210
  export type {JobCapabilities, JobImageSetInput, JobImageSet, JobImageSourceBinding, JobModelSourceBinding, JobModelReviewValue, JobImageReviewValue} from './job-contract.ts';
211
+
212
+ export type {JobCheckpointEvidence, JobCheckpointTable} from './job-contract.ts';
@@ -1,20 +1,23 @@
1
1
  import { randomBytes, randomUUID } from 'node:crypto';
2
- import { isAbsolute, relative, sep } from 'node:path';
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_RIG_REVIEW_ACT_SCHEMA, JOB_RECORD_READER_ID, jobStillByteLimit, JOB_CAPABILITIES, JOB_CAPABILITIES_V3, JOB_ENABLED_ACT_KINDS,
4
+ JOB_API_SCHEMA, JOB_API_V3_SCHEMA, JOB_ACT_SCHEMA, JOB_PARTS_VERDICT_ACT_SCHEMA, JOB_RIG_REVIEW_ACT_SCHEMA, JOB_RECORD_READER_ID, jobStillByteLimit, 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
8
  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 { jobApiSchemaForMode, jobHash, jobPartsEnumeratorVersion, jobWaitLimitMs, requestDigest, sameCapability } from './job-api.ts';
11
+ import { isRecordSource, parseRecordSource, jobApiSchemaForMode, jobHash, jobPartsEnumeratorVersion, jobWaitLimitMs, requestDigest, sameCapability } from './job-api.ts';
12
12
  import {
13
- assertJobRoot, assertJobSourceCurrent, assertRetainedSnapshotIntact, captureJobRoot, isRetainedRecordSource, prepareJobSource, jobSnapshotHash, removeOwnedJobSnapshot, verifyJobRecordSourceFresh,
13
+ assertStoredCheckpointEvidence, assertJobRoot, assertJobSourceCurrent, assertRetainedSnapshotIntact, captureJobRoot, isRetainedRecordSource, prepareJobSource, jobSnapshotHash, removeOwnedJobSnapshot, verifyJobRecordSourceFresh,
14
14
  type JobPublicationReader, type JobRetainedSource, type JobRetainedSourceV3, type JobRootIdentity,
15
15
  } from './job-source.ts';
16
16
  import { JobError, JobStore, type JobSnapshotOwner, type StoredJob } from './job-store.ts';
17
17
  import { canonicalStatePath } from './state-dir.ts';
18
+ import { loadReview } from './manifest.ts';
19
+ import { loadPartsView } from './parts-view.ts';
20
+ import { validateStoredPartsComment } from './parts-comment-crops.ts';
18
21
 
19
22
  export type { JobDisplayPublicationV3 } from './job-contract.ts';
20
23
 
@@ -74,6 +77,37 @@ function assertStoredSchemas(data: JobData): void {
74
77
  if (data.apiSchema !== JOB_API_SCHEMA || data.actSchema !== JOB_ACT_SCHEMA) {
75
78
  throw new JobError('JOB_SOURCE_UNRETAINABLE', 'JOB_STORED_SCHEMA_MISMATCH');
76
79
  }
80
+ assertStoredEvidence(data);
81
+ }
82
+
83
+ /** Check only the new extension and its durable copies, including committed replay values. */
84
+ function assertStoredEvidence(data: JobData): void {
85
+ for (const stored of Object.values(data.publications)) {
86
+ assertStoredCheckpointEvidence(stored.retained);
87
+ assertStoredEvidenceCopy(stored.publication, data);
88
+ }
89
+ for (const ask of Object.values(data.asks)) assertStoredEvidenceCopy(ask, data);
90
+ for (const act of Object.values(data.acts)) assertStoredEvidenceCopy(act, data);
91
+ for (const event of data.events) {
92
+ if (event.type === 'published') assertStoredEvidenceCopy(event.publication, data);
93
+ if (event.type === 'pending') assertStoredEvidenceCopy(event.ask, data);
94
+ if (event.type === 'act') assertStoredEvidenceCopy(event.act, data);
95
+ }
96
+ for (const replay of Object.values(data.replays)) assertStoredEvidenceCopy(replay.value, data);
97
+ }
98
+
99
+ function assertStoredEvidenceCopy(value: unknown, data: JobData): void {
100
+ if (!value || typeof value !== 'object') return;
101
+ const copy = value as {publicationId: string; source: JobPublication['source'] | PublicationV3['source']};
102
+ const stored = data.publications[copy.publicationId];
103
+ const bound = stored?.retained.source;
104
+ if (!('source' in value) && !(bound && 'checkpointEvidence' in bound)) return;
105
+ 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;
107
+ if (!bound || copy.source.sourceHash !== bound.sourceHash ||
108
+ requestDigest(copy.source.checkpointEvidence ?? null) !== requestDigest(bound.checkpointEvidence ?? null) ||
109
+ requestDigest(copy.source.plan) !== requestDigest(bound.plan)) throw new JobError('JOB_SOURCE_MISMATCH');
110
+ if (isRecordSource(copy.source)) parseRecordSource(copy.source);
77
111
  }
78
112
 
79
113
  function within(root: string, path: string): boolean {
@@ -356,6 +390,7 @@ export class JobSession {
356
390
  }
357
391
 
358
392
  private replay(data: JobData, key: string, digest: string): Replay | null {
393
+ assertStoredSchemas(data);
359
394
  const previous = data.replays[key];
360
395
  if (previous && previous.digest !== digest) throw new JobError('JOB_IDEMPOTENCY_CONFLICT');
361
396
  return previous ?? null;
@@ -487,7 +522,7 @@ export class JobSession {
487
522
  switch (input.verb) {
488
523
  case 'publish': {
489
524
  assertJobSourceCurrent(candidate!);
490
- if (isRetainedRecordSource(candidate!)) {
525
+ if (isRetainedRecordSource(candidate!) || candidate!.source.checkpointEvidence) {
491
526
  assertRetainedSnapshotIntact(
492
527
  candidate!.snapshotRoot,
493
528
  candidate!.seals,
@@ -515,7 +550,7 @@ export class JobSession {
515
550
  if (data.head !== input.publicationId) throw new JobError('JOB_ACT_SOURCE_STALE');
516
551
  const retained = data.publications[input.publicationId].retained;
517
552
  assertJobSourceCurrent(retained);
518
- if (isRetainedRecordSource(retained)) {
553
+ if (isRetainedRecordSource(retained) || retained.source.checkpointEvidence) {
519
554
  assertRetainedSnapshotIntact(
520
555
  retained.snapshotRoot,
521
556
  retained.seals,
@@ -600,7 +635,9 @@ export class JobSession {
600
635
  }
601
636
 
602
637
  async commitUIAct(raw: unknown): Promise<ActV3> {
603
- const input = parseUISubmission(raw, this.publicationMode), digest = requestDigest(input), key = `ui:${input.pageId}:${input.submissionId}`;
638
+ const parsed = parseUISubmission(raw, this.publicationMode);
639
+ const input = parsed.kind === 'parts-verdict' ? {...parsed, value: structuredClone(parsed.value)} : parsed;
640
+ const digest = requestDigest(input), key = `ui:${input.pageId}:${input.submissionId}`;
604
641
  const current = this.current();
605
642
  const previous = this.replay(current.data, key, digest);
606
643
  if (previous) return previous.value as ActV3;
@@ -627,6 +664,34 @@ export class JobSession {
627
664
  phase: 'finalize',
628
665
  subject: ask.subject as RecordSubject,
629
666
  });
667
+ } else if (ask && stored && input.kind === 'parts-verdict') {
668
+ assertJobSourceCurrent(stored.retained);
669
+ const candidate = finalizeJobAct({jobId: this.jobId, submission: input, ask,
670
+ retained: stored.retained, reviewer: current.data.reviewer});
671
+ if (candidate.schema === JOB_PARTS_VERDICT_ACT_SCHEMA && candidate.value.issues.length) {
672
+ await this.readPublicationResponse(input.publicationId, async retained => {
673
+ if (isRetainedRecordSource(retained) || !retained.source.parts) throw new JobError('JOB_ACT_SOURCE_STALE');
674
+ assertRetainedSnapshotIntact(retained.snapshotRoot, retained.seals,
675
+ retained.snapshotIdentity, 'JOB_ACT_SOURCE_STALE');
676
+ try {
677
+ const review = await loadReview(retained.manifestPath);
678
+ const painting = review.handoff?.source;
679
+ const sealedPainting = painting && retained.seals.some(file =>
680
+ file.path === relative(retained.snapshotRoot, painting).split(sep).join('/')) ? painting : undefined;
681
+ const pkg = await loadPartsView(dirname(join(retained.snapshotRoot, retained.source.parts.manifest.path)),
682
+ {painting: sealedPainting, paintingRoot: retained.snapshotRoot});
683
+ for (const issue of candidate.value.issues) {
684
+ await validateStoredPartsComment(pkg, issue, false, {sourceHash: retained.source.sourceHash});
685
+ }
686
+ } catch (error) {
687
+ if (error instanceof JobError) throw error;
688
+ throw new JobError('JOB_ACT_INVALID');
689
+ }
690
+ assertRetainedSnapshotIntact(retained.snapshotRoot, retained.seals,
691
+ retained.snapshotIdentity, 'JOB_ACT_SOURCE_STALE');
692
+ return new Response(null, {status: 204});
693
+ });
694
+ }
630
695
  }
631
696
  }
632
697
  }
@@ -646,7 +711,7 @@ export class JobSession {
646
711
  if (!ask) throw new JobError('JOB_ASK_INVALID');
647
712
  const retained = fresh.data.publications[input.publicationId].retained;
648
713
  assertJobSourceCurrent(retained);
649
- if (isRetainedRecordSource(retained)) {
714
+ if (isRetainedRecordSource(retained) || retained.source.checkpointEvidence || input.kind === 'parts-verdict') {
650
715
  assertRetainedSnapshotIntact(
651
716
  retained.snapshotRoot,
652
717
  retained.seals,