rig-review 3.7.0 → 4.0.1

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.
Files changed (109) hide show
  1. package/README.md +3 -3
  2. package/docs/DESIGN.md +145 -74
  3. package/docs/PANELS.md +20 -12
  4. package/docs/PARTS_VIEW.md +133 -76
  5. package/docs/REVIEW_PACKAGE.md +446 -100
  6. package/docs/STABILITY.md +132 -198
  7. package/docs/WORKFLOWS.md +41 -120
  8. package/package.json +4 -3
  9. package/skills/rig-review/SKILL.md +41 -27
  10. package/src/build.ts +10 -2
  11. package/src/cli.ts +17 -16
  12. package/src/comment-crops.ts +6 -1
  13. package/src/compare-html.ts +22 -24
  14. package/src/compare-server.ts +1 -1
  15. package/src/compare-session.ts +41 -3
  16. package/src/correction-handoff.ts +27 -4
  17. package/src/create-pin-gate.ts +3 -0
  18. package/src/direction-inspection.ts +6 -2
  19. package/src/feedback-export.ts +68 -1
  20. package/src/front.ts +5 -200
  21. package/src/handoff.ts +1 -1
  22. package/src/interview-routes.ts +1 -1
  23. package/src/interview-scene.ts +3 -3
  24. package/src/job-act.ts +77 -73
  25. package/src/job-api.ts +326 -13
  26. package/src/job-checkpoint-evidence.ts +113 -0
  27. package/src/job-cli.ts +27 -14
  28. package/src/job-contract.ts +284 -62
  29. package/src/job-front.ts +192 -61
  30. package/src/job-host.ts +23 -4
  31. package/src/job-session.ts +109 -24
  32. package/src/job-source.ts +227 -58
  33. package/src/job-store.ts +80 -6
  34. package/src/job-worker.ts +1 -47
  35. package/src/joined-project.ts +61 -4
  36. package/src/manifest.ts +32 -4
  37. package/src/open-workspace.ts +12 -12
  38. package/src/open.ts +19 -12
  39. package/src/parts-comment-crops.ts +126 -31
  40. package/src/parts-comment.ts +351 -28
  41. package/src/parts-server.ts +19 -7
  42. package/src/parts-view.ts +588 -109
  43. package/src/scene-inspection.ts +50 -0
  44. package/src/server.ts +31 -22
  45. package/src/session.ts +58 -0
  46. package/src/stage-comment.ts +48 -1
  47. package/src/stage-parts.ts +23 -11
  48. package/web/animation-inspection.ts +1 -1
  49. package/web/bones-panel.ts +1 -3
  50. package/web/catalog-en.ts +175 -39
  51. package/web/catalog-ko.ts +175 -39
  52. package/web/cloth-panel.ts +1 -2
  53. package/web/compare.css +3 -13
  54. package/web/compare.html +3 -3
  55. package/web/compare.ts +69 -64
  56. package/web/cuts-panel.ts +1 -3
  57. package/web/density-strip-panel.ts +1 -2
  58. package/web/direction-panel.ts +22 -6
  59. package/web/i18n.ts +13 -1
  60. package/web/idle-panel.ts +1 -2
  61. package/web/index.html +1 -5
  62. package/web/inspection-persistence.ts +2 -1
  63. package/web/inspector-blocks.ts +149 -40
  64. package/web/instance-access.ts +24 -5
  65. package/web/interview-panel.ts +224 -175
  66. package/web/job-rig-capture.ts +164 -21
  67. package/web/job-rig-screen.ts +344 -0
  68. package/web/job-session.ts +611 -1443
  69. package/web/main.ts +614 -151
  70. package/web/mesh-panel.ts +1 -2
  71. package/web/owner-workspace.ts +88 -109
  72. package/web/part-selection.ts +47 -6
  73. package/web/part-thumbnails.ts +20 -6
  74. package/web/parts-render.ts +26 -19
  75. package/web/parts-viewport-provider.ts +181 -7
  76. package/web/physics-panel.ts +1 -2
  77. package/web/readings-panel.ts +1 -2
  78. package/web/requirements-panel.ts +1 -3
  79. package/web/retained-frame-stage.ts +105 -0
  80. package/web/retarget-panel.ts +2 -3
  81. package/web/rig-fields-panel.ts +1 -2
  82. package/web/rig-host.ts +64 -0
  83. package/web/rig-viewport-provider.ts +65 -16
  84. package/web/scene-plates.ts +57 -4
  85. package/web/stage-comments.ts +103 -46
  86. package/web/styles.css +117 -63
  87. package/web/view-controls.ts +201 -12
  88. package/web/viewport-capture.ts +12 -2
  89. package/web/viewport-controller.ts +107 -27
  90. package/web/viewport-pair.ts +2 -1
  91. package/web/workspace-preferences.ts +5 -4
  92. package/web/workspace-ui.ts +151 -19
  93. package/src/front-worker.ts +0 -2
  94. package/src/interview-server.ts +0 -54
  95. package/src/job-hub.ts +0 -304
  96. package/src/job-image-set.ts +0 -50
  97. package/web/interview.css +0 -28
  98. package/web/interview.html +0 -17
  99. package/web/interview.ts +0 -40
  100. package/web/job-hub.css +0 -14
  101. package/web/job-hub.html +0 -5
  102. package/web/job-hub.ts +0 -179
  103. package/web/owner-workspace.css +0 -14
  104. package/web/owner-workspace.html +0 -5
  105. package/web/parts-flags.ts +0 -48
  106. package/web/parts.css +0 -104
  107. package/web/parts.html +0 -49
  108. package/web/parts.ts +0 -604
  109. package/web/stage-nav.ts +0 -136
package/src/job-api.ts CHANGED
@@ -1,10 +1,11 @@
1
+ import {checkpointEvidenceFields} from './job-checkpoint-evidence.ts';
1
2
  import { createHash, timingSafeEqual } from 'node:crypto';
