rig-review 4.4.0 → 4.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rig-review",
3
- "version": "4.4.0",
3
+ "version": "4.6.0",
4
4
  "type": "module",
5
5
  "description": "Local human rig inspection and structured feedback export",
6
6
  "license": "MIT",
@@ -16,23 +16,32 @@ export interface DirectionInspection {
16
16
  };
17
17
  postVersion?: number;
18
18
  rigVersion: number;
19
+ /**
20
+ * rig-create/direction@3: the take is the composed model's own `idle`, played at the model stage.
21
+ * @3 authors no camera, timing or scene, so its camera and timing key lists are empty.
22
+ */
23
+ composed?: true;
19
24
  camera: { space: 'rig-world-y-up'; keys: { time: number; easing: string; box: { x: number; y: number; width: number; height: number } }[] };
20
25
  take: { duration: number; loop: boolean };
21
26
  timing: { time: number; source_time: number; easing: string }[];
22
27
  }
23
28
 
24
29
  /**
25
- * Read the inspection subset of Create's rig-create/direction@1 or rig-create/direction@2.
26
- * Scene bytes are inspected separately when the manifest declares them.
27
- * Create validates scene, project history and citations.
30
+ * Read the inspection subset of Create's rig-create/direction@1, @2 or @3.
31
+ * Scene bytes are inspected separately when the manifest declares them; @3 has no scene.
32
+ * Create validates scene, compose, acceptance, project history and citations.
28
33
  */
