rig-review 4.9.1 → 4.11.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.
Files changed (51) hide show
  1. package/docs/DESIGN.md +5 -5
  2. package/docs/PANELS.md +3 -1
  3. package/docs/REVIEW_PACKAGE.md +143 -30
  4. package/docs/STABILITY.md +110 -3
  5. package/package.json +2 -2
  6. package/src/chest-landmarks.ts +9 -4
  7. package/src/cloth-recipe.ts +27 -7
  8. package/src/compare-html.ts +1 -1
  9. package/src/feedback-export.ts +2 -2
  10. package/src/feedback-validation.ts +11 -6
  11. package/src/frame-clock.ts +20 -4
  12. package/src/job-act.ts +60 -71
  13. package/src/job-api.ts +302 -46
  14. package/src/job-checkpoint-evidence.ts +17 -0
  15. package/src/job-cli.ts +3 -2
  16. package/src/job-contract.ts +107 -7
  17. package/src/job-front.ts +48 -12
  18. package/src/job-host.ts +7 -1
  19. package/src/job-session.ts +136 -26
  20. package/src/job-source.ts +133 -21
  21. package/src/job-store.ts +7 -4
  22. package/src/manifest.ts +59 -7
  23. package/src/open-workspace-state.ts +6 -1
  24. package/src/open.ts +3 -3
  25. package/src/rebuild.ts +42 -10
  26. package/src/session.ts +9 -4
  27. package/src/stage-comment.ts +2 -1
  28. package/web/catalog-en.ts +31 -6
  29. package/web/catalog-ko.ts +79 -54
  30. package/web/chest-editor.ts +236 -31
  31. package/web/cloth-panel.ts +1 -1
  32. package/web/compare.css +2 -2
  33. package/web/environment-world.ts +9 -0
  34. package/web/i18n.ts +1 -3
  35. package/web/inspection-persistence.ts +19 -6
  36. package/web/interview-panel.ts +13 -80
  37. package/web/job-rig-screen.ts +65 -37
  38. package/web/job-session.ts +204 -64
  39. package/web/label-placement.ts +25 -8
  40. package/web/main.ts +350 -114
  41. package/web/part-selection.ts +2 -1
  42. package/web/parts-viewport-provider.ts +21 -8
  43. package/web/rebuild-client.ts +3 -5
  44. package/web/rig-host.ts +5 -4
  45. package/web/rig-overlays.ts +3 -2
  46. package/web/rig-viewport-provider.ts +10 -6
  47. package/web/stage-comments.ts +24 -21
  48. package/web/styles.css +23 -51
  49. package/web/viewport-controller.ts +4 -0
  50. package/web/workspace-layout.ts +4 -4
  51. package/web/workspace-ui.ts +8 -6
package/src/job-source.ts CHANGED
@@ -11,6 +11,7 @@ import {
11
11
  JOB_PARTS_ENUMERATOR_RANGE,
12
12
  } from './job-contract.ts';