2
3
  import {
3
4
  JOB_ACT_SCHEMA, JOB_API_SCHEMA, JOB_API_V3_SCHEMA, JOB_ENABLED_ACT_KINDS, JOB_PARTS_ENUMERATOR_RANGE,
4
- JOB_PLAN_BOUND_SIGNOFF_STAGES, JOB_RECORD_ACT_SCHEMA, JOB_RECORD_INSTANCE_SCHEMA, JOB_RECORD_SOURCE_SCHEMA,
5
+ JOB_PLAN_BOUND_SIGNOFF_STAGES, JOB_RECORD_SIGNOFF_STAGES, JOB_RECORD_ACT_SCHEMA, JOB_RECORD_INSTANCE_SCHEMA, JOB_RECORD_SOURCE_SCHEMA,
5
6
  JOB_RESERVED_ACT_KINDS,
6
7
  type AgentRequestV3, type FetchActRequestV3, type JobAgentRequest, type JobApiSchema,
7
- type JobDisplayAcknowledgment, type JobErrorCode, type JobFetchActRequest, type JobFileIdentity,
8
+ type JobCheckpointEvidence, type JobDisplayAcknowledgment, type JobErrorCode, type JobFetchActRequest, type JobFileIdentity,
8
9
  type JobHostPorts, type JobHumanAuthority, type JobInterviewDiagnostic, type JobInterviewDiagnostics,
9
10
  type JobInterviewJson, type JobInterviewRecord, type JobPlanIdentity, type JobPublicationMode,
10
11
  type JobPublishRequest, type JobResult, type JobSelector, type JobSha256, type JobSubject,
@@ -16,6 +17,16 @@ import {
16
17
  } from './job-contract.ts';
17
18
  import { JobError } from './job-store.ts';
18
19
  import type { JobSession } from './job-session.ts';
20
+ import { JOB_COMMENTS_ACT_SCHEMA, JOB_COMMENT_CONTEXT_ACT_SCHEMA, type JobCommentContext, type JobContextComment,
21
+ type JobContextCommentsAct, type JobComment, type JobCommentAnchor, type JobCommentsAct,
22
+ type SourceV3, type JobRigStill } from './job-contract.ts';
23
+ import { parseFeedback } from './session.ts';
24
+ import { parsePartsIssue } from './parts-comment.ts';
25
+ import { parseStageComment, hasStageComment, projectComments, commentModes } from './stage-comment.ts';
26
+ import { validatePngCrop, validatePngCropMetadata } from './comment-crops.ts';
27
+ import {parseJobPartsIdentity} from './job-source.ts';
28
+ import {parseControlPart, parseControlView} from './control.ts';
29
+ import {EMIT_UNPINNED_CREATE_FIELDS} from './create-pin-gate.ts';
19
30
 
20
31
  export type {
21
32
  JobInterviewJson,
@@ -245,7 +256,7 @@ export function parseRecordSubject(value: unknown): RecordSubject {
245
256
  case 'signoff': {
246
257
  jobObject(item, ['kind', 'stage']);
247
258
  const stage = jobId(item.stage);
248
- if (!(JOB_PLAN_BOUND_SIGNOFF_STAGES as readonly string[]).includes(stage)) {
259
+ if (!(JOB_RECORD_SIGNOFF_STAGES as readonly string[]).includes(stage)) {
249
260
  throw new JobError('JOB_ASK_INVALID');
250
261
  }
251
262
  return { kind: 'signoff', stage: stage as RecordSignoffStage };
@@ -391,13 +402,14 @@ function asCode<Value>(fn: () => Value, code: JobErrorCode): Value {
391
402
  }
392
403
  }
393
404
 
394
- function exactObject(
405
+ export function exactObject(
395
406
  value: unknown,
396
407
  keys: readonly string[],
397
408
  code: JobErrorCode,
409
+ optional: readonly string[] = [],
398
410
  ): Record<string, unknown> {
399
- const item = asCode(() => jobObject(value, keys), code);
400
- if (Object.keys(item).length !== keys.length || keys.some(key => item[key] === undefined)) {
411
+ const item = asCode(() => jobObject(value, [...keys, ...optional]), code);
412
+ if (keys.some(key => !Object.hasOwn(item, key) || item[key] === undefined)) {
401
413
  throw new JobError(code);
402
414
  }
403
415
  return item;
@@ -648,6 +660,7 @@ type ParsedRecordPayload =
648
660
  }
649
661
  | {
650
662
  readonly kind: 'plan';
663
+ readonly checkpointEvidence?: readonly JobCheckpointEvidence[];
651
664
  readonly inputs: readonly JobFileIdentity[];
652
665
  readonly files: readonly JobFileIdentity[];
653
666
  readonly plan: JobPlanIdentity;
@@ -661,17 +674,18 @@ function parseRecordClosureAndSubjects(
661
674
  rawSubjects: unknown,
662
675
  selection: RecordResult,
663
676
  checkedRecord?: ProjectRecord,
677
+ evidenceHolder: object = {},
664
678
  ): ParsedRecordPayload {
665
679
  const { inputs, files } = parseFileClosure(rawInputs, rawFiles, checkedRecord, 'JOB_SOURCE_MISMATCH');
666
680
  if (selection.kind === 'option-set') {
667
- if (rawPlan !== null) throw new JobError('JOB_SOURCE_MISMATCH');
681
+ if (rawPlan !== null || 'checkpointEvidence' in evidenceHolder) throw new JobError('JOB_SOURCE_MISMATCH');
668
682
  const subjects = parseOptionSubjects(rawSubjects, selection, 'JOB_SOURCE_MISMATCH');
669
683
  return { kind: 'option-set', inputs, files, plan: null, subjects };
670
684
  }
671
685
  if (rawPlan === null) throw new JobError('JOB_SOURCE_MISMATCH');
672
686
  const { plan, stepIds } = parsePlanIdentity(rawPlan, 'JOB_SOURCE_MISMATCH');
673
687
  const subjects = parsePlanSubjects(rawSubjects, stepIds, 'JOB_SOURCE_MISMATCH');
674
- return { kind: 'plan', inputs, files, plan, subjects };
688
+ return { kind: 'plan', inputs, files, plan, subjects, ...checkpointEvidenceFields(evidenceHolder, plan, subjects, files) };
675
689
  }
676
690
 
677
691
  export function parseRecordPublishedContext(
@@ -696,7 +710,7 @@ export function parseRecordPublishedContext(
696
710
  ): OptionContext | PlanContext {
697
711
  const selection = parseRecordResult(result);
698
712
  const checkedRecord = record === undefined ? undefined : parseProjectRecord(record, 'JOB_SOURCE_MISMATCH');
699
- const item = exactObject(value, ['label', 'parts', 'inputs', 'files', 'plan', 'subjects'], 'JOB_SOURCE_MISMATCH');
713
+ const item = exactObject(value, ['label', 'parts', 'inputs', 'files', 'plan', 'subjects'], 'JOB_SOURCE_MISMATCH', ['checkpointEvidence']);
700
714
  const label = asCode(() => jobText(item.label), 'JOB_SOURCE_MISMATCH');
701
715
  const parts = parseRecordPartsIdentity(item.parts, 'JOB_SOURCE_MISMATCH');
702
716
  const body = parseRecordClosureAndSubjects(
@@ -706,11 +720,13 @@ export function parseRecordPublishedContext(
706
720
  item.subjects,
707
721
  selection,
708
722
  checkedRecord,
723
+ item,
709
724
  );
710
725
  if (body.kind === 'option-set') {
711
726
  return { label, parts, inputs: body.inputs, files: body.files, plan: null, subjects: body.subjects };
712
727
  }
713
- return { label, parts, inputs: body.inputs, files: body.files, plan: body.plan, subjects: body.subjects };
728
+ return { label, parts, inputs: body.inputs, files: body.files, plan: body.plan, subjects: body.subjects,
729
+ ...(body.checkpointEvidence ? {checkpointEvidence: body.checkpointEvidence} : {}) };
714
730
  }
715
731
 
716
732
  export function assertEqualRecordContexts(
@@ -734,6 +750,7 @@ export function assertEqualRecordContexts(
734
750
  }
735
751
 
736
752
  export interface RecordSourceDigestInput {
753
+ readonly checkpointEvidence?: readonly JobCheckpointEvidence[];
737
754
  readonly schema?: typeof JOB_RECORD_SOURCE_SCHEMA;
738
755
  readonly sourceHash?: JobSha256;
739
756
  readonly projectHash?: JobSha256;
@@ -764,6 +781,7 @@ export function serializeRecordSourceDigestPayload(input: RecordSourceDigestInpu
764
781
  'plan',
765
782
  'subjects',
766
783
  'files',
784
+ 'checkpointEvidence',
767
785
  ]),
768
786
  'JOB_SOURCE_MISMATCH',
769
787
  );
@@ -787,7 +805,7 @@ export function serializeRecordSourceDigestPayload(input: RecordSourceDigestInpu
787
805
  const { inputs, files, byPath } = parseFileClosure(item.inputs, item.files, record, 'JOB_SOURCE_MISMATCH');
788
806
 
789
807
  if (selection.kind === 'option-set') {
790
- if (item.plan !== null || item.optionSet === null || item.optionSetFile === null) {
808
+ if ('checkpointEvidence' in item || item.plan !== null || item.optionSet === null || item.optionSetFile === null) {
791
809
  throw new JobError('JOB_SOURCE_MISMATCH');
792
810
  }
793
811
  const rawOptionSet = exactObject(item.optionSet, ['id', 'sha256'], 'JOB_SOURCE_MISMATCH');
@@ -831,6 +849,7 @@ export function serializeRecordSourceDigestPayload(input: RecordSourceDigestInpu
831
849
  plan,
832
850
  subjects,
833
851
  files,
852
+ ...checkpointEvidenceFields(item, plan, subjects, files),
834
853
  });
835
854
  }
836
855
 
@@ -896,6 +915,7 @@ function assembleRecordSource(
896
915
  plan: body.plan,
897
916
  subjects: body.subjects,
898
917
  files: body.files,
918
+ ...(body.checkpointEvidence ? {checkpointEvidence: body.checkpointEvidence} : {}),
899
919
  });
900
920
  return {
901
921
  sourceHash,
@@ -903,6 +923,7 @@ function assembleRecordSource(
903
923
  record,
904
924
  inputs: body.inputs,
905
925
  files: body.files,
926
+ ...(body.checkpointEvidence ? {checkpointEvidence: body.checkpointEvidence} : {}),
906
927
  subject: 'plan',
907
928
  selection: { kind: 'plan' },
908
929
  optionSet: null,
@@ -948,6 +969,7 @@ export function buildRecordSource(input: {
948
969
  files: context.files,
949
970
  plan: context.plan,
950
971
  subjects: context.subjects,
972
+ ...(context.checkpointEvidence ? {checkpointEvidence: context.checkpointEvidence} : {}),
951
973
  };
952
974
  return assembleRecordSource(record, selection, body, input.optionSetFile);
953
975
  }
@@ -969,6 +991,7 @@ export function parseRecordSource(value: unknown): RecordSource {
969
991
  'subjects',
970
992
  ],
971
993
  'JOB_SOURCE_MISMATCH',
994
+ ['checkpointEvidence'],
972
995
  );
973
996
  const record = parseProjectRecord(item.record, 'JOB_SOURCE_MISMATCH');
974
997
  const projectHash = asCode(() => jobSha(item.projectHash), 'JOB_SOURCE_MISMATCH');
@@ -983,6 +1006,7 @@ export function parseRecordSource(value: unknown): RecordSource {
983
1006
  item.subjects,
984
1007
  selection,
985
1008
  record,
1009
+ item,
986
1010
  );
987
1011
  if (selection.kind === 'option-set') {
988
1012
  const rawOptionSet = exactObject(item.optionSet, ['id', 'sha256'], 'JOB_SOURCE_MISMATCH');
@@ -1126,7 +1150,7 @@ export function parseRecordAct(value: unknown): RecordAct {
1126
1150
  if (source.subject !== 'plan' || source.plan.steps.length === 0) throw new JobError('JOB_ACT_INVALID');
1127
1151
  const rawValue = exactObject(item.value, ['stage', 'decision', 'words'], 'JOB_ACT_INVALID');
1128
1152
  const stage = asCode(() => jobId(rawValue.stage), 'JOB_ACT_INVALID');
1129
- if (!(JOB_PLAN_BOUND_SIGNOFF_STAGES as readonly string[]).includes(stage) || rawValue.decision !== 'approved') {
1153
+ if (!(JOB_RECORD_SIGNOFF_STAGES as readonly string[]).includes(stage) || rawValue.decision !== 'approved') {
1130
1154
  throw new JobError('JOB_ACT_INVALID');
1131
1155
  }
1132
1156
  asCode(() => validateRecordAskSubject({ kind: 'signoff', stage }, source), 'JOB_ACT_INVALID');
@@ -1167,6 +1191,281 @@ export function parseRecordAct(value: unknown): RecordAct {
1167
1191
  throw new JobError('JOB_ACT_INVALID');
1168
1192
  }
1169
1193
 
1194
+ /** Shared closed object reader for the comments contract; legacy readers retain their rules. */
1195
+ export function commentsObject(value: unknown, keys: readonly string[], optional: readonly string[] = []): Record<string, unknown> {
1196
+ if (!value || typeof value !== 'object' || Object.getPrototypeOf(value) !== Object.prototype) throw new JobError('JOB_ACT_INVALID');
1197
+ return exactObject(value, keys, 'JOB_ACT_INVALID', optional);
1198
+ }
1199
+
1200
+ function commentCrop(value: unknown): void {
1201
+ const crop = commentsObject(value, ['path', 'sha256', 'width', 'height'], ['png']);
1202
+ jobSha(crop.sha256);
1203
+ validatePngCropMetadata(crop as unknown as Parameters<typeof validatePngCropMetadata>[0]);
1204
+ if (Object.hasOwn(crop, 'png')) validatePngCrop(crop as unknown as Parameters<typeof validatePngCrop>[0]);
1205
+ }
1206
+
1207
+ /** Both checkpoint values and pins obey the source's declared checkpoint mapping. */
1208
+ function assertCommentsCheckpointBinding(source: SourceV3, checkpointId: string, planStepId: string): void {
1209
+ if (!source.plan?.steps.some(step => step.id === planStepId) ||
1210
+ 'record' in source && checkpointId !== planStepId) throw new JobError('JOB_ACT_INVALID');
1211
+ const evidence = source.checkpointEvidence?.find(packet => packet.checkpointId === checkpointId);
1212
+ if (evidence && evidence.planStepId !== planStepId) throw new JobError('JOB_ACT_INVALID');
1213
+ }
1214
+
1215
+ function parseCommentAnchor(raw: unknown, text: string, source?: SourceV3 | string): JobCommentAnchor {
1216
+ const item = commentsObject(raw, [], Object.keys(raw && typeof raw === 'object' ? raw : {}));
1217
+ const sourceHash = typeof source === 'string' ? source : source?.sourceHash;
1218
+ if ('schema' in item) {
1219
+ commentsObject(item, ['schema', 'id', 'parts', 'sourceHash', 'rigRegion', 'imageRegion', 'view', 'crop', 'nativeCrop']);
1220
+ const issue = parsePartsIssue({...item, summary: text}, true, false, false);
1221
+ if (issue.crop.png !== undefined) validatePngCrop(issue.crop as Parameters<typeof validatePngCrop>[0]);
1222
+ if (sourceHash && issue.sourceHash !== sourceHash) throw new JobError('JOB_ACT_SOURCE_STALE');
1223
+ if (source && typeof source !== 'string' && !('record' in source)) {
1224
+ if (!source.parts || issue.parts.some(part => !source.parts!.images.some(image =>
1225
+ image.role === 'part' && image.path === `parts/${part.name}.png` && image.sha256 === part.imageHash))) throw new JobError('JOB_ACT_SOURCE_STALE');
1226
+ }
1227
+ const {summary: _summary, ...anchor} = issue;
1228
+ return anchor;
1229
+ }
1230
+ if ('frameStart' in item) {
1231
+ commentsObject(item, ['id', 'frameStart', 'frameEnd', 'target', 'category'], ['context', 'side']);
1232
+ commentsObject(item.target, ['kind', 'name']);
1233
+ jobId(item.id);
1234
+ if ('side' in item && item.side !== 'a' && item.side !== 'b') throw new JobError('JOB_ACT_INVALID');
1235
+ const feedback = parseFeedback({...item, summary: text});
1236
+ const context = feedback.context as Record<string, unknown> | undefined;
1237
+ if (hasStageComment(context?.comment)) {
1238
+ const mark = parseStageComment(context!.comment);
1239
+ validatePngCrop(mark.crop);
1240
+ if (sourceHash && mark.sourceHash !== sourceHash) throw new JobError('JOB_ACT_SOURCE_STALE');
1241
+ if (source && typeof source !== 'string' && !('record' in source) &&
1242
+ mark.viewport !== 'reference' && mark.modelHash !== source.model?.sha256) throw new JobError('JOB_ACT_SOURCE_STALE');
1243
+ }
1244
+ const {summary: _summary, ...anchor} = feedback;
1245
+ return {...anchor, ...('side' in item ? {side: item.side as 'a' | 'b'} : {})};
1246
+ }
1247
+ if ('checkpointId' in item) {
1248
+ commentsObject(item, ['checkpointId', 'planStepId']);
1249
+ const checkpointId = jobId(item.checkpointId), planStepId = jobId(item.planStepId);
1250
+ if (source && typeof source !== 'string') assertCommentsCheckpointBinding(source, checkpointId, planStepId);
1251
+ return {checkpointId, planStepId};
1252
+ }
1253
+ if ('name' in item) {
1254
+ commentsObject(item, ['name'], ['imageRegion', 'crop', 'nativeCrop']);
1255
+ const name = jobText(item.name);
1256
+ if (source) throw new JobError('JOB_ACT_SOURCE_STALE');
1257
+ if (Object.keys(item).length === 1) return {name};
1258
+ commentsObject(item, ['name', 'imageRegion', 'crop', 'nativeCrop']);
1259
+ const region = commentsObject(item.imageRegion, ['x', 'y', 'width', 'height']);
1260
+ for (const axis of ['x', 'y', 'width', 'height']) jobInteger(region[axis]);
1261
+ if (!region.width || !region.height || Number(region.width) * Number(region.height) > 16777216) throw new JobError('JOB_ACT_INVALID');
1262
+ commentsObject(item.nativeCrop, ['path', 'sha256', 'width', 'height']);
1263
+ commentCrop(item.crop); commentCrop(item.nativeCrop);
1264
+ if ((item.nativeCrop as {width: number}).width !== region.width ||
1265
+ (item.nativeCrop as {height: number}).height !== region.height) throw new JobError('JOB_ACT_INVALID');
1266
+ return structuredClone(item) as unknown as JobCommentAnchor;
1267
+ }
1268
+ throw new JobError('JOB_ACT_INVALID');
1269
+ }
1270
+
1271
+ /** Structural/source-identity decoding only. Original asset freshness remains with the retained-source owner. */
1272
+ export function parseComments(value: unknown, source?: SourceV3 | string): JobComment[] {
1273
+ return decodeComments(value, source, false);
1274
+ }
1275
+
1276
+ function decodeComments(value: unknown, source: SourceV3 | string | undefined, withContext: false): JobComment[];
1277
+ function decodeComments(value: unknown, source: SourceV3 | string | undefined, withContext: true): JobContextComment[];
1278
+ function decodeComments(value: unknown, source: SourceV3 | string | undefined, withContext: boolean): JobContextComment[] {
1279
+ return asCode(() => {
1280
+ if (!Array.isArray(value) || value.length > 1000) throw new JobError('JOB_ACT_INVALID');
1281
+ const ids = new Set<string>();
1282
+ const comments: JobContextComment[] = value.map(raw => {
1283
+ const item = commentsObject(raw, ['text'], withContext ? ['anchor', 'context'] : ['anchor']);
1284
+ const text = parseActWords(item.text, 'JOB_ACT_INVALID');
1285
+ if (!text.trim()) throw new JobError('JOB_ACT_INVALID');
1286
+ const context = Object.hasOwn(item, 'context') ? {context: parseCommentContext(item.context, source)} : {};
1287
+ if (!Object.hasOwn(item, 'anchor')) return {text, ...context};
1288
+ const anchor = parseCommentAnchor(item.anchor, text, source);
1289
+ if ('id' in anchor) {
1290
+ if (ids.has(anchor.id)) throw new JobError('JOB_ACT_INVALID');
1291
+ ids.add(anchor.id);
1292
+ }
1293
+ return {text, anchor, ...context};
1294
+ });
1295
+ // The signed projection covers text and anchor only; context restores a view and is not signed text.
1296
+ projectComments(comments.map(({text, anchor}) => anchor === undefined ? {text} : {text, anchor}));
1297
+ return comments;
1298
+ }, 'JOB_ACT_INVALID');
1299
+ }
1300
+
1301
+ /** act@7 comment context. Each field reuses the decoder of the pin or restore path it copies. */
1302
+ function parseCommentContext(raw: unknown, source?: SourceV3 | string): JobCommentContext {
1303
+ const item = commentsObject(raw, [], ['subject', 'mode', 'tab', 'part', 'region', 'viewMode', 'camera', 'frame']);
1304
+ if (!Object.keys(item).length) throw new JobError('JOB_ACT_INVALID');
1305
+ const out: Record<string, unknown> = {};
1306
+ if ('subject' in item) {
1307
+ const subject = commentsObject(item.subject, ['ask', 'sourceHash'], ['selector']);
1308
+ const ask = parseJobSubject(subject.ask), sourceHash = jobSha(subject.sourceHash);
1309
+ const selector = 'selector' in subject ? parseJobSelector(subject.selector) : undefined;
1310
+ if (selector === null) throw new JobError('JOB_ACT_INVALID');
1311
+ const bound = typeof source === 'string' ? source : source?.sourceHash;
1312
+ if (bound && sourceHash !== bound) throw new JobError('JOB_ACT_SOURCE_STALE');
1313
+ if (selector && source && typeof source !== 'string' && !('record' in source) &&
1314
+ JSON.stringify(selector) !== JSON.stringify(source.selector)) throw new JobError('JOB_ACT_SOURCE_STALE');
1315
+ out.subject = {ask, sourceHash, ...(selector ? {selector} : {})};
1316
+ }
1317
+ if ('mode' in item) {
1318
+ if (!(commentModes as readonly unknown[]).includes(item.mode)) throw new JobError('JOB_ACT_INVALID');
1319
+ out.mode = item.mode;
1320
+ }
1321
+ if ('tab' in item) {
1322
+ // The inspector values parseBookmark accepts (web/inspection-persistence.ts).
1323
+ if (!['view', 'rig', 'playback', 'feedback'].includes(item.tab as string)) throw new JobError('JOB_ACT_INVALID');
1324
+ out.tab = item.tab;
1325
+ }
1326
+ if ('part' in item) {
1327
+ const part = parseControlPart(item.part);
1328
+ if (!part) throw new JobError('JOB_ACT_INVALID');
1329
+ out.part = part;
1330
+ }
1331
+ if ('region' in item) {
1332
+ const region = commentsObject(item.region, ['x', 'y', 'width', 'height']);
1333
+ for (const axis of ['x', 'y', 'width', 'height']) {
1334
+ const n = region[axis];
1335
+ if (typeof n !== 'number' || !Number.isFinite(n) || Math.abs(n) > Number.MAX_SAFE_INTEGER) throw new JobError('JOB_ACT_INVALID');
1336
+ }
1337
+ if ((region.width as number) < 0 || (region.height as number) < 0) throw new JobError('JOB_ACT_INVALID');
1338
+ out.region = {x: region.x, y: region.y, width: region.width, height: region.height};
1339
+ }
1340
+ if ('viewMode' in item) {
1341
+ if (item.viewMode !== 'item' && item.viewMode !== 'assembled') throw new JobError('JOB_ACT_INVALID');
1342
+ out.viewMode = item.viewMode;
1343
+ }
1344
+ if ('camera' in item) {
1345
+ const space = (item.camera as {space?: unknown} | null)?.space;
1346
+ if (space !== 'world' && space !== 'image') throw new JobError('JOB_ACT_INVALID');
1347
+ const cameras = {rig: null, a: null, b: null, reference: null, [space === 'world' ? 'rig' : 'reference']: item.camera};
1348
+ const view = parseControlView({schema: 'rig-review-view/1', cameras});
1349
+ out.camera = space === 'world' ? view.cameras.rig : view.cameras.reference;
1350
+ }
1351
+ if ('frame' in item) {
1352
+ const frame = commentsObject(item.frame, ['index', 'basis']);
1353
+ if (!Number.isSafeInteger(frame.index) || (frame.index as number) < 0 ||
1354
+ (frame.basis !== 'producer' && frame.basis !== 'reference')) throw new JobError('JOB_ACT_INVALID');
1355
+ out.frame = {index: frame.index, basis: frame.basis};
1356
+ }
1357
+ return out as JobCommentContext;
1358
+ }
1359
+
1360
+ function commentsSource(raw: unknown): Exclude<SourceV3, OptionSource> {
1361
+ if (isRecordSource(raw)) {
1362
+ const record = parseRecordSource(raw);
1363
+ if (record.subject !== 'plan') throw new JobError('JOB_ACT_INVALID');
1364
+ return record;
1365
+ }
1366
+ const common = ['sourceHash', 'projectHash', 'package', 'direction', 'optionSet', 'appliedResult', 'plan', 'parts'];
1367
+ const item = commentsObject(raw, [...common, 'selector', 'model'], ['checkpointEvidence']);
1368
+ jobSha(item.sourceHash); if (item.projectHash !== null) jobSha(item.projectHash);
1369
+ const pkg = commentsObject(item.package, ['id', 'revision']); jobText(pkg.id); jobText(pkg.revision);
1370
+ for (const key of ['direction', 'model']) if (item[key] !== null) parseFileRow(item[key], 'JOB_ACT_INVALID');
1371
+ parseJobSelector(item.selector);
1372
+ if (item.optionSet !== null) {
1373
+ const set = commentsObject(item.optionSet, ['id', 'sha256']); jobId(set.id); jobSha(set.sha256);
1374
+ }
1375
+ if (item.appliedResult !== null) {
1376
+ const applied = commentsObject(item.appliedResult, ['id', 'modelHash']); jobId(applied.id); jobSha(applied.modelHash);
1377
+ }
1378
+ if (item.plan !== null) parsePlanIdentity(item.plan, 'JOB_ACT_INVALID');
1379
+ if (item.parts !== null) parseJobPartsIdentity(item.parts);
1380
+ if ('checkpointEvidence' in item) {
1381
+ if (!Array.isArray(item.checkpointEvidence)) throw new JobError('JOB_ACT_INVALID');
1382
+ // Validate the declared packet with the existing codec. Actual closure seals remain
1383
+ // with the retained-source owner; a decoder has neither files nor source authority.
1384
+ const declarations = item.checkpointEvidence.map(raw => commentsObject(raw,
1385
+ ['schema', 'checkpointId', 'planStepId', 'tiles', 'table', 'routesText', 'recommendationText']));
1386
+ const subjects = declarations.map(row => ({kind: 'checkpoint' as const, checkpointId: jobId(row.checkpointId), planStepId: jobId(row.planStepId)}));
1387
+ const files = declarations.flatMap(row => {
1388
+ if (!Array.isArray(row.tiles)) throw new JobError('JOB_ACT_INVALID');
1389
+ return [...row.tiles, row.table].map(file => parseFileRow(
1390
+ {path: (file as JobFileIdentity)?.path, sha256: (file as JobFileIdentity)?.sha256}, 'JOB_ACT_INVALID'));
1391
+ });
1392
+ checkpointEvidenceFields(item, item.plan as JobPlanIdentity | null, subjects, files);
1393
+ }
1394
+ return structuredClone(item) as unknown as Exclude<SourceV3, OptionSource>;
1395
+ }
1396
+
1397
+ /** Public @6 decoder. The UI finalizers write checkpoint, parts, rig/post verdict and signoff acts at @6 (#713). */
1398
+ export function parseCommentsAct(raw: unknown): JobCommentsAct {
1399
+ return decodeCommentsAct(raw, false) as JobCommentsAct;
1400
+ }
1401
+
1402
+ /** Public @7 decoder: the @6 rules plus an optional `context` on each comment. @6 input refuses. */
1403
+ export function parseContextCommentsAct(raw: unknown): JobContextCommentsAct {
1404
+ return decodeCommentsAct(raw, true) as JobContextCommentsAct;
1405
+ }
1406
+
1407
+ /** The comments act a writer sends. With EMIT_UNPINNED_CREATE_FIELDS off, contexts are dropped and @6 goes out. */
1408
+ export function commentsActForEmission(act: JobCommentsAct | JobContextCommentsAct,
1409
+ emitUnpinned: boolean = EMIT_UNPINNED_CREATE_FIELDS): JobCommentsAct | JobContextCommentsAct {
1410
+ const value = act.value as {comments: readonly JobContextComment[]};
1411
+ const comments = value.comments.map(({context, ...comment}) => emitUnpinned && context ? {...comment, context} : comment);
1412
+ const schema = emitUnpinned && comments.some(comment => 'context' in comment) ? JOB_COMMENT_CONTEXT_ACT_SCHEMA : JOB_COMMENTS_ACT_SCHEMA;
1413
+ const next = {...structuredClone(act), schema, value: {...structuredClone(act.value), comments: structuredClone(comments)}};
1414
+ return schema === JOB_COMMENTS_ACT_SCHEMA ? parseCommentsAct(next) : parseContextCommentsAct(next);
1415
+ }
1416
+
1417
+ function decodeCommentsAct(raw: unknown, withContext: boolean): JobCommentsAct | JobContextCommentsAct {
1418
+ return asCode(() => {
1419
+ const item = commentsObject(raw, ['schema', 'actId', 'jobId', 'askId', 'publicationId', 'kind', 'authority', 'at', 'source', 'value'], ['still']);
1420
+ if (item.schema !== (withContext ? JOB_COMMENT_CONTEXT_ACT_SCHEMA : JOB_COMMENTS_ACT_SCHEMA)) throw new JobError('JOB_ACT_INVALID');
1421
+ for (const key of ['actId', 'jobId', 'askId', 'publicationId']) jobId(item[key]);
1422
+ parseHumanAuthority(item.authority, 'JOB_ACT_INVALID');
1423
+ if (typeof item.at !== 'string' || !Number.isFinite(Date.parse(item.at))) throw new JobError('JOB_ACT_INVALID');
1424
+ const source = commentsSource(item.source);
1425
+ const fields: Record<string, readonly string[]> = {
1426
+ checkpoint: ['checkpointId', 'planStepId', 'outcome', 'comments'],
1427
+ 'parts-verdict': ['verdict', 'comments'], 'review-verdict': ['stage', 'verdict', 'comments'],
1428
+ signoff: ['stage', 'decision', 'comments'], reopen: ['stage', 'comments'],
1429
+ };
1430
+ const keys = typeof item.kind === 'string' && Object.hasOwn(fields, item.kind) ? fields[item.kind] : undefined;
1431
+ if (!keys) throw new JobError('JOB_ACT_INVALID');
1432
+ const value = commentsObject(item.value, keys);
1433
+ const comments = withContext ? decodeComments(value.comments, source, true) : parseComments(value.comments, source);
1434
+ if (comments.some(comment => comment.anchor && 'side' in comment.anchor)) throw new JobError('JOB_ACT_INVALID');
1435
+ if ((comments as readonly JobContextComment[]).some(comment => comment.context?.subject &&
1436
+ comment.context.subject.ask.kind !== item.kind)) throw new JobError('JOB_ACT_INVALID');
1437
+ if (item.kind === 'checkpoint') {
1438
+ const checkpointId = jobId(value.checkpointId), planStepId = jobId(value.planStepId);
1439
+ if (typeof value.outcome !== 'string' || !['pass', 'fail'].includes(value.outcome)) throw new JobError('JOB_ACT_INVALID');
1440
+ assertCommentsCheckpointBinding(source, checkpointId, planStepId);
1441
+ } else if (item.kind === 'parts-verdict') {
1442
+ if ('record' in source || source.selector?.kind !== 'draft' || !source.parts || !source.projectHash ||
1443
+ typeof value.verdict !== 'string' || !['approved', 'changes-requested'].includes(value.verdict)) throw new JobError('JOB_ACT_INVALID');
1444
+ const issues = comments.filter(comment => comment.anchor && 'schema' in comment.anchor).length;
1445
+ if ((value.verdict === 'approved') !== (issues === 0)) throw new JobError('JOB_ACT_INVALID');
1446
+ } else if (item.kind === 'review-verdict') {
1447
+ if ('record' in source || typeof value.verdict !== 'string' || !['pending', 'approved', 'changes-requested'].includes(value.verdict)) throw new JobError('JOB_ACT_INVALID');
1448
+ if (!source.model || (value.stage === 'rig-review' ? source.selector?.kind !== 'rig' : value.stage !== 'direction-review' || source.selector?.kind !== 'post' || !source.direction)) throw new JobError('JOB_ACT_INVALID');
1449
+ } else {
1450
+ const stage = jobId(value.stage);
1451
+ if (item.kind === 'signoff' && value.decision !== 'approved') throw new JobError('JOB_ACT_INVALID');
1452
+ if (item.kind === 'reopen' && !('record' in source)) throw new JobError('JOB_ACT_INVALID');
1453
+ const planBoundStages = 'record' in source ? JOB_RECORD_SIGNOFF_STAGES : JOB_PLAN_BOUND_SIGNOFF_STAGES;
1454
+ if (item.kind === 'signoff' && (planBoundStages as readonly string[]).includes(stage) && !source.plan?.steps.length) throw new JobError('JOB_ACT_INVALID');
1455
+ }
1456
+ if ('record' in source) validateRecordAskSubject(item.kind === 'checkpoint' ? {kind: item.kind, checkpointId: value.checkpointId} :
1457
+ {kind: item.kind, stage: value.stage}, source);
1458
+ const rig = item.kind === 'review-verdict' && value.stage === 'rig-review';
1459
+ if (rig) {
1460
+ const still = commentsObject(item.still, ['path', 'sha256', 'camera', 'frame'], ['animation']);
1461
+ if (still.path !== jobSha(still.sha256) + '.png' || still.camera !== 'fixed' ||
1462
+ (still.frame === 'setup' ? 'animation' in still : typeof still.frame !== 'number' || !Number.isFinite(still.frame) ||
1463
+ still.frame < 0 || typeof still.animation !== 'string' || !still.animation)) throw new JobError('JOB_ACT_INVALID');
1464
+ } else if ('still' in item) throw new JobError('JOB_ACT_INVALID');
1465
+ return {...structuredClone(item), source, value: {...value, comments}} as unknown as JobCommentsAct | JobContextCommentsAct;
1466
+ }, 'JOB_ACT_INVALID');
1467
+ }
1468
+
1170
1469
  export async function jobBody(request: Request, maximum = jobBodyLimit): Promise<unknown> {
1171
1470
  if (!/^application\/json(?:\s*;|$)/i.test(request.headers.get('content-type') ?? '')) {
1172
1471
  throw new JobError('JOB_REQUEST_INVALID');
@@ -1192,7 +1491,10 @@ export async function jobBody(request: Request, maximum = jobBodyLimit): Promise
1192
1491
  chunks.push(value);
1193
1492
  }
1194
1493
  const value = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks)));
1195
- if (size > jobBodyLimit && (value?.kind !== 'review-verdict' || value?.value?.stage !== 'rig-review' || !value.capture)) {
1494
+ const hasCommentImages = ['parts-verdict', 'review-verdict', 'checkpoint', 'signoff', 'reopen'].includes(value?.kind) &&
1495
+ /"png":"data:image\/png;base64,/.test(JSON.stringify(value?.value));
1496
+ const rigCapture = value?.kind === 'review-verdict' && value?.value?.stage === 'rig-review' && value.capture;
1497
+ if (size > jobBodyLimit && !(maximum > jobBodyLimit && (rigCapture || hasCommentImages))) {
1196
1498
  throw new JobError('JOB_BODY_LIMIT');
1197
1499
  }
1198
1500
  return value;
@@ -1242,6 +1544,17 @@ export function createJobHostPorts(session: JobSession, origin: string): JobHost
1242
1544
  let input: JobAgentRequest | AgentRequestV3 | JobFetchActRequest | FetchActRequestV3 | null = null;
1243
1545
  let responseSchema: typeof JOB_API_SCHEMA | typeof JOB_API_V3_SCHEMA = session.apiSchema;
1244
1546
  try {
1547
+ const cropUrl = new URL(request.url);
1548
+ const crop = new RegExp('^' + base + '/comment-crops/([a-f0-9]{64})\\.png$').exec(cropUrl.pathname);
1549
+ if (crop && request.method === 'GET' && cropUrl.origin === origin && !cropUrl.search && !cropUrl.hash) {
1550
+ if (request.headers.get('sec-fetch-site') === 'cross-site' ||
1551
+ request.headers.get('origin') !== null && request.headers.get('origin') !== origin) {
1552
+ throw new JobError('JOB_SAME_ORIGIN_REQUIRED');
1553
+ }
1554
+ session.authorize('ui-evidence', request.headers.get('X-Review-Capability'));
1555
+ return new Response(new Uint8Array(session.readCommentCrop(crop[1]!)),
1556
+ {headers: {...responseHeaders, 'Content-Type': 'image/png'}});
1557
+ }
1245
1558
  gate(request, base + '/api', false);
1246
1559
  const body = await jobBody(request);
1247
1560
  const mode: JobPublicationMode =
@@ -0,0 +1,113 @@
1
+ import {realpathSync} from 'node:fs';
2
+ import type {JobCheckpointEvidence, JobCheckpointTable, JobFileIdentity, JobPlanIdentity, JobSubject, RecordSubject} from './job-contract.ts';
3
+ import {exactObject, jobHash, jobId, jobPath, jobSha} from './job-api.ts';
4
+ import {JobError} from './job-store.ts';
5
+ import {checkedPath, readRegular} from './interview-project.ts';
6
+ import {validatePngBytes} from './comment-crops.ts';
7
+
8
+ const evidenceSchema = 'rig-review-checkpoint-evidence/1';
9
+ const tableSchema = 'rig-review-checkpoint-table/1';
10
+
11
+ function evidenceText(value: unknown, max: number): string {
12
+ if (typeof value !== 'string' || !value.length || value.length > max || /[\x00-\x08\x0b-\x1f\x7f]/.test(value)) {
13
+ throw new JobError('JOB_SOURCE_MISMATCH', 'CHECKPOINT_EVIDENCE_TEXT_INVALID');
14
+ }
15
+ return value;
16
+ }
17
+
18
+ /** Canonical optional declaration. Absence must not materialize a historical field. */
19
+ export function checkpointEvidenceFields(holder: object, plan: JobPlanIdentity | null,
20
+ subjects: readonly (JobSubject | RecordSubject)[], files: readonly JobFileIdentity[]): {checkpointEvidence?: readonly JobCheckpointEvidence[]} {
21
+ if (!('checkpointEvidence' in holder)) return {};
22
+ try {
23
+ const raw = holder.checkpointEvidence;
24
+ if (!plan || !Array.isArray(raw) || raw.length < 1 || raw.length > 8) throw new Error('collection');
25
+ const seen = new Set<string>();
26
+ const checkpointEvidence = raw.map<JobCheckpointEvidence>(value => {
27
+ const item = exactObject(value, ['schema', 'checkpointId', 'planStepId', 'tiles', 'table', 'routesText', 'recommendationText'], 'JOB_SOURCE_MISMATCH');
28
+ const checkpointId = jobId(item.checkpointId), planStepId = jobId(item.planStepId);
29
+ if (item.schema !== evidenceSchema || seen.has(checkpointId) || !plan.steps.some(step => step.id === planStepId) ||
30
+ !subjects.some(subject => subject.kind === 'checkpoint' && subject.checkpointId === checkpointId &&
31
+ (('planStepId' in subject ? subject.planStepId : undefined) ?? subject.checkpointId) === planStepId)) throw new Error('association');
32
+ seen.add(checkpointId);
33
+ if (!Array.isArray(item.tiles) || item.tiles.length < 1 || item.tiles.length > 8) throw new Error('tiles');
34
+ const ids = new Set<string>();
35
+ const tiles = item.tiles.map(value => {
36
+ const tile = exactObject(value, ['id', 'label', 'path', 'sha256'], 'JOB_SOURCE_MISMATCH');
37
+ const id = jobId(tile.id);
38
+ if (ids.has(id)) throw new Error('duplicate tile');
39
+ ids.add(id);
40
+ return {id, label: evidenceText(tile.label, 512), path: jobPath(tile.path), sha256: jobSha(tile.sha256)};
41
+ });
42
+ const rawTable = exactObject(item.table, ['path', 'sha256'], 'JOB_SOURCE_MISMATCH', ['label']);
43
+ const table = {path: jobPath(rawTable.path), sha256: jobSha(rawTable.sha256),
44
+ ...('label' in rawTable ? {label: evidenceText(rawTable.label, 512)} : {})};
45
+ for (const file of [...tiles, table]) {
46
+ if (!files.some(seal => seal.path === file.path && seal.sha256 === file.sha256)) throw new Error('closure');
47
+ }
48
+ return {schema: evidenceSchema, checkpointId, planStepId, tiles, table,
49
+ routesText: evidenceText(item.routesText, 4096), recommendationText: evidenceText(item.recommendationText, 4096)};
50
+ });
51
+ if (Buffer.byteLength(JSON.stringify(checkpointEvidence)) > 32 * 1024) throw new Error('declaration bound');
52
+ return {checkpointEvidence};
53
+ } catch {
54
+ throw new JobError('JOB_SOURCE_MISMATCH', 'CHECKPOINT_EVIDENCE_INVALID');
55
+ }
56
+ }
57
+
58
+ /** The sealed document is the sole table body. Preserve columns, rows and scalars. */
59
+ export function parseCheckpointTable(bytes: Buffer): JobCheckpointTable {
60
+ try {
61
+ if (bytes.length > 256 * 1024) throw new Error('byte bound');
62
+ const item = exactObject(JSON.parse(new TextDecoder('utf-8', {fatal: true}).decode(bytes)), ['schema', 'columns', 'rows'], 'JOB_SOURCE_MISMATCH');
63
+ if (item.schema !== tableSchema || !Array.isArray(item.columns) || item.columns.length < 1 || item.columns.length > 32 ||
64
+ !Array.isArray(item.rows) || item.rows.length > 2048 || item.rows.length * item.columns.length > 16384) throw new Error('dimensions');
65
+ const columns = item.columns.map(value => evidenceText(value, 512));
66
+ const rows = item.rows.map(row => {
67
+ if (!Array.isArray(row) || row.length !== columns.length) throw new Error('row width');
68
+ return row.map(cell => {
69
+ if (typeof cell === 'string') {
70
+ if (cell.length > 2048 || /[\x00-\x08\x0b-\x1f\x7f]/.test(cell)) throw new Error('cell text');
71
+ } else if (cell !== null && typeof cell !== 'boolean' && !(typeof cell === 'number' && Number.isFinite(cell))) {
72
+ throw new Error('scalar');
73
+ }
74
+ return cell as string | number | boolean | null;
75
+ });
76
+ });
77
+ return {schema: tableSchema, columns, rows};
78
+ } catch {
79
+ throw new JobError('JOB_SOURCE_MISMATCH', 'CHECKPOINT_EVIDENCE_TABLE_INVALID');
80
+ }
81
+ }
82
+
83
+ /** Exact retained closure reads reuse regular-file, containment and descriptor bounds. */
84
+ export function readCheckpointEvidenceBytes(root: string, file: JobFileIdentity, limit: number): Buffer {
85
+ let bytes: Buffer;
86
+ try {
87
+ if (realpathSync(root) !== root) throw new Error('Noncanonical evidence root');
88
+ bytes = readRegular(checkedPath(root, file.path), limit);
89
+ }
90
+ catch { throw new JobError('JOB_SOURCE_UNRETAINABLE', 'CHECKPOINT_EVIDENCE_PATH_REFUSED'); }
91
+ if (jobHash(bytes) !== file.sha256) throw new JobError('JOB_SOURCE_MISMATCH', 'CHECKPOINT_EVIDENCE_HASH_MISMATCH');
92
+ return bytes;
93
+ }
94
+
95
+ /** Used before publication and metadata delivery. No table body enters durable state. */
96
+ export function checkpointEvidenceMetadata(root: string, evidence: readonly JobCheckpointEvidence[] | undefined) {
97
+ if (evidence === undefined) return {};
98
+ let tableBytes = 0;
99
+ const checkpointEvidence = evidence.map(packet => {
100
+ for (const tile of packet.tiles) {
101
+ const bytes = readCheckpointEvidenceBytes(root, tile, 8 * 1024 * 1024);
102
+ try { validatePngBytes(bytes, bytes.readUInt32BE(16), bytes.readUInt32BE(20)); }
103
+ catch { throw new JobError('JOB_SOURCE_MISMATCH', 'CHECKPOINT_EVIDENCE_PNG_INVALID'); }
104
+ }
105
+ const bytes = readCheckpointEvidenceBytes(root, packet.table, 256 * 1024);
106
+ tableBytes += bytes.length;
107
+ if (tableBytes > 512 * 1024) throw new JobError('JOB_SOURCE_UNRETAINABLE', 'CHECKPOINT_EVIDENCE_TABLE_LIMIT');
108
+ return {...packet, tiles: packet.tiles.map((tile, index) => ({...tile,
109
+ url: `/api/checkpoint-evidence/${packet.checkpointId}/tiles/${index}`})),
110
+ table: {...packet.table, url: `/api/checkpoint-evidence/${packet.checkpointId}/table`, ...parseCheckpointTable(bytes)}};
111
+ });
112
+ return {checkpointEvidence};
113
+ }