29
34
  export function readDirectionInspection(value: unknown, file: Binding, model: Binding | null): DirectionInspection {
30
35
  const doc = object(value, 'direction');
31
- if (doc.schema !== 'rig-create/direction@1' && doc.schema !== 'rig-create/direction@2')
32
- throw new Error('DIRECTION_SCHEMA: expected rig-create/direction@1 or rig-create/direction@2');
36
+ const composed = doc.schema === 'rig-create/direction@3';
37
+ if (doc.schema !== 'rig-create/direction@1' && doc.schema !== 'rig-create/direction@2' && !composed)
38
+ throw new Error('DIRECTION_SCHEMA: expected rig-create/direction@1, rig-create/direction@2 or rig-create/direction@3');
33
39
  const rig = object(doc.rig, 'direction.rig');
34
- const binding = object(rig.model, 'direction.rig.model');
35
- const path = packagePath(binding.path, 'direction.rig.model.path');
40
+ // @3 binds the compiled model at the top level; @1/@2 bind it under rig.
41
+ if (composed && (!doc.model || typeof doc.model !== 'object')) throw new Error('DIRECTION_SCHEMA: rig-create/direction@3 requires a top-level model');
42
+ const field = composed ? 'direction.model' : 'direction.rig.model';
43
+ const binding = object(composed ? doc.model : rig.model, field);
44
+ const path = packagePath(binding.path, field + '.path');
36
45
  if (!model || path !== model.path || binding.sha256 !== model.sha256)
37
46
  throw new Error('DIRECTION_MODEL_MISMATCH: expected the inspected model path and SHA-256');
38
47
  const rigVersion = numberField(rig.version, 'direction.rig.version', 1);
@@ -40,6 +49,7 @@ export function readDirectionInspection(value: unknown, file: Binding, model: Bi
40
49
  const take = object(doc.take, 'direction.take');
41
50
  const duration = numberField(take.duration, 'direction.take.duration');
42
51
  if (duration === 0 || typeof take.loop !== 'boolean') throw new Error('DIRECTION_SCHEMA: expected positive duration and loop boolean');
52
+ if (composed) return { file, model, rigVersion, composed: true, camera: { space: 'rig-world-y-up', keys: [] }, take: { duration, loop: take.loop }, timing: [] };
43
53
  const camera = object(doc.camera, 'direction.camera');
44
54
  const timing = object(doc.timing, 'direction.timing');
45
55
  if (camera.space !== 'rig-world-y-up') throw new Error('DIRECTION_SCHEMA: expected rig-world-y-up camera');
package/src/job-front.ts CHANGED
@@ -5,10 +5,10 @@ import {checkpointEvidenceMetadata, readCheckpointEvidenceBytes} from './job-che
5
5
  import { JOB_API_SCHEMA, JOB_ACT_SCHEMA, type JobErrorCode, type JobHostPorts, type JobId, type JobPublicationMode, type JobResult, type JobReviewerBinding } from './job-contract.ts';
6
6
  import { createJobHostPorts, jobBody, jobHash, jobId, jobObject, jobPartsEnumeratorVersion } from './job-api.ts';
7
7
  import { JobSession } from './job-session.ts';
8
- import { assertJobRoot, assertRetainedSnapshotIntact, captureJobRoot, planTextMetadata, isRetainedRecordSource, type JobRootIdentity } from './job-source.ts';
8
+ import { assertJobRoot, assertRetainedSnapshotIntact, captureJobRoot, planTextMetadata, isRetainedRecordSource, loadRetainedJobReview, type JobRootIdentity } from './job-source.ts';
9
9
  import type { JobWorkerOptions } from './job-worker.ts';
10
10
  import { JobError, JobStore, jobCropReferences } from './job-store.ts';
11
- import { loadReview, safeFile, packagePath, type ReviewPackage } from './manifest.ts';
11
+ import { safeFile, packagePath, type ReviewPackage } from './manifest.ts';
12
12
  import { serveReference, assertReviewUnchanged } from './reference.ts';
13
13
  import {preparePartsComment} from './parts-comment-crops.ts';
14
14
  import { loadPartsView, partsViewJson, partsDifference, servedImage, type PartsViewPackage } from './parts-view.ts';
@@ -331,7 +331,7 @@ export function retainedPublicationRoutes(session: JobSession) {
331
331
  let pending = views.get(publicationId);
332
332
  if (!pending) {
333
333
  pending = (async () => {
334
- const review = await loadReview(retained.manifestPath);
334
+ const review = await loadRetainedJobReview(retained, session.attestation().fingerprint);
335
335
  const partsRoot = retained.source.parts
336
336
  ? dirname(join(retained.snapshotRoot, retained.source.parts.manifest.path)) : null;
337
337
  // Forward only retained producer files. Discovery never reads the live draft.
@@ -466,7 +466,8 @@ export function retainedPublicationRoutes(session: JobSession) {
466
466
  const code = error instanceof JobError ? error.code :
467
467
  error instanceof Error && error.message.startsWith('PARTS_COMMENT_STALE_SOURCE:')
468
468
  ? 'PARTS_COMMENT_STALE_SOURCE' : 'JOB_SOURCE_MISMATCH';
469
- const message = error instanceof JobError && /^(CHECKPOINT_EVIDENCE|PLAN_TEXT)_[A-Z_]+$/.test(error.message)
469
+ const message = error instanceof JobError && (/^(CHECKPOINT_EVIDENCE|PLAN_TEXT)_[A-Z_]+$/.test(error.message) ||
470
+ error.code === 'JOB_SOURCE_UNRETAINABLE' && error.message.startsWith('snapshot reload '))
470
471
  ? error.message : undefined;
471
472
  return failure(code, errorStatus[code as JobErrorCode] ?? 409, undefined, message);
472
473
  }
@@ -10,12 +10,11 @@ import {
10
10
  import { bindJobAsk, bindJobRecordAsk, finalizeJobAct, parseUISubmission, prepareJobRecordAct, prepareJobStill } from './job-act.ts';
11
11
  import { isRecordSource, parseRecordSource, parseCommentsAct, jobApiSchemaForMode, jobHash, jobPartsEnumeratorVersion, jobWaitLimitMs, requestDigest, sameCapability } from './job-api.ts';
12
12
  import {
13
- assertStoredCheckpointEvidence, assertJobRoot, assertJobSourceCurrent, assertRetainedSnapshotIntact, captureJobRoot, isRetainedRecordSource, prepareJobSource, jobSnapshotHash, removeOwnedJobSnapshot, verifyJobRecordSourceFresh,
13
+ assertStoredCheckpointEvidence, assertJobRoot, assertJobSourceCurrent, assertRetainedSnapshotIntact, captureJobRoot, isRetainedRecordSource, loadRetainedJobReview, prepareJobSource, jobSnapshotHash, removeOwnedJobSnapshot, verifyJobRecordSourceFresh,
14
14
  type JobPublicationReader, type JobRetainedSource, type JobRetainedSourceV3, type JobRootIdentity,
15
15
  } from './job-source.ts';
16
16
  import { JobError, JobStore, jobCropReferences, type JobSnapshotOwner, type StoredJob } from './job-store.ts';
17
17
  import { canonicalStatePath } from './state-dir.ts';
18
- import { loadReview } from './manifest.ts';
19
18
  import { loadPartsView } from './parts-view.ts';
20
19
  import { validateStoredPartsComment } from './parts-comment-crops.ts';
21
20
  import { commentPartsIssues } from './parts-comment.ts';
@@ -693,7 +692,7 @@ export class JobSession {
693
692
  assertRetainedSnapshotIntact(retained.snapshotRoot, retained.seals,
694
693
  retained.snapshotIdentity, 'JOB_ACT_SOURCE_STALE');
695
694
  try {
696
- const review = await loadReview(retained.manifestPath);
695
+ const review = await loadRetainedJobReview(retained, this.attestation().fingerprint);
697
696
  const painting = review.handoff?.source;
698
697
  const sealedPainting = painting && retained.seals.some(file =>
699
698
  file.path === relative(retained.snapshotRoot, painting).split(sep).join('/')) ? painting : undefined;
@@ -786,19 +785,35 @@ export class JobSession {
786
785
  };
787
786
  }
788
787
 
789
- private async next(after: string | null, waitMs: number, signal: AbortSignal): Promise<JobNextValue | NextValueV3> {
788
+ private async next(after: string | null, waitMs: number, signal: AbortSignal, observeWrites = false): Promise<JobNextValue | NextValueV3> {
790
789
  if (waitMs < 0 || waitMs > jobWaitLimitMs || !Number.isSafeInteger(waitMs)) throw new JobError('JOB_REQUEST_INVALID');
791
790
  if (signal.aborted) throw new JobError('JOB_REQUEST_INVALID', 'Request cancelled');
791
+ // Capture before reading events so a commit between the read and listener registration still wakes us.
792
+ const revision = observeWrites ? this.store.revision(this.jobId) : null;
792
793
  const ready = this.events(after);
793
794
  if (ready.status !== 'timeout' || !waitMs) return ready;
794
795
  await new Promise<void>((resolve, reject) => {
795
- const finish = () => { clearTimeout(timer); this.listeners.delete(finish); signal.removeEventListener('abort', abort); resolve(); };
796
- const abort = () => { clearTimeout(timer); this.listeners.delete(finish); signal.removeEventListener('abort', abort); reject(new JobError('JOB_REQUEST_INVALID', 'Request cancelled')); };
796
+ let poll: ReturnType<typeof setInterval> | undefined;
797
+ let settled = false;
798
+ const cleanup = () => { clearTimeout(timer); clearInterval(poll); this.listeners.delete(finish); signal.removeEventListener('abort', abort); };
799
+ const finish = () => { if (settled) return; settled = true; cleanup(); resolve(); };
800
+ const fail = (error: unknown) => { if (settled) return; settled = true; cleanup(); reject(error); };
801
+ const abort = () => fail(new JobError('JOB_REQUEST_INVALID', 'Request cancelled'));
802
+ const changed = () => {
803
+ try { if (this.store.revision(this.jobId) !== revision) finish(); }
804
+ catch (error) { fail(error); }
805
+ };
797
806
  const timer = setTimeout(finish, waitMs);
798
807
  this.listeners.add(finish);
799
808
  signal.addEventListener('abort', abort, { once: true });
800
- if (signal.aborted) abort();
801
- else if (this.events(after).status !== 'timeout') finish();
809
+ try {
810
+ if (signal.aborted) abort();
811
+ else if (observeWrites) {
812
+ // Other sessions commit to the same store but cannot notify this instance's listeners.
813
+ poll = setInterval(changed, 250);
814
+ changed();
815
+ } else if (this.events(after).status !== 'timeout') finish();
816
+ } catch (error) { fail(error); }
802
817
  });
803
818
  return this.events(after);
804
819
  }
@@ -808,7 +823,7 @@ export class JobSession {
808
823
  let after = input.after;
809
824
  while (!input.signal.aborted) {
810
825
  let value: JobNextValue | NextValueV3;
811
- try { value = await this.next(after, jobWaitLimitMs, input.signal); }
826
+ try { value = await this.next(after, jobWaitLimitMs, input.signal, true); }
812
827
  catch (error) {
813
828
  if (input.signal.aborted && error instanceof JobError && error.code === 'JOB_REQUEST_INVALID') return;
814
829
  throw error;
package/src/job-source.ts CHANGED
@@ -17,7 +17,7 @@ import type {
17
17
  RecordReaderInput, RecordResult, RecordSource, RecordSubject,
18
18
  } from './job-contract.ts';
19
19
  import { checkedPath, jsonObject, readProject, readRegular, type InterviewQuestion, type InterviewSet } from './interview-project.ts';
20
- import { loadReview } from './manifest.ts';
20
+ import { loadJobReview } from './manifest.ts';
21
21
  import { HandoffError } from './handoff.ts';
22
22
  import { openKey } from './open.ts';
23
23
  import { assertReviewUnchanged } from './reference.ts';
@@ -66,6 +66,18 @@ export interface JobPublishedContext {
66
66
  readonly files: readonly JobFileIdentity[];
67
67
  }
68
68
 
69
+ /** Reload only the identity recorded for this publication; old bindings are never relabelled. */
70
+ export async function loadRetainedJobReview(retained: JobRetainedSource, fingerprint: string) {
71
+ const review = await loadJobReview(retained.manifestPath, retained.root.path);
72
+ const found = openKey({mode: 'single', p: {...review, sourceHash: retained.source.sourceHash},
73
+ inputs: {input: join(retained.root.path, relative(retained.snapshotRoot, retained.manifestPath))},
74
+ contentHash: retained.source.sourceHash, selection: null}, fingerprint);
75
+ if (found !== retained.instanceKey) throw new JobError('JOB_SOURCE_UNRETAINABLE',
76
+ `snapshot reload instanceKey ${found} requires stored ${retained.instanceKey} ` +
77
+ `(handoff ${review.handoff?.record.config.path ?? 'none'})`);
78
+ return review;
79
+ }
80
+
69
81
  export type JobPublicationReader = (input: {
70
82
  readonly root: string;
71
83
  readonly record: JobFileIdentity;
@@ -1321,10 +1333,11 @@ export async function prepareJobSource(options: {
1321
1333
  const declared = publishedIdentities(context);
1322
1334
  const evidence = checkpointEvidenceFields(context, context.plan, context.subjects, declared);
1323
1335
  checkpointEvidenceMetadata(root.path, evidence.checkpointEvidence);
1324
- let review: Awaited<ReturnType<typeof loadReview>>;
1336
+ let review: Awaited<ReturnType<typeof loadJobReview>>;
1325
1337
  try {
1326
1338
  const target = checkedPath(root.path, request.result.path, lstatSync(join(root.path, request.result.path)).isDirectory());
1327
- review = await loadReview(target);
1339
+ // Resolve producer references from the designated job root for both copies.
1340
+ review = await loadJobReview(target, root.path);
1328
1341
  } catch (error) {
1329
1342
  throw new JobError('JOB_SOURCE_MISMATCH', error instanceof HandoffError ? error.message : undefined);
1330
1343
  }
@@ -1388,9 +1401,12 @@ export async function prepareJobSource(options: {
1388
1401
  options.afterDirectorySync?.(directory);
1389
1402
  }
1390
1403
  await assertReviewUnchanged(review);
1391
- const retained = await loadReview(join(snapshotRoot, request.result.path));
1404
+ const retained = await loadJobReview(join(snapshotRoot, request.result.path), root.path);
1392
1405
  if (retained.sourceHash !== review.sourceHash || requestDigest(retained.reviewedSource) !== requestDigest(review.reviewedSource)) {
1393
- throw new JobError('JOB_SOURCE_UNRETAINABLE');
1406
+ throw new JobError('JOB_SOURCE_UNRETAINABLE',
1407
+ `snapshot reload sourceHash ${retained.sourceHash} requires live ${review.sourceHash}; ` +
1408
+ `reviewedSource digest ${requestDigest(retained.reviewedSource)} requires ${requestDigest(review.reviewedSource)} ` +
1409
+ `(handoff snapshot ${retained.handoff?.record.config.path ?? 'none'}, live ${review.handoff?.record.config.path ?? 'none'})`);
1394
1410
  }
1395
1411
  const originalIdentity = (file: { path: string; sha256: string } | null): JobFileIdentity | null => file && ({
1396
1412
  path: rootRelative(root.path, resolve(review.root, file.path)), sha256: file.sha256,
package/src/job-store.ts CHANGED
@@ -294,6 +294,19 @@ export class JobStore<Data> {
294
294
  }
295
295
  }
296
296
 
297
+ /** Observe committed writes to one job without decoding its document or crops. */
298
+ revision(jobId: string): number {
299
+ try {
300
+ const row = this.db.query<{ revision: number }, [string]>('SELECT revision FROM jobs WHERE job_id=?').get(jobId);
301
+ if (!row) throw new JobError('JOB_UNKNOWN');
302
+ if (!Number.isSafeInteger(row.revision) || row.revision < 0) throw new JobError('JOB_STORAGE_FAILED');
303
+ return row.revision;
304
+ } catch (error) {
305
+ if (error instanceof JobError) throw error;
306
+ throw new JobError('JOB_STORAGE_FAILED', 'Stored job state is invalid');
307
+ }
308
+ }
309
+
297
310
  get(jobId: string): StoredJob<Data> {
298
311
  try {
299
312
  const row = this.db.query<JobRow, [string]>(`SELECT jobs.*, job_closures.document AS closure
package/src/manifest.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import {readSceneInspection,scenePlateBytes,type SceneInspection} from './scene-inspection.ts';
2
2
  import {DIRECTION_MAX_BYTES, readDirectionInspection, type DirectionInspection} from './direction-inspection.ts';
3
3
  import {discoverTurnDials} from './turn-pad.ts';
4
+ import {fileURLToPath} from 'node:url';
4
5
  import { createHash } from 'node:crypto';
5
6
  import { toolVersions } from './versions.ts';
6
7
  import type { FeedbackCatalog } from './feedback-validation.ts';
@@ -37,6 +38,8 @@ export interface ReviewPackage { scene?:SceneInspection; direction?:DirectionIns
37
38
  viewOnly?: boolean;
38
39
  /** Logical working directory passed at load/open time for resolving an external producer (`options.cwd`). */
39
40
  cwd?: string;
41
+ /** Explicit producer lookup roots, retained for source revalidation. */
42
+ handoffStarts?: readonly string[];
40
43
  /** #329: the handoff's source painting, served at a fixed route by its pinned hash; absent when the handoff knows none. */
41
44
  sourcePainting?: SourcePainting }
42
45
  function fail(field: string, expected: string): never { throw new Error(`${field}: expected ${expected}`); }
@@ -100,7 +103,7 @@ export function parseManifest(input: unknown): ReviewManifest {
100
103
  return manifest;
101
104
  }
102
105
  /** `options.handoff` are the explicit `--config …` flags; they win over the manifest block and discovery. */
103
- export async function loadReview(input: string, options: { handoff?: HandoffFlags; cwd?: string } = {}): Promise<ReviewPackage> {
106
+ export async function loadReview(input: string, options: { handoff?: HandoffFlags; cwd?: string; handoffStarts?: readonly string[] } = {}): Promise<ReviewPackage> {
104
107
  const inputPath=await realpath(resolve(input));const directory=(await stat(inputPath)).isDirectory();
105
108
  if(directory){try{await stat(resolve(inputPath,'review.json'));return loadReview(resolve(inputPath,'review.json'),options);}catch(e){if((e as NodeJS.ErrnoException).code!=='ENOENT')throw e;}
106
109
  // #149: a rig-parts build root without a model of its own opens as its check package, exactly as opening check/ does.
@@ -132,7 +135,7 @@ export async function loadReview(input: string, options: { handoff?: HandoffFlag
132
135
  }
133
136
  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;
134
137
  // The handoff files are hashed beside the package: their record joins the reviewed identity (and so the session file).
135
- const {handoff,reason:handoffReason}=await resolveHandoff(root,manifest.producer,options.handoff,{starts:[options.cwd??process.cwd()]});
138
+ const {handoff,reason:handoffReason}=await resolveHandoff(root,manifest.producer,options.handoff,{starts:options.handoffStarts??[options.cwd??process.cwd()]});
136
139
  // #329: the source painting the handoff knows is the first reference, outside the package's own files.
137
140
  const painting=sourcePainting(manifest,handoff,directory);
138
141
  let scene:SceneInspection|undefined;
@@ -165,7 +168,7 @@ export async function loadReview(input: string, options: { handoff?: HandoffFlag
165
168
  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}:{})};
166
169
  const direction=manifest.direction?readDirectionInspection(directionInput,{path:manifest.direction,sha256:fileHashes.get(manifest.direction)!},reviewedSource.rig):undefined;
167
170
  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)}:{})};
168
- 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}:{})};
171
+ 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}:{})};
169
172
  }
170
173
 
171
174
  /** #329: the reference id and served path of the handoff's source painting; the path is a name, never a package file. */
@@ -186,6 +189,11 @@ function sourcePainting(manifest:ReviewManifest,handoff:Handoff|null,folder:bool
186
189
  if(folder)manifest.checkpoints.unshift({id:reference.id,title:'Inspect '+reference.label,reference:reference.id,workspace:'motion'});
187
190
  return {id:reference.id,path:record.path,sha256:record.sha256};
188
191
  }
192
+ /** Job lookup is fixed to its designation and this Review install, never the operator's shell. */
193
+ export function loadJobReview(input: string, root: string): Promise<ReviewPackage> {
194
+ return loadReview(input, {cwd: root, handoffStarts: [root, fileURLToPath(new URL('..', import.meta.url))]});
195
+ }
196
+
189
197
  /**
190
198
  * #149: the `check/` package of a rig-parts build root ({@link isBuildRoot}), when the folder has neither of the two
191
199
  * adapter model paths itself (a folder that does keeps opening as before). Fixed names, no search.
@@ -1,5 +1,6 @@
1
1
  import {createHmac, randomUUID} from 'node:crypto';
2
2
  import {lstat, mkdir, rename, unlink, writeFile} from 'node:fs/promises';
3
+ import type {Stats} from 'node:fs';
3
4
  import {isAbsolute, join} from 'node:path';
4
5
  import {appRoot} from './build.ts';
5
6
  import {readOpenStatus, running, smallJson} from './open.ts';
@@ -10,12 +11,15 @@ import {WORKSPACE_BODY_LIMIT, WORKSPACE_SCHEMA, WORKSPACE_TARGETS_SCHEMA, WORKSP
10
11
 
11
12
  export function workspaceError(code: string): Error {return new Error(code);}
12
13
 
13
- export async function assertPrivate(path: string, directory: boolean) {
14
- const info = await lstat(path);
14
+ function assertPrivateInfo(info: Stats, directory: boolean) {
15
15
  if (!(directory ? info.isDirectory() : info.isFile()) || (info.mode & 0o077) !== 0 ||
16
16
  typeof process.getuid === 'function' && info.uid !== process.getuid() || !directory && info.nlink !== 1) throw workspaceError('WORKSPACE_STATE_INVALID');
17
17
  }
18
18
 
19
+ export async function assertPrivate(path: string, directory: boolean) {
20
+ assertPrivateInfo(await lstat(path), directory);
21
+ }
22
+
19
23
  export async function workspaceDirectory(stateDir: string) {
20
24
  const directory = join(canonicalStatePath(stateDir), 'owner-workspace');
21
25
  await mkdir(directory, {recursive: true, mode: 0o700});
@@ -24,7 +28,12 @@ export async function workspaceDirectory(stateDir: string) {
24
28
  }
25
29
 
26
30
  export async function readPrivate(path: string): Promise<unknown | null> {
27
- try {await assertPrivate(path, false); return await smallJson(path);}
31
+ try {
32
+ const info = await lstat(path);
33
+ // lstat can finish with nlink=0 during unlink. Establish that the path still
34
+ // opens before validating that snapshot; a vanished path remains ENOENT.
35
+ return await smallJson(path, () => assertPrivateInfo(info, false));
36
+ }
28
37
  catch (error) {if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null; throw workspaceError('WORKSPACE_STATE_INVALID');}
29
38
  }
30
39
 
package/src/open.ts CHANGED
@@ -73,7 +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
- export async function smallJson(file:string):Promise<unknown>{const handle=await openFile(file,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK);try{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, 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();}}
77
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;}
78
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;}}
79
80
  /** Hard byte ceiling and body deadline, including stalled or chunked responses. */
package/src/reference.ts CHANGED
@@ -28,8 +28,8 @@ export async function hashLocalVideo(input:string):Promise<{path:string;name:str
28
28
  const after=await stat(path);if(await realpath(input)!==path||before.dev!==after.dev||before.ino!==after.ino||before.size!==after.size||before.mtimeMs!==after.mtimeMs||before.ctimeMs!==after.ctimeMs)throw new Error('Reference inputs changed while hashing');
29
29
  return {path,name:basename(path),sha256:hash.digest('hex')};
30
30
  }
31
- export async function loadReferencedReview(input:string,reference?:string,handoff?:HandoffFlags,cwd?:string):Promise<ReviewPackage>{
32
- const base=await loadReview(input,{handoff,...(cwd?{cwd}:{})});if(reference===undefined)return base;
31
+ export async function loadReferencedReview(input:string,reference?:string,handoff?:HandoffFlags,cwd?:string,handoffStarts?:readonly string[]):Promise<ReviewPackage>{
32
+ const base=await loadReview(input,{handoff,...(cwd?{cwd}:{}),...(handoffStarts?{handoffStarts}:{})});if(reference===undefined)return base;
33
33
  const video=await hashLocalVideo(reference),id='open-reference-'+video.sha256;
34
34
  if(base.manifest.references.some(r=>r.id===id))throw new Error('reference: selected reference id collides with package reference');
35
35
  const binding:ReferenceBinding={packageSourceHash:base.sourceHash,reference:{id,name:video.name,sha256:video.sha256}};
@@ -39,7 +39,7 @@ export async function loadReferencedReview(input:string,reference?:string,handof
39
39
  export async function assertReviewUnchanged(p:ReviewPackage):Promise<void>{
40
40
  const assertCurrent=(p as BoundPackage)[sourceAssertion];
41
41
  if(assertCurrent)return assertCurrent();
42
- try{const current=await loadReferencedReview(p.manifestPath,selectedReference(p)?.path,p.handoffInputs,p.cwd);if(current.sourceHash!==p.sourceHash||!isDeepStrictEqual(current.reviewedSource,p.reviewedSource)||!isDeepStrictEqual(referenceBinding(current),referenceBinding(p)))throw new Error('source binding differs');}
42
+ try{const current=await loadReferencedReview(p.manifestPath,selectedReference(p)?.path,p.handoffInputs,p.cwd,p.handoffStarts);if(current.sourceHash!==p.sourceHash||!isDeepStrictEqual(current.reviewedSource,p.reviewedSource)||!isDeepStrictEqual(referenceBinding(current),referenceBinding(p)))throw new Error('source binding differs');}
43
43
  catch{throw new Error('Package inputs changed or are unavailable. Restart review to bind feedback to current inputs.');}
44
44
  }
45
45
  export async function safeSelectedReference(p:ReviewPackage):Promise<string>{
package/web/catalog-en.ts CHANGED
@@ -164,6 +164,8 @@ export const enCatalog: Readonly<Record<string, string>> = {
164
164
  "interview.delegate": "Delegate",
165
165
  "interview.open": "Open interview",
166
166
  "interview.close": "Close interview",
167
+ "interview.noteLabel": "Your note (optional)",
168
+ "interview.notePlaceholder": "Anything the choices don't cover",
167
169
  "PARTS_DIFFERENCE_PROVENANCE: declared path, lowercase SHA-256 and lanczos3-rgb-opaque required": "PARTS_DIFFERENCE_PROVENANCE: declared path, lowercase SHA-256 and lanczos3-rgb-opaque required",
168
170
  "PARTS_DIFFERENCE_PATH: literal portable inside-package path required": "PARTS_DIFFERENCE_PATH: literal portable inside-package path required",
169
171
  "PARTS_DIFFERENCE_PATH: declared painting must be readable inside the package": "PARTS_DIFFERENCE_PATH: declared painting must be readable inside the package",
@@ -230,6 +232,7 @@ export const enCatalog: Readonly<Record<string, string>> = {
230
232
  "scene.plateDimensions": "SCENE_PLATE_DIMENSIONS: {0}",
231
233
  "scene.canvasRequired": "SCENE_REQUIRED: canvas renderer required.",
232
234
  "direction.summary": "Direction{0} · {1} s · {2} · {3}",
235
+ "direction.composed": "Direction{0} · {1} s · {2}",
233
236
  "direction.loop": "loop",
234
237
  "direction.once": "once",
235
238
  "direction.fixedCamera": "fixed camera",
@@ -3527,7 +3530,7 @@ export const enCatalog: Readonly<Record<string, string>> = {
3527
3530
  "JOB_PUBLICATION_UNKNOWN": "JOB_PUBLICATION_UNKNOWN",
3528
3531
  "JOB_SNAPSHOT_RECLAIMED": "JOB_SNAPSHOT_RECLAIMED",
3529
3532
  "JOB_RECORD_INCOMPLETE": "JOB_RECORD_INCOMPLETE",
3530
- "JOB_RECORD_MOVED": "JOB_RECORD_MOVED",
3533
+ "JOB_RECORD_MOVED": "This review has been updated since you opened this page. Reload the page, or wait for the operator to reopen the review.",
3531
3534
  "JOB_REQUEST_INVALID": "JOB_REQUEST_INVALID",
3532
3535
  "JOB_API_SCHEMA_MISMATCH": "JOB_API_SCHEMA_MISMATCH",
3533
3536
  "JOB_STORED_SCHEMA_MISMATCH": "JOB_STORED_SCHEMA_MISMATCH",