rig-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.
@@ -196,9 +196,21 @@ export function projectSessionCorrection(input: SessionInput) {
196
196
  return { ...common, kind: 'checked-patch' as const, applied, sessionBytes, patchBytes: patchText(patch), outcome: null };
197
197
  }
198
198
 
199
+ type PartsCorrectionVerdict = PartsVerdict | {
200
+ schema?: string;
201
+ mode: PartsVerdict['mode'];
202
+ tool?: { name: string; version: string };
203
+ source: PartsVerdict['source'];
204
+ status?: string;
205
+ parts?: Record<string, { outcome: string; note: string; flags: string[] }>;
206
+ comments?: import('./parts-comment.ts').PartsComment[];
207
+ issues?: import('./parts-comment.ts').PartsIssue[];
208
+ updatedAt?: string;
209
+ };
210
+
199
211
  /** Standalone parts notes and pointed comments keep their original parts identity. */
200
212
  export function projectPartsDescription(input: {
201
- verdict: PartsVerdict;
213
+ verdict: PartsCorrectionVerdict;
202
214
  source: PartsVerdict['source'];
203
215
  selector: Extract<Selector, { kind: 'parts' }>;
204
216
  selection: { kind: 'comment'; itemId: string } | { kind: 'note'; itemId: string; part: string };
@@ -210,13 +222,24 @@ export function projectPartsDescription(input: {
210
222
  }
211
223
  const { itemId } = selection;
212
224
  if (selection.kind === 'comment') {
213
- const matches = verdict.comments.filter(comment => comment.id === itemId);
225
+ if ('issues' in verdict && Array.isArray(verdict.issues)) {
226
+ const matches = verdict.issues.filter(issue => issue.id === itemId);
227
+ const item = matches[0];
228
+ if (matches.length !== 1 || !item || item.sourceHash !== source.sha256) {
229
+ return refuse('CORRECTION_ITEM_INVALID', 'expected one source-bound parts comment');
230
+ }
231
+ const primary = item.parts[0]!;
232
+ return { kind: 'described' as const, itemId, verbatim: itemWords(itemId, item.summary), stage: selector.stage, on, source, part: primary.name, imageHash: primary.imageHash, parts: item.parts, comment: item, outcome: null };
233
+ }
234
+ const comments = ('comments' in verdict && Array.isArray(verdict.comments)) ? verdict.comments : [];
235
+ const matches = comments.filter(comment => comment.id === itemId);
214
236
  const item = matches[0];
215
237
  if (matches.length !== 1 || !item || item.sourceHash !== source.sha256) {
216
238
  return refuse('CORRECTION_ITEM_INVALID', 'expected one source-bound parts comment');
217
239
  }
218
240
  return { kind: 'described' as const, itemId, verbatim: itemWords(itemId, item.summary), stage: selector.stage, on, source, part: item.part, imageHash: item.imageHash, comment: item, outcome: null };
219
241
  }
220
- if (!Object.hasOwn(verdict.parts, selection.part)) return refuse('CORRECTION_ITEM_INVALID', 'expected a saved part note');
221
- return { kind: 'described' as const, itemId, verbatim: itemWords(itemId, verdict.parts[selection.part]!.note), stage: selector.stage, on, source, part: selection.part, outcome: null };
242
+ const parts = ('parts' in verdict && verdict.parts) ? verdict.parts : null;
243
+ if (!parts || !Object.hasOwn(parts, selection.part)) return refuse('CORRECTION_ITEM_INVALID', 'expected a saved part note');
244
+ return { kind: 'described' as const, itemId, verbatim: itemWords(itemId, parts[selection.part]!.note), stage: selector.stage, on, source, part: selection.part, outcome: null };
222
245
  }
@@ -247,7 +247,7 @@ export function formatFeedbackIssues(input: ParsedFeedbackSession): string {
247
247
 
248
248
  /** Selected handoff uses the existing issue export surface with exact JSON-escaped words and evidence. */
249
249
  export function formatCorrectionIssue(
250
- correction: {kind:string;itemId:string;stage:string;on:readonly string[];verbatim:string;source:unknown;createSource?:string;operation?:string;patchBytes?:string;target?:unknown;part?:string;imageHash?:string;comment?:import('./parts-comment.ts').PartsComment},
250
+ correction: {kind:string;itemId:string;stage:string;on:readonly string[];verbatim:string;source:unknown;createSource?:string;operation?:string;patchBytes?:string;target?:unknown;part?:string;imageHash?:string;comment?:import('./parts-comment.ts').PartsComment|import('./parts-comment.ts').PartsIssue},
251
251
  context?:Json,
252
252
  ): string {
253
253
  const state=correction.kind==='described'?'Unresolved request':
package/src/front.ts CHANGED
@@ -12,6 +12,7 @@ import {lstat,readFile,readdir,realpath,rename,unlink,writeFile,open as openFile
12
12
  import {dirname,join} from 'node:path';
13
13
  import {fileURLToPath} from 'node:url';
14
14
  import {acquireClaim,alive,openFingerprint,readRecord,releaseClaim,running,smallJson,type RecordFile} from './open.ts';
15
+ import {playBuildConditions} from './build.ts';
15
16
  import {capabilityHeader,openKeyHeader,openNonceHeader,sameSecret} from './open-protocol.ts';
16
17
  import {DEFAULT_CLOSE_GRACE_MS,LIVE_PATH} from './live-lifecycle.ts';
17
18
  export const defaultFrontPort=4318; // Foreground `review <dir>` keeps 4317.
@@ -40,7 +41,7 @@ export async function ensureFront(options:{control:string;port:number;fingerprin
40
41
  const row=await reuse();if(row)return row.origin;
41
42
  request=join(control,`${name}.${nonce}.request.json`);const log=join(control,`${name}.${nonce}.log`);
42
43
  const spec:FrontRequest={schema:'rig-review-front-request/1',control,request,record:recordPath,port,nonce,fingerprint,idleMs};await writeFile(request,JSON.stringify(spec),{mode:0o600,flag:'wx'});
43
- const logHandle=await openFile(log,'a',0o600);try{child=spawn(process.execPath,[join(appRoot,'src/front-worker.ts'),request],{cwd:control,detached:true,stdio:['ignore',logHandle.fd,logHandle.fd],env:process.env});child.unref();}finally{await logHandle.close();}
44
+ const logHandle=await openFile(log,'a',0o600);try{child=spawn(process.execPath,[...playBuildConditions().map(c=>`--conditions=${c}`),join(appRoot,'src/front-worker.ts'),request],{cwd:control,detached:true,stdio:['ignore',logHandle.fd,logHandle.fd],env:process.env});child.unref();}finally{await logHandle.close();}
44
45
  let exited:string|undefined;child.on('error',error=>{exited=error.message;});child.on('exit',(code,signal)=>{exited=`exit ${code} ${signal??''}`;});
45
46
  while(performance.now()<deadline){const live=await reuse();if(live){handedOff=true;return live.origin;}
46
47
  if(exited){if(/FRONT_PORT_BUSY/.test(await readFile(log,'utf8').catch(()=>'')))throw new Error(`FRONT_PORT_BUSY: 127.0.0.1:${port} is held by another listener; use --direct (or set RIG_REVIEW_FRONT_PORT)`);throw new Error(`FRONT_START: ${exited}; front log ${log}`);}
package/src/handoff.ts CHANGED
@@ -430,7 +430,7 @@ export async function resolveHandoff(root: string, declared: HandoffDeclaration
430
430
  const full = declared.full !== undefined ? await blockPath(root, declared.full, 'producer.full', 'dir') : undefined;
431
431
  const head = declared.head !== undefined ? await blockPath(root, declared.head, 'producer.head', 'dir') : undefined;
432
432
  const keypoints = declared.keypoints !== undefined ? await blockPath(root, declared.keypoints, 'producer.keypoints', 'file') : undefined;
433
- if ((source === undefined) !== (full === undefined) || (head !== undefined && full === undefined)) throw new HandoffError('HANDOFF_FLAGS_INVALID', 'producer', 'source and full are given together, head only with them');
433
+ if ((full !== undefined && source === undefined) || (head !== undefined && full === undefined)) throw new HandoffError('HANDOFF_FLAGS_INVALID', 'producer', 'full requires source, and head requires full');
434
434
  return { handoff: await record(root, root, 'declared', 'review.json producer', config, parts, { source, full, head, keypoints }, declared.parts !== undefined, options), reason: null };
435
435
  }
436
436
  for (const name of ['config.json', 'rig/config.json']) {
package/src/job-act.ts CHANGED
@@ -1,10 +1,11 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import {
3
- JOB_ACT_SCHEMA, JOB_API_SCHEMA, JOB_API_V3_SCHEMA, JOB_RECORD_ACT_KINDS, JOB_RECORD_ACT_SCHEMA, JOB_RIG_REVIEW_ACT_SCHEMA, jobStillByteLimit, JOB_ENABLED_ACT_KINDS, JOB_PLAN_BOUND_SIGNOFF_STAGES, JOB_RESERVED_ACT_KINDS,
3
+ JOB_ACT_SCHEMA, JOB_API_SCHEMA, JOB_API_V3_SCHEMA, JOB_PARTS_VERDICT_ACT_SCHEMA, JOB_RECORD_ACT_KINDS, JOB_RECORD_ACT_SCHEMA, JOB_RIG_REVIEW_ACT_SCHEMA, jobStillByteLimit, JOB_ENABLED_ACT_KINDS, JOB_PLAN_BOUND_SIGNOFF_STAGES, JOB_RESERVED_ACT_KINDS,
4
4
  type ActV3, type JobAct, type JobActValues, type JobApiSchema, type JobPendingAsk, type JobPublicationMode, type JobReviewerBinding,
5
5
  type JobSourceBinding, type JobSubject, type JobUISubmission, type JobRigCapture, type JobRigStill,
6
6
  type PendingAskV3, type RecordAct, type RecordSource, type RecordSubject, type SourceV3, type UISubmissionV3,
7
7
  } from './job-contract.ts';
8
+ import { parsePartsIssue, type PartsIssue } from './parts-comment.ts';
8
9
  import {
9
10
  isRecordSource, jobHash, jobId, jobInteger, jobObject,
10
11
  parseRecordAct, parseRecordSource, requestDigest, validateRecordAskSubject,
@@ -558,30 +559,49 @@ export function finalizeJobAct(options: {
558
559
  } };
559
560
  }
560
561
  case 'parts-verdict': {
561
- const value = jobObject(submission.value, ['verdict', 'parts', 'words']);
562
- if (!Array.isArray(value.parts) || value.parts.length !== retained.partIds.length) throw new JobError('JOB_ACT_INVALID');
562
+ const value = jobObject(submission.value, ['verdict', 'issues', 'words']);
563
+ const verdict = choice(value.verdict, ['approved', 'changes-requested'] as const);
564
+ if (
565
+ !Array.isArray(value.issues) ||
566
+ value.issues.length > 1000 ||
567
+ (verdict === 'approved') !== (value.issues.length === 0)
568
+ ) {
569
+ throw new JobError('JOB_ACT_INVALID');
570
+ }
563
571
  const ids = new Set<string>();
564
- const parts = value.parts.map(raw => {
565
- const item = jobObject(raw, ['partId', 'part', 'mesh']);
566
- const partId = jobId(item.partId);
567
- if (!retained.partIds.includes(partId) || ids.has(partId)) throw new JobError('JOB_ACT_INVALID');
568
- ids.add(partId);
569
- const outcome = (raw: unknown) => {
570
- const item = jobObject(raw, ['outcome', 'note']);
571
- const result = { outcome: choice(item.outcome, ['pending', 'clean', 'flagged'] as const), note: words(item.note) };
572
- // Match the existing parts verdict writer's flagged-note validation.
573
- if (result.outcome === 'flagged' && !result.note.trim()) throw new JobError('JOB_ACT_INVALID');
574
- return result;
575
- };
576
- return { partId, part: outcome(item.part), mesh: outcome(item.mesh) };
572
+ const issues: PartsIssue[] = value.issues.map(raw => {
573
+ let issue: PartsIssue;
574
+ try {
575
+ issue = parsePartsIssue(raw, true, false, false);
576
+ } catch {
577
+ throw new JobError('JOB_ACT_INVALID');
578
+ }
579
+ if (issue.sourceHash !== source.sourceHash || ids.has(issue.id)) {
580
+ throw new JobError('JOB_ACT_INVALID');
581
+ }
582
+ ids.add(issue.id);
583
+ for (const part of issue.parts) {
584
+ const matchesSource = source.parts!.images.some(
585
+ img => img.role === 'part' && img.path === `parts/${part.name}.png` && img.sha256 === part.imageHash,
586
+ );
587
+ if (!retained.partIds.includes(part.name) || !matchesSource) {
588
+ throw new JobError('JOB_ACT_INVALID');
589
+ }
590
+ }
591
+ return structuredClone(issue);
577
592
  });
578
- const verdict = choice(value.verdict, ['pending', 'approved', 'changes-requested'] as const);
579
- const outcomes = parts.flatMap(part => [part.part.outcome, part.mesh.outcome]);
580
- if (verdict === 'approved' && outcomes.some(outcome => outcome !== 'clean') ||
581
- verdict === 'changes-requested' && !outcomes.includes('flagged')) throw new JobError('JOB_ACT_INVALID');
582
- return { ...envelope, kind: 'parts-verdict', source: { ...source, projectHash: source.projectHash!,
583
- selector: source.selector as Extract<NonNullable<JobSourceBinding['selector']>, { kind: 'draft' }>, parts: source.parts! },
584
- value: { verdict, parts, words: words(value.words) } };
593
+ return {
594
+ ...envelope,
595
+ schema: JOB_PARTS_VERDICT_ACT_SCHEMA,
596
+ kind: 'parts-verdict',
597
+ source: {
598
+ ...source,
599
+ projectHash: source.projectHash!,
600
+ selector: source.selector as Extract<NonNullable<JobSourceBinding['selector']>, { kind: 'draft' }>,
601
+ parts: source.parts!,
602
+ },
603
+ value: { verdict, issues, words: words(value.words) },
604
+ };
585
605
  }
586
606
  case 'review-verdict': {
587
607
  const value = jobObject(submission.value, ['stage', 'verdict', 'words']);
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
5
  JOB_PLAN_BOUND_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,
@@ -391,13 +392,14 @@ function asCode<Value>(fn: () => Value, code: JobErrorCode): Value {
391
392
  }
392
393
  }
393
394
 
394
- function exactObject(
395
+ export function exactObject(
395
396
  value: unknown,
396
397
  keys: readonly string[],
397
398
  code: JobErrorCode,
399
+ optional: readonly string[] = [],
398
400
  ): 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)) {
401
+ const item = asCode(() => jobObject(value, [...keys, ...optional]), code);
402
+ if (keys.some(key => !Object.hasOwn(item, key) || item[key] === undefined)) {
401
403
  throw new JobError(code);
402
404
  }
403
405
  return item;
@@ -648,6 +650,7 @@ type ParsedRecordPayload =
648
650
  }
649
651
  | {
650
652
  readonly kind: 'plan';
653
+ readonly checkpointEvidence?: readonly JobCheckpointEvidence[];
651
654
  readonly inputs: readonly JobFileIdentity[];
652
655
  readonly files: readonly JobFileIdentity[];
653
656
  readonly plan: JobPlanIdentity;
@@ -661,17 +664,18 @@ function parseRecordClosureAndSubjects(
661
664
  rawSubjects: unknown,
662
665
  selection: RecordResult,
663
666
  checkedRecord?: ProjectRecord,
667
+ evidenceHolder: object = {},
664
668
  ): ParsedRecordPayload {
665
669
  const { inputs, files } = parseFileClosure(rawInputs, rawFiles, checkedRecord, 'JOB_SOURCE_MISMATCH');
666
670
  if (selection.kind === 'option-set') {
667
- if (rawPlan !== null) throw new JobError('JOB_SOURCE_MISMATCH');
671
+ if (rawPlan !== null || 'checkpointEvidence' in evidenceHolder) throw new JobError('JOB_SOURCE_MISMATCH');
668
672
  const subjects = parseOptionSubjects(rawSubjects, selection, 'JOB_SOURCE_MISMATCH');
669
673
  return { kind: 'option-set', inputs, files, plan: null, subjects };
670
674
  }
671
675
  if (rawPlan === null) throw new JobError('JOB_SOURCE_MISMATCH');
672
676
  const { plan, stepIds } = parsePlanIdentity(rawPlan, 'JOB_SOURCE_MISMATCH');
673
677
  const subjects = parsePlanSubjects(rawSubjects, stepIds, 'JOB_SOURCE_MISMATCH');
674
- return { kind: 'plan', inputs, files, plan, subjects };
678
+ return { kind: 'plan', inputs, files, plan, subjects, ...checkpointEvidenceFields(evidenceHolder, plan, subjects, files) };
675
679
  }
676
680
 
677
681
  export function parseRecordPublishedContext(
@@ -696,7 +700,7 @@ export function parseRecordPublishedContext(
696
700
  ): OptionContext | PlanContext {
697
701
  const selection = parseRecordResult(result);
698
702
  const checkedRecord = record === undefined ? undefined : parseProjectRecord(record, 'JOB_SOURCE_MISMATCH');
699
- const item = exactObject(value, ['label', 'parts', 'inputs', 'files', 'plan', 'subjects'], 'JOB_SOURCE_MISMATCH');
703
+ const item = exactObject(value, ['label', 'parts', 'inputs', 'files', 'plan', 'subjects'], 'JOB_SOURCE_MISMATCH', ['checkpointEvidence']);
700
704
  const label = asCode(() => jobText(item.label), 'JOB_SOURCE_MISMATCH');
701
705
  const parts = parseRecordPartsIdentity(item.parts, 'JOB_SOURCE_MISMATCH');
702
706
  const body = parseRecordClosureAndSubjects(
@@ -706,11 +710,13 @@ export function parseRecordPublishedContext(
706
710
  item.subjects,
707
711
  selection,
708
712
  checkedRecord,
713
+ item,
709
714
  );
710
715
  if (body.kind === 'option-set') {
711
716
  return { label, parts, inputs: body.inputs, files: body.files, plan: null, subjects: body.subjects };
712
717
  }
713
- return { label, parts, inputs: body.inputs, files: body.files, plan: body.plan, subjects: body.subjects };
718
+ return { label, parts, inputs: body.inputs, files: body.files, plan: body.plan, subjects: body.subjects,
719
+ ...(body.checkpointEvidence ? {checkpointEvidence: body.checkpointEvidence} : {}) };
714
720
  }
715
721
 
716
722
  export function assertEqualRecordContexts(
@@ -734,6 +740,7 @@ export function assertEqualRecordContexts(
734
740
  }
735
741
 
736
742
  export interface RecordSourceDigestInput {
743
+ readonly checkpointEvidence?: readonly JobCheckpointEvidence[];
737
744
  readonly schema?: typeof JOB_RECORD_SOURCE_SCHEMA;
738
745
  readonly sourceHash?: JobSha256;
739
746
  readonly projectHash?: JobSha256;
@@ -764,6 +771,7 @@ export function serializeRecordSourceDigestPayload(input: RecordSourceDigestInpu
764
771
  'plan',
765
772
  'subjects',
766
773
  'files',
774
+ 'checkpointEvidence',
767
775
  ]),
768
776
  'JOB_SOURCE_MISMATCH',
769
777
  );
@@ -787,7 +795,7 @@ export function serializeRecordSourceDigestPayload(input: RecordSourceDigestInpu
787
795
  const { inputs, files, byPath } = parseFileClosure(item.inputs, item.files, record, 'JOB_SOURCE_MISMATCH');
788
796
 
789
797
  if (selection.kind === 'option-set') {
790
- if (item.plan !== null || item.optionSet === null || item.optionSetFile === null) {
798
+ if ('checkpointEvidence' in item || item.plan !== null || item.optionSet === null || item.optionSetFile === null) {
791
799
  throw new JobError('JOB_SOURCE_MISMATCH');
792
800
  }
793
801
  const rawOptionSet = exactObject(item.optionSet, ['id', 'sha256'], 'JOB_SOURCE_MISMATCH');
@@ -831,6 +839,7 @@ export function serializeRecordSourceDigestPayload(input: RecordSourceDigestInpu
831
839
  plan,
832
840
  subjects,
833
841
  files,
842
+ ...checkpointEvidenceFields(item, plan, subjects, files),
834
843
  });
835
844
  }
836
845
 
@@ -896,6 +905,7 @@ function assembleRecordSource(
896
905
  plan: body.plan,
897
906
  subjects: body.subjects,
898
907
  files: body.files,
908
+ ...(body.checkpointEvidence ? {checkpointEvidence: body.checkpointEvidence} : {}),
899
909
  });
900
910
  return {
901
911
  sourceHash,
@@ -903,6 +913,7 @@ function assembleRecordSource(
903
913
  record,
904
914
  inputs: body.inputs,
905
915
  files: body.files,
916
+ ...(body.checkpointEvidence ? {checkpointEvidence: body.checkpointEvidence} : {}),
906
917
  subject: 'plan',
907
918
  selection: { kind: 'plan' },
908
919
  optionSet: null,
@@ -948,6 +959,7 @@ export function buildRecordSource(input: {
948
959
  files: context.files,
949
960
  plan: context.plan,
950
961
  subjects: context.subjects,
962
+ ...(context.checkpointEvidence ? {checkpointEvidence: context.checkpointEvidence} : {}),
951
963
  };
952
964
  return assembleRecordSource(record, selection, body, input.optionSetFile);
953
965
  }
@@ -969,6 +981,7 @@ export function parseRecordSource(value: unknown): RecordSource {
969
981
  'subjects',
970
982
  ],
971
983
  'JOB_SOURCE_MISMATCH',
984
+ ['checkpointEvidence'],
972
985
  );
973
986
  const record = parseProjectRecord(item.record, 'JOB_SOURCE_MISMATCH');
974
987
  const projectHash = asCode(() => jobSha(item.projectHash), 'JOB_SOURCE_MISMATCH');
@@ -983,6 +996,7 @@ export function parseRecordSource(value: unknown): RecordSource {
983
996
  item.subjects,
984
997
  selection,
985
998
  record,
999
+ item,
986
1000
  );
987
1001
  if (selection.kind === 'option-set') {
988
1002
  const rawOptionSet = exactObject(item.optionSet, ['id', 'sha256'], 'JOB_SOURCE_MISMATCH');
@@ -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
+ }
package/src/job-cli.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import {closeSync, constants, fstatSync, fsyncSync, lstatSync, openSync, readFileSync, renameSync, unlinkSync, writeSync} from 'node:fs';
3
3
  import {join} from 'node:path';
4
- import { JOB_API_SCHEMA, JOB_ACT_SCHEMA, JOB_RIG_REVIEW_ACT_SCHEMA, JOB_ENABLED_ACT_KINDS, jobRawActMediaType, jobStillByteLimit,
4
+ import { JOB_API_SCHEMA, JOB_ACT_SCHEMA, JOB_PARTS_VERDICT_ACT_SCHEMA, JOB_RIG_REVIEW_ACT_SCHEMA, JOB_ENABLED_ACT_KINDS, jobRawActMediaType, jobStillByteLimit,
5
5
  type JobAct, type JobAgentRequest, type JobNextRequest, type JobNextValue } from './job-contract.ts';
6
6
  import { assertJobApiSchema, jobFailure, jobHash, jobId, jobInteger, jobObject, jobWaitLimitMs, parseJobRequest } from './job-api.ts';
7
7
  import { JobError } from './job-store.ts';
@@ -150,7 +150,11 @@ function parseConsumerAct(bytes: Buffer, job: string, actId: string): JobAct {
150
150
  try { value = JSON.parse(new TextDecoder('utf-8', {fatal: true}).decode(bytes)); }
151
151
  catch { throw new JobError('JOB_REQUEST_INVALID'); }
152
152
  const act = jobObject(value, ['schema', 'actId', 'jobId', 'askId', 'publicationId', 'kind', 'authority', 'at', 'source', 'value', 'still']);
153
- if (act.jobId !== job || act.actId !== actId || (act.schema !== JOB_ACT_SCHEMA && act.schema !== JOB_RIG_REVIEW_ACT_SCHEMA)) {
153
+ if (act.jobId !== job || act.actId !== actId ||
154
+ (act.schema !== JOB_ACT_SCHEMA && act.schema !== JOB_RIG_REVIEW_ACT_SCHEMA && act.schema !== JOB_PARTS_VERDICT_ACT_SCHEMA)) {
155
+ throw new JobError('JOB_ACT_INVALID');
156
+ }
157
+ if (act.schema === JOB_PARTS_VERDICT_ACT_SCHEMA && (act.kind !== 'parts-verdict' || act.still !== undefined)) {
154
158
  throw new JobError('JOB_ACT_INVALID');
155
159
  }
156
160
  if (act.schema === JOB_RIG_REVIEW_ACT_SCHEMA) {