13
13
  import type {
14
+ JobChestLandmarkValue, JobErrorCode, JobPublication, JobPublishedChestLandmark,
14
15
  JobCheckpointEvidence, JobFileIdentity, JobInterviewDiagnostics, JobInterviewRecord, JobModelSourceBinding, JobPartsEnumerator, JobPartsFileReference, JobPartsIdentity, JobPlanIdentity, JobPublishRequest,
15
16
  JobPreviousDraft, JobSelector, JobSourceBinding, JobSubject, JobPlanTextProjection, JobPlanTextStep,
16
17
  OptionContext, OptionSource, PackageResultV3, PlanContext, PlanSource, ProjectRecord, PublishRequestV3,
@@ -22,8 +23,12 @@ import { acceptedRigReview } from './interview-scene.ts';
22
23
  import { BUILD_MODEL_PATH, loadJobReview, loadReview } from './manifest.ts';
23
24
  import { HandoffError } from './handoff.ts';
24
25
  import { openKey } from './open.ts';
26
+ import { attachmentHashText, MESH_EDIT_CODES } from './mesh-edit.ts';
27
+ import { readStoredSetupMesh } from './setup-mesh.ts';
28
+ import { contourParts } from './rebuild.ts';
29
+ import { parseBustSpec } from './chest-landmarks.ts';
25
30
  import { assertReviewUnchanged } from './reference.ts';
26
- import {
31
+ import { isRigDraftVerdictSource,
27
32
  assertEqualRecordContexts,
28
33
  assertJobApiSchema,
29
34
  atSubject,
@@ -36,7 +41,9 @@ import {
36
41
  jobPath,
37
42
  jobSha,
38
43
  jobText,
44
+ optionSetRefs,
39
45
  parseJobInterviewDiagnostics,
46
+ parsePublishedChestLandmarks,
40
47
  parseRecordFreeze,
41
48
  parseRecordPublishedContext,
42
49
  parseRecordResult,
@@ -62,6 +69,7 @@ export interface JobRootIdentity {
62
69
  export interface JobPublishedContext {
63
70
  readonly checkpointEvidence?: readonly JobCheckpointEvidence[];
64
71
  readonly previousDraft?: JobPreviousDraft;
72
+ readonly chestLandmarks?: JobPublication['chestLandmarks'];
65
73
  readonly selector: JobSelector | null;
66
74
  readonly plan: JobPlanIdentity | null;
67
75
  readonly parts: JobPartsIdentity | null;
@@ -91,6 +99,7 @@ export type JobPublicationReader = (input: {
91
99
  export interface JobRetainedSource {
92
100
  /** Private base preimage for optional declarations. Keeps its historical key. */
93
101
  readonly checkpointEvidencePackageHash?: string;
102
+ readonly chestLandmarks?: JobPublication['chestLandmarks'];
94
103
  readonly root: JobRootIdentity;
95
104
  readonly record: JobFileIdentity | null;
96
105
  readonly seals: readonly JobFileIdentity[];
@@ -133,6 +142,13 @@ export function isRetainedRecordSource(retained: JobRetainedSourceV3): retained
133
142
  return 'kind' in retained && retained.kind === 'record';
134
143
  }
135
144
 
145
+ /** Select rig inspection from the retained declaration before any ask arrives. */
146
+ export function retainedRigDraftVerdict(retained: JobRetainedSourceV3): boolean {
147
+ return !isRetainedRecordSource(retained) && isRigDraftVerdictSource(retained.source) &&
148
+ retained.subjects.some(subject => subject.kind === 'review-verdict' && subject.stage === 'rig-review');
149
+ }
150
+
151
+
136
152
  const maxSourceBytes = 256 * 1024 * 1024;
137
153
  const maxSourceFiles = 4096;
138
154
  const maxFileBytes = 64 * 1024 * 1024;
@@ -197,6 +213,50 @@ function sourceBytes(root: string, path: string): Buffer {
197
213
  return bytes;
198
214
  }
199
215
 
216
+ /** Read the sealed model for both kinds of setup-space edit. */
217
+ export function readJobEditModel(root: string, file: JobFileIdentity | null, code: JobErrorCode) {
218
+ try {
219
+ if (!file) throw new JobError(code);
220
+ const bytes = sourceBytes(root, file.path);
221
+ if (jobHash(bytes) !== file.sha256) throw new JobError(code);
222
+ return JSON.parse(bytes.toString('utf8')) as {stage?: {width?: number; height?: number}};
223
+ } catch {
224
+ throw new JobError(code);
225
+ }
226
+ }
227
+
228
+ export function readJobEditMesh(model: ReturnType<typeof readJobEditModel>, edit: Omit<JobChestLandmarkValue, 'bust'>,
229
+ stale: JobErrorCode, invalid: JobErrorCode) {
230
+ const read = readStoredSetupMesh(model, edit.slot, edit, MESH_EDIT_CODES);
231
+ if (!read.ok || jobHash(attachmentHashText(read.mesh.entry)) !== edit.source.hash) throw new JobError(stale);
232
+ const {width, height} = edit.source.frame;
233
+ if (read.mesh.linked || model.stage?.width !== width || model.stage?.height !== height) throw new JobError(invalid);
234
+ return read.mesh;
235
+ }
236
+
237
+ function assertPublishedChestLandmarks(root: string, modelFile: JobFileIdentity | null, configFiles: readonly JobFileIdentity[],
238
+ seeds: readonly JobPublishedChestLandmark[]): void {
239
+ const code = 'JOB_SOURCE_MISMATCH';
240
+ const model = readJobEditModel(root, modelFile, code);
241
+ const configs = new Map<string, ReturnType<typeof contourParts>>();
242
+ for (const seed of seeds) {
243
+ readJobEditMesh(model, seed, code, code);
244
+ const hash = seed.source.configHash;
245
+ let parts = configs.get(hash);
246
+ if (!parts) {
247
+ const file = configFiles.find(file => file.sha256 === hash);
248
+ if (!file) throw new JobError(code, 'Published chest landmarks require the retained source config');
249
+ const bytes = readCheckpointEvidenceBytes(root, file, maxFileBytes, () => new JobError(code));
250
+ parts = contourParts(new TextDecoder('utf-8', {fatal: true}).decode(bytes));
251
+ configs.set(hash, parts);
252
+ }
253
+ const contour = parts.find(part => part.name === seed.slot)?.entry.contour as {bust?: unknown} | undefined;
254
+ if (!contour || requestDigest(parseBustSpec(contour.bust, 'contour.bust', true)) !== requestDigest(seed.bust)) {
255
+ throw new JobError(code, 'Published chest landmarks differ from the retained source config');
256
+ }
257
+ }
258
+ }
259
+
200
260
  /** Read and hash the exact bytes the caller will consume, including on a cache hit at the front. */
201
261
  export function readPreviousDraftBytes(root: string, file: JobFileIdentity, operand: 'current' | 'previous' | 'diff'): Buffer {
202
262
  const limit = operand === 'diff' ? 1024 * 1024 : maxFileBytes;
@@ -896,6 +956,21 @@ export async function loadRetainedRecordRig(retained: JobRetainedRecordSource) {
896
956
  }
897
957
  }
898
958
 
959
+ /** Create declares the original painting as the first project input. */
960
+ export function retainedRecordPainting(retained: JobRetainedRecordSource): Pick<InterviewQuestion['images'][number], 'ref' | 'name'> | null {
961
+ const {project} = readProjectRecordBytes(retained.snapshotRoot, retained.record);
962
+ const input = asPlainObject(Array.isArray(project.inputs) ? project.inputs[0] : null);
963
+ const seal = retained.seals.find(file => file.path === input?.path && file.sha256 === input?.sha256);
964
+ if (!seal || !/\.(png|jpe?g|webp|svg)$/i.test(seal.path)) return null;
965
+ return {ref: seal, name: posix.basename(seal.path)};
966
+ }
967
+
968
+ const recordInterviewCollections = (interview: Record<string, unknown>) => [
969
+ [interview.framing, ['interview']],
970
+ [interview.waypoints, ['interview', 'rigging-interview']],
971
+ [asPlainObject(interview.post)?.items, ['post-interview']],
972
+ ] as const;
973
+
899
974
  /** Delivery-only projection through the existing retained record reader. */
900
975
  export function projectRetainedPlanText(retained: JobRetainedSourceV3): JobPlanTextProjection | undefined {
901
976
  const {source, record} = retained;
@@ -955,7 +1030,20 @@ export function projectRetainedPlanText(retained: JobRetainedSourceV3): JobPlanT
955
1030
  }
956
1031
  return {id:step.id, hash:step.hash, ...fields, issues};
957
1032
  });
958
- const projection: JobPlanTextProjection = {schema:JOB_PLAN_TEXT_SCHEMA, record:identity, status:'projected', steps};
1033
+ const questions: Record<string, string> = {};
1034
+ const interview = asPlainObject(project.interview);
1035
+ if (interview) {
1036
+ for (const [items] of recordInterviewCollections(interview)) {
1037
+ for (const rawItem of Array.isArray(items) ? items : []) {
1038
+ const item = asPlainObject(rawItem);
1039
+ if (typeof item?.id === 'string' && item.id.length <= 128 && /^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(item.id) &&
1040
+ typeof item.text === 'string' && !Object.hasOwn(questions, item.id))
1041
+ questions[item.id] = item.text;
1042
+ }
1043
+ }
1044
+ }
1045
+ const projection: JobPlanTextProjection = {schema:JOB_PLAN_TEXT_SCHEMA, record:identity, status:'projected', steps,
1046
+ ...(Object.keys(questions).length ? {questions} : {})};
959
1047
  return Buffer.byteLength(JSON.stringify(projection)) > 512 * 1024 ? unavailable('PLAN_TEXT_LIMIT') : projection;
960
1048
  }
961
1049
 
@@ -981,6 +1069,7 @@ function decodeRetainedRecordProject(
981
1069
  ): {
982
1070
  readonly questions: readonly InterviewQuestion[];
983
1071
  readonly optionSetFile: JobFileIdentity | null;
1072
+ readonly optionSetFiles?: readonly JobFileIdentity[];
984
1073
  } {
985
1074
  const sealMap = new Map<string, string>();
986
1075
  for (const seal of seals) {
@@ -994,14 +1083,11 @@ function decodeRetainedRecordProject(
994
1083
  if (context.plan !== null) {
995
1084
  throw new JobError('JOB_SOURCE_MISMATCH');
996
1085
  }
997
- const { questionId, setId } = result;
998
1086
  const interview = asPlainObject(project.interview);
999
1087
  if (!interview) throw new JobError('JOB_SOURCE_MISMATCH');
1000
- const collections = [
1001
- [interview.framing, ['interview']],
1002
- [interview.waypoints, ['interview', 'rigging-interview']],
1003
- [asPlainObject(interview.post)?.items, ['post-interview']],
1004
- ] as const;
1088
+ // #1004: one question per published set, in set order; one set keeps the original single-question result.
1089
+ const decodedSets = optionSetRefs(result).map(({ questionId, setId }) => {
1090
+ const collections = recordInterviewCollections(interview);
1005
1091
  const matches: { readonly pending: unknown; readonly allowedStages: readonly string[] }[] = [];
1006
1092
  for (const [items, allowedStages] of collections) {
1007
1093
  if (items !== undefined && !Array.isArray(items)) throw new JobError('JOB_SOURCE_MISMATCH');
@@ -1092,7 +1178,7 @@ function decodeRetainedRecordProject(
1092
1178
  } catch {hasBoundParts = false;}
1093
1179
  }
1094
1180
  return {
1095
- questions: [{
1181
+ question: {
1096
1182
  ref,
1097
1183
  set,
1098
1184
  editable: true,
@@ -1101,8 +1187,14 @@ function decodeRetainedRecordProject(
1101
1187
  ...(ctx?.kind === 'scene' && images.length ? {scenePicture: true as const} : {}),
1102
1188
  ...(set.stage === 'post-interview' && !images.length && (ctx?.kind === 'rig' || ctx?.kind === 'scene')
1103
1189
  ? {missingPicture: ctx.kind} : {}),
1104
- }],
1105
- optionSetFile: ref,
1190
+ } satisfies InterviewQuestion,
1191
+ ref,
1192
+ };
1193
+ });
1194
+ return {
1195
+ questions: decodedSets.map(item => item.question),
1196
+ optionSetFile: decodedSets[0]!.ref,
1197
+ ...(result.sets ? { optionSetFiles: decodedSets.map(item => item.ref) } : {}),
1106
1198
  };
1107
1199
  }
1108
1200
 
@@ -1216,6 +1308,7 @@ export async function prepareJobRecordSource(options: {
1216
1308
  selection: result,
1217
1309
  context: retainedContext as OptionContext,
1218
1310
  optionSetFile: decoded.optionSetFile!,
1311
+ ...(decoded.optionSetFiles ? { optionSetFiles: decoded.optionSetFiles } : {}),
1219
1312
  })
1220
1313
  : buildRecordSource({
1221
1314
  record,
@@ -1324,6 +1417,7 @@ export async function verifyJobRecordSourceFresh(options: {
1324
1417
  selection: retained.result,
1325
1418
  context: retainedContext as OptionContext,
1326
1419
  optionSetFile: decoded.optionSetFile!,
1420
+ ...(decoded.optionSetFiles ? { optionSetFiles: decoded.optionSetFiles } : {}),
1327
1421
  })
1328
1422
  : buildRecordSource({
1329
1423
  record: retained.record,
@@ -1357,7 +1451,7 @@ export async function verifyJobRecordSourceFresh(options: {
1357
1451
  /** Preserve the existing composite preimage, conditionally appending the declaration. */
1358
1452
  function packageSourceDigest(packageSourceHash: string, record: JobFileIdentity | null,
1359
1453
  source: Pick<JobModelSourceBinding, 'selector' | 'plan' | 'parts'>, files: readonly JobFileIdentity[],
1360
- evidence: Pick<JobModelSourceBinding, 'checkpointEvidence' | 'previousDraft'>): string {
1454
+ evidence: Pick<JobModelSourceBinding, 'checkpointEvidence' | 'previousDraft'> & Pick<JobPublication, 'chestLandmarks'>): string {
1361
1455
  return jobHash(JSON.stringify({schema: 'rig-review-job-source/2', packageSourceHash, record,
1362
1456
  selector: source.selector, plan: source.plan, parts: source.parts, files, ...evidence}));
1363
1457
  }
@@ -1481,6 +1575,9 @@ export async function prepareJobSource(options: {
1481
1575
  const declared = publishedIdentities(context);
1482
1576
  const previous = previousDraftFields(context, context.selector, declared);
1483
1577
  const evidence = checkpointEvidenceFields(context, context.plan, context.subjects, declared);
1578
+ const chestLandmarks = 'chestLandmarks' in context ? parsePublishedChestLandmarks(context.chestLandmarks) : undefined;
1579
+ if (chestLandmarks && context.selector?.kind !== 'rig') throw new JobError('JOB_SOURCE_MISMATCH');
1580
+ const chest = chestLandmarks ? {chestLandmarks} : {};
1484
1581
  checkpointEvidenceMetadata(root.path, evidence.checkpointEvidence);
1485
1582
  let review: Awaited<ReturnType<typeof loadJobReview>>;
1486
1583
  try {
@@ -1567,13 +1664,18 @@ export async function prepareJobSource(options: {
1567
1664
  path: rootRelative(root.path, resolve(review.root, file.path)), sha256: file.sha256,
1568
1665
  });
1569
1666
  checkpointEvidenceMetadata(snapshotRoot, evidence.checkpointEvidence);
1667
+ const model = originalIdentity(review.reviewedSource.rig);
1668
+ if (chestLandmarks) {
1669
+ const handoffConfig = originalIdentity(review.handoff?.record.config ?? null);
1670
+ assertPublishedChestLandmarks(snapshotRoot, model, handoffConfig ? [handoffConfig] : declared, chestLandmarks);
1671
+ }
1570
1672
  const modelSource: JobModelSourceBinding = {
1571
- sourceHash: project || context.plan || context.parts ? packageSourceDigest(review.sourceHash, record,
1572
- {selector: context.selector, plan: context.plan, parts: parts.identity}, seals, {...evidence, ...previous}) : review.sourceHash,
1673
+ sourceHash: project || context.plan || context.parts || chestLandmarks ? packageSourceDigest(review.sourceHash, record,
1674
+ {selector: context.selector, plan: context.plan, parts: parts.identity}, seals, {...evidence, ...previous, ...chest}) : review.sourceHash,
1573
1675
  projectHash: project?.hash ?? null,
1574
1676
  package: { id: review.manifest.id, revision: review.manifest.revision },
1575
1677
  selector: context.selector,
1576
- model: originalIdentity(review.reviewedSource.rig),
1678
+ model,
1577
1679
  direction: originalIdentity(review.direction?.file ?? null),
1578
1680
  optionSet: null, appliedResult: null, plan: context.plan, parts: parts.identity,
1579
1681
  };
@@ -1597,7 +1699,8 @@ export async function prepareJobSource(options: {
1597
1699
  : null;
1598
1700
  const prepared: JobRetainedSource = {
1599
1701
  root, record, seals, snapshotRoot, snapshotIdentity,
1600
- ...(source.checkpointEvidence || source.previousDraft ? {checkpointEvidencePackageHash: review.sourceHash} : {}),
1702
+ ...(source.checkpointEvidence || source.previousDraft || chestLandmarks ? {checkpointEvidencePackageHash: review.sourceHash} : {}),
1703
+ ...chest,
1601
1704
  manifestPath: retained.manifestPath,
1602
1705
  source,
1603
1706
  instanceKey: openKey({ mode: 'single', p: boundReview, inputs: { input: review.manifestPath },
@@ -1619,7 +1722,7 @@ export async function prepareJobSource(options: {
1619
1722
  };
1620
1723
  await options.afterSnapshot?.();
1621
1724
  assertJobSourceCurrent(prepared);
1622
- if (source.checkpointEvidence || source.previousDraft) assertRetainedSnapshotIntact(snapshotRoot, seals, snapshotIdentity);
1725
+ if (source.checkpointEvidence || source.previousDraft || chestLandmarks) assertRetainedSnapshotIntact(snapshotRoot, seals, snapshotIdentity);
1623
1726
  return prepared;
1624
1727
  } catch (error) {
1625
1728
  if (snapshotIdentity) await removeOwnedJobSnapshot(options.stateRoot, {snapshotRoot, ...snapshotIdentity});
@@ -1635,24 +1738,33 @@ export function assertStoredCheckpointEvidence(retained: JobRetainedSourceV3): v
1635
1738
  }
1636
1739
  const hasEvidence = 'checkpointEvidence' in retained.source;
1637
1740
  if (isRetainedRecordSource(retained)) {
1741
+ if ('chestLandmarks' in retained) throw new JobError('JOB_SOURCE_MISMATCH');
1638
1742
  const parsed = parseRecordSource(retained.source);
1639
- if (!hasEvidence && !('checkpointEvidence' in retained.context) && !('previousDraft' in retained.context)) return;
1743
+ if (!hasEvidence && !('planPicture' in retained.source) && !('checkpointEvidence' in retained.context) &&
1744
+ !('planPicture' in retained.context) && !('previousDraft' in retained.context)) return;
1640
1745
  const context = parseRecordPublishedContext(retained.context, retained.result, retained.record);
1641
1746
  if (requestDigest(parsed.checkpointEvidence ?? null) !== requestDigest(context.checkpointEvidence ?? null) ||
1747
+ requestDigest(parsed.planPicture ?? null) !== requestDigest(context.planPicture ?? null) ||
1642
1748
  requestDigest(parsed.subjects) !== requestDigest(retained.subjects) ||
1643
1749
  requestDigest(parsed.files) !== requestDigest(retained.seals)) throw new JobError('JOB_SOURCE_MISMATCH');
1644
1750
  return;
1645
1751
  }
1646
1752
  const source = retained.source;
1647
1753
  const hasPreviousDraft = 'previousDraft' in source;
1648
- if (!hasEvidence && !hasPreviousDraft && !('checkpointEvidencePackageHash' in retained)) return;
1649
- if (!(hasEvidence || hasPreviousDraft) || !retained.record || (hasPreviousDraft && !source.parts)) {
1754
+ const hasChest = 'chestLandmarks' in retained;
1755
+ if (!hasEvidence && !hasPreviousDraft && !hasChest && !('checkpointEvidencePackageHash' in retained)) return;
1756
+ if (!(hasEvidence || hasPreviousDraft || hasChest) || !retained.record || (hasPreviousDraft && !source.parts) ||
1757
+ (hasChest && (source.selector?.kind !== 'rig' || !source.model))) {
1650
1758
  throw new JobError('JOB_SOURCE_MISMATCH');
1651
1759
  }
1652
1760
  const evidence = checkpointEvidenceFields(source, source.plan, retained.subjects, retained.seals);
1653
1761
  const previous = previousDraftFields(source, source.selector, retained.seals);
1654
1762
  const packageSourceHash = jobSha(retained.checkpointEvidencePackageHash);
1655
- const expected = packageSourceDigest(packageSourceHash, retained.record, source, retained.seals, {...evidence, ...previous});
1763
+ const chest = hasChest ? {chestLandmarks: parsePublishedChestLandmarks(retained.chestLandmarks)} : {};
1764
+ if (chest.chestLandmarks?.some(seed => !retained.seals.some(file => file.sha256 === seed.source.configHash))) {
1765
+ throw new JobError('JOB_SOURCE_MISMATCH');
1766
+ }
1767
+ const expected = packageSourceDigest(packageSourceHash, retained.record, source, retained.seals, {...evidence, ...previous, ...chest});
1656
1768
  if (expected !== source.sourceHash ||
1657
1769
  requestDigest(evidence.checkpointEvidence ?? null) !== requestDigest(source.checkpointEvidence ?? null) ||
1658
1770
  requestDigest(previous.previousDraft ?? null) !== requestDigest(source.previousDraft ?? null)) {
package/src/job-store.ts CHANGED
@@ -370,11 +370,13 @@ export class JobStore<Data> {
370
370
  readonly active?: boolean;
371
371
  readonly snapshot?: JobSnapshotOwner;
372
372
  readonly still?: JobStoredStill;
373
- }, replay?: (current: StoredJob<Data>) => boolean): StoredJob<Data> {
373
+ }, replay?: (current: StoredJob<Data>) => boolean, sameSemanticRevision?: (current: StoredJob<Data>) => boolean): StoredJob<Data> {
374
374
  return this.transaction(() => {
375
375
  const current = this.get(jobId);
376
376
  if (replay?.(current)) return current;
377
- if (expectedRevision !== null && current.revision !== expectedRevision) throw new JobError('JOB_GENERATION_STALE');
377
+ if (expectedRevision !== null && current.revision !== expectedRevision && !sameSemanticRevision?.(current)) {
378
+ throw new JobError('JOB_GENERATION_STALE');
379
+ }
378
380
  const next = operation(current);
379
381
  const active = next.active ?? current.active;
380
382
  const document = encode(JSON.parse(this.saveCrops(next.data)));
@@ -451,12 +453,13 @@ export class JobStore<Data> {
451
453
  /** Close never grows or rewrites the bounded historical document. */
452
454
  sealClose(jobId: string, expectedRevision: number,
453
455
  replay: (current: StoredJob<Data>) => Pick<JobClosure, 'replay'> | null,
454
- prepare: (current: StoredJob<Data>) => JobClosure): Pick<JobClosure, 'replay'> {
456
+ prepare: (current: StoredJob<Data>) => JobClosure,
457
+ sameSemanticRevision?: (current: StoredJob<Data>) => boolean): Pick<JobClosure, 'replay'> {
455
458
  return this.transaction(() => {
456
459
  const current = this.get(jobId);
457
460
  const previous = replay(current);
458
461
  if (previous) return previous;
459
- if (current.revision !== expectedRevision) throw new JobError('JOB_GENERATION_STALE');
462
+ if (current.revision !== expectedRevision && !sameSemanticRevision?.(current)) throw new JobError('JOB_GENERATION_STALE');
460
463
  if (!current.active) throw new JobError('JOB_CLOSED');
461
464
  const closure = prepare(current), document = encode(closure);
462
465
  this.db.query('INSERT INTO job_closures(job_id,document) VALUES(?,?)').run(jobId, document);
package/src/manifest.ts CHANGED
@@ -7,6 +7,7 @@ import { toolVersions } from './versions.ts';
7
7
  import type { FeedbackCatalog } from './feedback-validation.ts';
8
8
  import { validatePoseSequence } from './pose.ts';
9
9
  import { parseReport, type ReportSeeds } from './report.ts';
10
+ import { framesSetClock, type DeclaredFrameClock } from './frame-clock.ts';
10
11
  import { readFile, realpath, stat, lstat, readdir } from 'node:fs/promises';
11
12
  import { createReadStream } from 'node:fs';
12
13
  import { basename, dirname, isAbsolute, relative, resolve, posix } from 'node:path';
@@ -19,7 +20,7 @@ export type Json = null | boolean | number | string | Json[] | { [key: string]:
19
20
  export interface Reference { id: string; label: string; type: 'image' | 'video' | 'pose'; path: string; width?: number; height?: number }
20
21
  export interface Checkpoint { id: string; title: string; time?: number; animation?: string; reference?: string; note?: string; workspace?: 'modeling' | 'motion'; camera?: { zoom: number; x: number; y: number }; axis?: {id:string;value:number} }
21
22
  export interface ReviewManifest {
22
- schema: 'rig-review/1'; id: string; title: string; revision: string; model?: string; motion?: string;
23
+ schema: 'rig-review/1'; id: string; title: string; revision: string; model?: string; frames?: string; motion?: string;
23
24
  direction?: string; scene?: string; sets?: string;
24
25
  references: Reference[]; animations: { id: string; label?: string; duration?: number }[];
25
26
  checkpoints: Checkpoint[]; authoring: { label: string; path: string }[];
@@ -29,8 +30,10 @@ export interface ReviewManifest {
29
30
  producer?: HandoffDeclaration;
30
31
  panels?: JobPanelComposition;
31
32
  }
33
+ export interface ReviewFrameSet { animation: string; fps: number; written: number; stride: number; duration: number }
34
+ export interface ReviewFrames { path: string; sha256: string; sets: ReviewFrameSet[] }
32
35
  export interface ReviewedSource { readonly packageRevision:string; readonly viewerVersion:string; readonly runtimeVersion:string; readonly rig:{readonly path:string;readonly sha256:string}|null; readonly motion:{readonly path:string;readonly sha256:string}|null; readonly handoff?:HandoffRecord }
33
- export interface ReviewPackage { scene?:SceneInspection; direction?:DirectionInspection; setsHash?:string; referenceHashes?:Record<string,string>; root: string; manifestPath: string; manifest: ReviewManifest; sourceHash: string; reviewedSource:ReviewedSource; files: Set<string>; report:ReportSeeds|null; feedbackCatalog:FeedbackCatalog;
36
+ export interface ReviewPackage { scene?:SceneInspection; direction?:DirectionInspection; setsHash?:string; referenceHashes?:Record<string,string>; root: string; manifestPath: string; manifest: ReviewManifest; sourceHash: string; reviewedSource:ReviewedSource; files: Set<string>; report:ReportSeeds|null; frames:ReviewFrames|null; feedbackCatalog:FeedbackCatalog;
34
37
  /** The resolved producer handoff (#101) and, when there is none, the refusal line naming where it was looked for. */
35
38
  handoff: Handoff|null; handoffReason: string|null; handoffInputs?: HandoffFlags;
36
39
  /** #187: the rig-parts build root ({@link isBuildRoot}) whose `check/` this package is, however it was opened; review state stays outside it. */
@@ -80,6 +83,7 @@ export function parseManifest(input: unknown): ReviewManifest {
80
83
  const manifest: ReviewManifest = {
81
84
  schema: 'rig-review/1', id: id(m.id, 'id'), title: string(m.title, 'title'), revision: string(m.revision, 'revision'),
82
85
  model: m.model === undefined ? undefined : packagePath(m.model, 'model'),
86
+ ...(m.frames===undefined?{}:{frames:packagePath(m.frames,'frames')}),
83
87
  ...(m.direction===undefined?{}:{direction:packagePath(m.direction,'direction')}),
84
88
  ...(m.scene===undefined?{}:{scene:packagePath(m.scene,'scene')}),
85
89
  ...(m.sets===undefined?{}:{sets:packagePath(m.sets,'sets')}),
@@ -103,6 +107,49 @@ export function parseManifest(input: unknown): ReviewManifest {
103
107
  for(const c of manifest.checkpoints) if(c.axis){const a=manifest.axes.find(a=>a.id===c.axis!.id);if(!a)fail(`checkpoint ${c.id}.axis`,'declared axis id');if(c.axis.value<a.min||c.axis.value>a.max)fail(`checkpoint ${c.id}.axis.value`,`number in [${a.min}, ${a.max}]`);}
104
108
  return manifest;
105
109
  }
110
+ function parseFrames(text: string, path: string, sha256: string): ReviewFrames {
111
+ let raw: unknown;
112
+ try { raw = JSON.parse(text); } catch (e) { throw new Error(`FRAMES_JSON: ${path}: ${e instanceof Error ? e.message : String(e)}`); }
113
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw new Error(`FRAMES_FIELD: ${path}: expected object`);
114
+ const doc = raw as Record<string, unknown>;
115
+ if (doc.spec !== 'rigc-frames/1') throw new Error(`FRAMES_SPEC: ${path}.spec: expected rigc-frames/1`);
116
+ if (!Array.isArray(doc.sets) || doc.sets.length > 10000) throw new Error(`FRAMES_FIELD: ${path}.sets: expected array of at most 10000 entries`);
117
+ const seen = new Set<string>();
118
+ const sets = doc.sets.map((entry, i): ReviewFrameSet => {
119
+ const f = `${path}.sets[${i}]`;
120
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) throw new Error(`FRAMES_FIELD: ${f}: expected object`);
121
+ const s = entry as Record<string, unknown>;
122
+ if (typeof s.animation !== 'string' || !s.animation.trim() || s.animation.length > 10000) throw new Error(`FRAMES_FIELD: ${f}.animation: expected nonempty string`);
123
+ if (seen.has(s.animation)) throw new Error(`FRAMES_DUPLICATE_ANIMATION: ${f}.animation: duplicate animation ${JSON.stringify(s.animation)}`);
124
+ seen.add(s.animation);
125
+ if (typeof s.fps !== 'number' || !Number.isSafeInteger(s.fps) || s.fps <= 0) throw new Error(`FRAMES_FIELD: ${f}.fps: expected integer > 0`);
126
+ if (typeof s.written !== 'number' || !Number.isSafeInteger(s.written) || s.written < 0) throw new Error(`FRAMES_FIELD: ${f}.written: expected integer >= 0`);
127
+ if (typeof s.stride !== 'number' || !Number.isSafeInteger(s.stride) || s.stride <= 0) throw new Error(`FRAMES_FIELD: ${f}.stride: expected integer > 0`);
128
+ if (typeof s.duration !== 'number' || !Number.isFinite(s.duration) || s.duration < 0) throw new Error(`FRAMES_FIELD: ${f}.duration: expected finite number >= 0`);
129
+ return { animation: s.animation, fps: s.fps, written: s.written, stride: s.stride, duration: s.duration };
130
+ });
131
+ return { path, sha256, sets };
132
+ }
133
+ /** Seconds a set's `duration` may differ from the producer's last sample time: float rounding only (#1018). */
134
+ export const FRAMES_DURATION_TOLERANCE = 1e-9;
135
+ /**
136
+ * #1018: one clock per set of the declared record, each checked against the compiled model's animation before it
137
+ * indexes anything. The producer samples an animation of duration D at fps to round(D * fps) + 1 frames, frame i at
138
+ * i / fps, writes every stride-th one from frame 0, and records the last sample's time as `duration`; a set that is
139
+ * not that schedule for the model's animation is refused by name. An animation the report's clock names keeps the
140
+ * report's clock, so its set adds none. A package without a compiled model plays nothing, so its record adds no clock.
141
+ */
142
+ function declaredFrameClocks(frames: ReviewFrames, animations: {name: string; duration: number}[], report: ReportSeeds | null): DeclaredFrameClock[] {
143
+ return frames.sets.flatMap(set => {
144
+ const where = `${frames.path}: set ${JSON.stringify(set.animation)}`;
145
+ const clip = animations.find(value => value.name === set.animation);
146
+ if (!clip) throw new Error(`FRAMES_ANIMATION_UNKNOWN: ${where} names no animation of the compiled model`);
147
+ const last = Math.round(clip.duration * set.fps), written = Math.floor(last / set.stride) + 1;
148
+ if (set.written !== written) throw new Error(`FRAMES_COUNT_MISMATCH: ${where} writes ${set.written} frame(s) at ${set.fps} fps stride ${set.stride}; the model's ${clip.duration} s animation samples to ${written}`);
149
+ if (Math.abs(set.duration - last / set.fps) > FRAMES_DURATION_TOLERANCE) throw new Error(`FRAMES_DURATION_MISMATCH: ${where} lasts ${set.duration} s; the model's ${clip.duration} s animation at ${set.fps} fps ends its last sample at ${last / set.fps} s`);
150
+ return report?.clock && report.animation === set.animation ? [] : [{animation: set.animation, clock: framesSetClock(set)}];
151
+ });
152
+ }
106
153
  export const BUILD_MODEL_PATH = 'build/skeleton.model.json';
107
154
  interface ReviewLoadOptions {
108
155
  /** Explicit producer flags take precedence over discovery. False disables producer lookup. */
@@ -124,11 +171,14 @@ export async function loadReview(input: string, options: ReviewLoadOptions = {})
124
171
  const assetFile=async(path:string):Promise<string>=>{
125
172
  if(sealedPlayback&&!sealedPlayback.has(path))fail(path,'sealed playback file');
126
173
  const literal=sealedPlayback?checkedPath(root,path):undefined;
127
- const full=await safeFile(root,path);
174
+ let full:string;
175
+ try{full=await safeFile(root,path);}
176
+ catch(e){if(path===manifest.frames&&['ENOENT','ENOTDIR'].includes((e as NodeJS.ErrnoException).code??''))throw new Error(`FRAMES_MISSING: ${path}: ${(e as Error).message}`);throw e;}
128
177
  if(literal!==undefined&&full!==literal)fail(path,'file without symlinks');
129
178
  return full;
130
179
  };
131
180
  const files = new Set([...(directory?[]:[relative(root,manifestPath)]),...manifest.references.map(v=>v.path),...manifest.authoring.map(v=>v.path),...manifest.audio.clips.map(v=>v.path)]);
181
+ if(manifest.frames)files.add(manifest.frames);
132
182
  if(manifest.direction)files.add(manifest.direction);
133
183
  if(manifest.sets)files.add(manifest.sets);
134
184
  const rootFile=async(name:string):Promise<string|undefined>=>{try{await safeFile(root,name);return name;}catch(e){if((e as NodeJS.ErrnoException).code==='ENOENT')return undefined;throw e;}};
@@ -158,7 +208,7 @@ export async function loadReview(input: string, options: ReviewLoadOptions = {})
158
208
  const joints=list(pose.joints,`pose ${r.id}.joints`,(v,f)=>({id:id(v.id,f+'.id'),x:number(v.x,f+'.x',-Number.MAX_VALUE),y:number(v.y,f+'.y',-Number.MAX_VALUE),parent:optionalString(v.parent,f+'.parent')}));
159
209
  for(const j of joints) if(j.parent&&!joints.some(v=>v.id===j.parent&&v.id!==j.id)) fail(`pose ${r.id} joint ${j.id}.parent`,'another declared joint id');
160
210
  }
161
- const reportPath=files.has('report.json')?'report.json':authoringPath('report.json');let report:ReportSeeds|null=null;let modelMetadata:Record<string,unknown>|null=null;let directionInput:unknown;
211
+ const reportPath=files.has('report.json')?'report.json':authoringPath('report.json');let report:ReportSeeds|null=null;let frames:ReviewFrames|null=null;let modelMetadata:Record<string,unknown>|null=null;let directionInput:unknown;
162
212
  // The handoff files are hashed beside the package: their record joins the reviewed identity (and so the session file).
163
213
  const {handoff,reason:handoffReason}=options.handoff===false?{handoff:null,reason:null}:
164
214
  await resolveHandoff(root,manifest.producer,options.handoff,{starts:options.handoffStarts??[options.cwd??process.cwd()]});
@@ -182,20 +232,22 @@ export async function loadReview(input: string, options: ReviewLoadOptions = {})
182
232
  }
183
233
  const hash = createHash('sha256');hash.update(JSON.stringify(manifest));hash.update('\0');const fileHashes=new Map<string,string>();
184
234
  for(const p of [...files].sort()) { const full=await assetFile(p); const before=await stat(full); hash.update(p);hash.update('\0');hash.update(String(before.size));hash.update('\0'); const fileHash=createHash('sha256');const metadataChunks:Buffer[]=[];const isDirection=p===manifest.direction;let bytesRead=0;
185
- if(isDirection&&before.size>DIRECTION_MAX_BYTES)throw new Error('DIRECTION_SIZE: direction exceeds 256 KiB');for await(const chunk of createReadStream(full)){hash.update(chunk);fileHash.update(chunk);if(isDirection&&(bytesRead+=chunk.length)>DIRECTION_MAX_BYTES)throw new Error('DIRECTION_SIZE: direction exceeds 256 KiB');if(p===reportPath||p===manifest.model||isDirection)metadataChunks.push(chunk);}fileHashes.set(p,fileHash.digest('hex'));if(sceneBytes.has(p)&&createHash('sha256').update(sceneBytes.get(p)!).digest('hex')!==fileHashes.get(p))throw new Error('SCENE_SOURCE_MISMATCH: '+p); const after=await stat(full); if(before.size!==after.size||before.mtimeMs!==after.mtimeMs) throw new Error(`Asset ${p} changed while hashing; retry with stable package inputs`);
235
+ if(isDirection&&before.size>DIRECTION_MAX_BYTES)throw new Error('DIRECTION_SIZE: direction exceeds 256 KiB');for await(const chunk of createReadStream(full)){hash.update(chunk);fileHash.update(chunk);if(isDirection&&(bytesRead+=chunk.length)>DIRECTION_MAX_BYTES)throw new Error('DIRECTION_SIZE: direction exceeds 256 KiB');if(p===reportPath||p===manifest.model||isDirection||p===manifest.frames)metadataChunks.push(chunk);}fileHashes.set(p,fileHash.digest('hex'));if(sceneBytes.has(p)&&createHash('sha256').update(sceneBytes.get(p)!).digest('hex')!==fileHashes.get(p))throw new Error('SCENE_SOURCE_MISMATCH: '+p); const after=await stat(full); if(before.size!==after.size||before.mtimeMs!==after.mtimeMs) throw new Error(`Asset ${p} changed while hashing; retry with stable package inputs`);
186
236
  if(sealedPlayback&&fileHashes.get(p)!==sealedPlayback.get(p))fail(p,'sealed playback hash');
187
237
  // The parser and package hash consume the same bytes, never two file reads.
188
238
  if(p===manifest.model){if(fileHashes.get(p)!==modelBytesHash)throw new Error(`Model ${p} changed while hashing; retry with stable package inputs`);modelMetadata=object(JSON.parse(Buffer.concat(metadataChunks).toString('utf8')),'model');}
189
239
  if(isDirection)directionInput=JSON.parse(Buffer.concat(metadataChunks).toString('utf8'));
190
240
  if(p===reportPath){let value:unknown;try{value=JSON.parse(Buffer.concat(metadataChunks).toString('utf8'));}catch(e){throw new Error(`${p}: ${e instanceof Error?e.message:String(e)}`);}report=parseReport(value,p);}
241
+ if(p===manifest.frames)frames=parseFrames(Buffer.concat(metadataChunks).toString('utf8'),p,fileHashes.get(p)!);
191
242
  }
192
243
  if(painting){hash.update(SOURCE_PAINTING_ID);hash.update('\0');hash.update(painting.sha256);hash.update('\0');}
193
244
  // #192: the root is `check/` whether the folder or its review.json was opened, so the build root is kept either way.
194
245
  const buildRoot=!sealedPlayback&&basename(root)==='check'&&await isBuildRoot(dirname(root))?dirname(root):undefined;
195
246
  const reviewedSource:ReviewedSource={packageRevision:manifest.revision,...await toolVersions(),rig:rigPath?{path:rigPath,sha256:fileHashes.get(rigPath)!}:null,motion:motionPath?{path:motionPath,sha256:fileHashes.get(motionPath)!}:null,...(handoff?{handoff:handoff.record}:{})};
196
247
  const direction=manifest.direction?readDirectionInspection(directionInput,{path:manifest.direction,sha256:fileHashes.get(manifest.direction)!},reviewedSource.rig):undefined;
197
- const feedbackCatalog:FeedbackCatalog={rig:manifest.id,bones:modelNames(modelMetadata,'bones'),slots:modelNames(modelMetadata,'slots'),animations:modelAnimations(modelMetadata),clock:report?.clock??null,clockAnimation:report?.animation??null,...(discoverTurnDials(modelMetadata).length?{turnDials:discoverTurnDials(modelMetadata)}:{})};
198
- return {...(scene?{scene}:{}),...(direction?{direction}:{}),...(manifest.sets?{setsHash:fileHashes.get(manifest.sets)!}:{}),referenceHashes:Object.fromEntries(manifest.references.map(r=>[r.id,r.id===painting?.id?painting.sha256:fileHashes.get(r.path)!])),root,manifestPath,manifest,sourceHash:hash.digest('hex'),reviewedSource,files,report,feedbackCatalog,handoff,handoffReason,...(handoff?.flags?{handoffInputs:handoff.flags}:{}),...(buildRoot?{buildRoot}:{}),...(painting?{sourcePainting:painting}:{}),...(options.cwd?{cwd:options.cwd}:{}),...(options.handoffStarts?{handoffStarts:options.handoffStarts}:{})};
248
+ const animations=modelAnimations(modelMetadata);
249
+ const feedbackCatalog:FeedbackCatalog={rig:manifest.id,bones:modelNames(modelMetadata,'bones'),slots:modelNames(modelMetadata,'slots'),animations,clock:report?.clock??null,clockAnimation:report?.animation??null,...(frames&&animations?{frameClocks:declaredFrameClocks(frames,animations,report)}:{}),...(discoverTurnDials(modelMetadata).length?{turnDials:discoverTurnDials(modelMetadata)}:{})};
250
+ return {...(scene?{scene}:{}),...(direction?{direction}:{}),...(manifest.sets?{setsHash:fileHashes.get(manifest.sets)!}:{}),referenceHashes:Object.fromEntries(manifest.references.map(r=>[r.id,r.id===painting?.id?painting.sha256:fileHashes.get(r.path)!])),root,manifestPath,manifest,sourceHash:hash.digest('hex'),reviewedSource,files,report,frames,feedbackCatalog,handoff,handoffReason,...(handoff?.flags?{handoffInputs:handoff.flags}:{}),...(buildRoot?{buildRoot}:{}),...(painting?{sourcePainting:painting}:{}),...(options.cwd?{cwd:options.cwd}:{}),...(options.handoffStarts?{handoffStarts:options.handoffStarts}:{})};
199
251
  }
200
252
 
201
253
  /** #329: the reference id and served path of the handoff's source painting; the path is a name, never a package file. */
@@ -32,7 +32,12 @@ export async function readPrivate(path: string): Promise<unknown | null> {
32
32
  const info = await lstat(path);
33
33
  // lstat can finish with nlink=0 during unlink. Establish that the path still
34
34
  // opens before validating that snapshot; a vanished path remains ENOENT.
35
- return await smallJson(path, () => assertPrivateInfo(info, false));
35
+ // On Linux the open can still reach that same detached inode (fstat nlink=0, #894):
36
+ // no path names it any more, so it is absent too. A reappeared file still refuses.
37
+ return await smallJson(path, opened => {
38
+ if (info.nlink === 0 && opened.nlink === 0) throw Object.assign(new Error('detached'), {code: 'ENOENT'});
39
+ assertPrivateInfo(info, false);
40
+ });
36
41
  }
37
42
  catch (error) {if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null; throw workspaceError('WORKSPACE_STATE_INVALID');}
38
43
  }
package/src/open.ts CHANGED
@@ -5,7 +5,7 @@ import {createHash,randomBytes,randomUUID} from 'node:crypto';
5
5
  import {spawn} from 'node:child_process';
6
6
  import {homedir} from 'node:os';
7
7
  import {mkdir,readFile,readdir,writeFile,rename,unlink,rm,rmdir,realpath,lstat,stat,open as openFile} from 'node:fs/promises';
8
- import {constants} from 'node:fs';
8
+ import {constants,type Stats} from 'node:fs';
9
9
  import {basename,dirname,join,resolve,isAbsolute} from 'node:path';
10
10
  import {fileURLToPath} from 'node:url';
11
11
  import {loadReferencedReview,selectedReference,assertReviewUnchanged} from './reference.ts';
@@ -73,8 +73,8 @@ export function openKey(p:OpenPackage,fingerprint:string):string {return digest(
73
73
  /** Handoff URL: the managed front's `/instances/<key>/` path (or the worker's own origin when direct). The
74
74
  * capability rides in the fragment, which browsers never send to a server; the page stores and strips it. */
75
75
  export function openUrl(record:Pick<RecordFile,'origin'|'key'|'contentHash'|'capability'>,front?:string):string {const url=new URL(front?`${front}/instances/${record.key}/`:record.origin);url.searchParams.set('input',record.contentHash);url.searchParams.set('handoff',record.key);url.hash='cap='+record.capability;return url.href;}
76
- /** Optional caller validation runs after open, before any content read, inside the close guard. */
77
- export async function smallJson(file:string,validate?:()=>void):Promise<unknown>{const handle=await openFile(file,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK);try{validate?.();const before=await handle.stat();if(!before.isFile()||before.size>65536)throw new Error('open state: bounded regular file required');const buffer=Buffer.alloc(before.size+1);let size=0;while(size<buffer.length){const next=await handle.read(buffer,size,buffer.length-size,size);if(!next.bytesRead)break;size+=next.bytesRead;}const after=await handle.stat();if(size!==before.size||before.size!==after.size||before.mtimeMs!==after.mtimeMs)throw new Error('open state: changed while reading');return JSON.parse(buffer.subarray(0,size).toString('utf8'));}finally{await handle.close();}}
76
+ /** Optional caller validation runs after open with the opened descriptor's fstat, before any content read, inside the close guard. */
77
+ export async function smallJson(file:string,validate?:(opened:Stats)=>void):Promise<unknown>{const handle=await openFile(file,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK);try{const before=await handle.stat();validate?.(before);if(!before.isFile()||before.size>65536)throw new Error('open state: bounded regular file required');const buffer=Buffer.alloc(before.size+1);let size=0;while(size<buffer.length){const next=await handle.read(buffer,size,buffer.length-size,size);if(!next.bytesRead)break;size+=next.bytesRead;}const after=await handle.stat();if(size!==before.size||before.size!==after.size||before.mtimeMs!==after.mtimeMs)throw new Error('open state: changed while reading');return JSON.parse(buffer.subarray(0,size).toString('utf8'));}finally{await handle.close();}}
78
78
  function recordValue(value:unknown,key:string):RecordFile|null {if(!value||typeof value!=='object')return null;const v=value as Partial<RecordFile>;return v.schema==='rig-review-open-instance/1'&&v.key===key&&/^[a-f0-9]{64}$/.test(v.contentHash??'')&&/^[a-f0-9]{64}$/.test(v.fingerprint??'')&&typeof v.nonce==='string'&&/^[a-f0-9-]{36}$/.test(v.nonce)&&typeof v.origin==='string'&&/^http:\/\/127\.0\.0\.1:[1-9]\d{0,4}$/.test(v.origin)&&Number(v.origin.slice(v.origin.lastIndexOf(':')+1))<=65535&&Number.isSafeInteger(v.pid)&&v.pid!>0&&(v.mode==='single'||v.mode==='compare')&&capabilityPattern.test(v.capability??'')?v as RecordFile:null;}
79
79
  export async function readRecord(file:string,key:string):Promise<RecordFile|null>{try{return recordValue(await smallJson(file),key);}catch(e){if(['ENOENT','ELOOP'].includes((e as NodeJS.ErrnoException).code??'')||e instanceof SyntaxError)return null;throw e;}}
80
80
  /** Hard byte ceiling and body deadline, including stalled or chunked responses. */