@rig-c/review 1.18.0 → 2.1.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.
@@ -2,12 +2,12 @@ import { randomBytes, randomUUID } from 'node:crypto';
2
2
  import { rm } from 'node:fs/promises';
3
3
  import { isAbsolute, relative, sep } from 'node:path';
4
4
  import {
5
- JOB_ENABLED_ACT_KINDS, type JobAct, type JobAgentRequest, type JobDisplayAcknowledgment,
5
+ JOB_API_SCHEMA, JOB_ACT_SCHEMA, JOB_ENABLED_ACT_KINDS, type JobPartsEnumerator, type JobAct, type JobAgentRequest, type JobDisplayAcknowledgment,
6
6
  type JobDisplayPublication, type JobDisplayReceipt, type JobEvent, type JobFetchActRequest,
7
7
  type JobNextValue, type JobPendingAsk, type JobPublication, type JobReviewerBinding, type JobStatus,
8
8
  } from './job-contract.ts';
9
9
  import { bindJobAsk, finalizeJobAct, parseUISubmission } from './job-act.ts';
10
- import { jobHash, jobWaitLimitMs, requestDigest, sameCapability } from './job-api.ts';
10
+ import { jobHash, jobPartsEnumeratorVersion, jobWaitLimitMs, requestDigest, sameCapability } from './job-api.ts';
11
11
  import {
12
12
  assertJobRoot, assertJobSourceCurrent, captureJobRoot, prepareJobSource,
13
13
  type JobPublicationReader, type JobRetainedSource, type JobRootIdentity,
@@ -26,6 +26,8 @@ interface Replay {
26
26
  }
27
27
 
28
28
  interface JobData {
29
+ apiSchema: typeof JOB_API_SCHEMA;
30
+ actSchema: typeof JOB_ACT_SCHEMA;
29
31
  root: JobRootIdentity;
30
32
  fingerprint: string;
31
33
  reviewer: JobReviewerBinding;
@@ -50,11 +52,18 @@ export interface JobSessionOptions {
50
52
  readonly fingerprint: string;
51
53
  readonly reviewer: JobReviewerBinding;
52
54
  readonly readPublished?: JobPublicationReader;
55
+ readonly partsEnumerator?: JobPartsEnumerator;
53
56
  /** Deterministic boundary hook for disposable concurrency controls only. */
54
57
  readonly afterSnapshot?: () => void | Promise<void>;
55
58
  readonly afterDirectorySync?: (path: string) => void;
56
59
  }
57
60
 
61
+ function assertStoredSchemas(data: JobData): void {
62
+ if (data.apiSchema !== JOB_API_SCHEMA || data.actSchema !== JOB_ACT_SCHEMA) {
63
+ throw new JobError('JOB_SOURCE_UNRETAINABLE', 'JOB_STORED_SCHEMA_MISMATCH');
64
+ }
65
+ }
66
+
58
67
  function within(root: string, path: string): boolean {
59
68
  const rel = relative(root, path);
60
69
  return !rel || rel !== '..' && !rel.startsWith('..' + sep) && !isAbsolute(rel);
@@ -74,24 +83,35 @@ export class JobSession {
74
83
  const root = captureJobRoot(options.root), state = canonicalStatePath(options.stateDir);
75
84
  if (within(root.path, state)) throw new JobError('JOB_SOURCE_UNRETAINABLE', 'Job state must be outside the designated work root');
76
85
  if (!options.reviewer.id || !['owner', 'delegate'].includes(options.reviewer.role)) throw new JobError('JOB_AUTHORITY_REFUSED');
86
+ if (options.partsEnumerator) jobPartsEnumeratorVersion(options.partsEnumerator.version);
77
87
  this.store = new JobStore(state);
78
- const row = this.store.open(jobHash(JSON.stringify([root.path, options.fingerprint])), () => ({
79
- root, fingerprint: options.fingerprint, reviewer: structuredClone(options.reviewer),
80
- agentCapability: randomBytes(32).toString('hex'), uiCapability: randomBytes(32).toString('hex'),
81
- fetchCapability: randomBytes(32).toString('hex'), generation: 0, head: null,
82
- publications: {}, asks: {}, acts: {}, events: [], replays: {}, pages: {},
83
- }));
84
- this.jobId = row.jobId;
85
- assertJobRoot(row.data.root);
86
- if (requestDigest(row.data.reviewer) !== requestDigest(options.reviewer)) {
88
+ try {
89
+ const row = this.store.open(jobHash(JSON.stringify([root.path, options.fingerprint])), () => ({
90
+ apiSchema: JOB_API_SCHEMA, actSchema: JOB_ACT_SCHEMA,
91
+ root, fingerprint: options.fingerprint, reviewer: structuredClone(options.reviewer),
92
+ agentCapability: randomBytes(32).toString('hex'), uiCapability: randomBytes(32).toString('hex'),
93
+ fetchCapability: randomBytes(32).toString('hex'), generation: 0, head: null,
94
+ publications: {}, asks: {}, acts: {}, events: [], replays: {}, pages: {},
95
+ }), root.path);
96
+ this.jobId = row.jobId;
97
+ assertStoredSchemas(row.data);
98
+ assertJobRoot(row.data.root);
99
+ if (requestDigest(row.data.reviewer) !== requestDigest(options.reviewer)) {
100
+ throw new JobError('JOB_AUTHORITY_REFUSED', 'Active window reviewer binding differs');
101
+ }
102
+ } catch (error) {
87
103
  this.store.close();
88
- throw new JobError('JOB_AUTHORITY_REFUSED', 'Active window reviewer binding differs');
104
+ throw error;
89
105
  }
90
106
  }
91
107
 
92
108
  get busy(): boolean { return this.operations > 0; }
93
109
 
94
- private current(): StoredJob<JobData> { return this.store.get(this.jobId); }
110
+ private current(): StoredJob<JobData> {
111
+ const row = this.store.get(this.jobId);
112
+ assertStoredSchemas(row.data);
113
+ return row;
114
+ }
95
115
 
96
116
  /** Bootstrap delivery is private host work. Agent and owner credentials go to
97
117
  * their separate launch channels. The fetch grant is installed by Create's
@@ -188,7 +208,7 @@ export class JobSession {
188
208
  if (input.verb === 'publish') {
189
209
  candidate = await prepareJobSource({ root: current.data.root, stateRoot: this.store.root,
190
210
  fingerprint: current.data.fingerprint, request: input,
191
- readPublished: this.options.readPublished, afterSnapshot: this.options.afterSnapshot,
211
+ readPublished: this.options.readPublished, partsEnumerator: this.options.partsEnumerator, afterSnapshot: this.options.afterSnapshot,
192
212
  afterDirectorySync: this.options.afterDirectorySync });
193
213
  }
194
214
  if (signal.aborted) throw new JobError('JOB_REQUEST_INVALID', 'Request cancelled');
package/src/job-source.ts CHANGED
@@ -1,16 +1,18 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import { lstatSync, realpathSync } from 'node:fs';
3
- import { mkdir, open, rm } from 'node:fs/promises';
3
+ import { mkdir, open, rm, writeFile } from 'node:fs/promises';
4
4
  import { dirname, isAbsolute, join, posix, relative, resolve, sep } from 'node:path';
5
+ import { PNG } from 'pngjs';
6
+ import { JOB_PARTS_ENUMERATOR_RANGE } from './job-contract.ts';
5
7
  import type {
6
- JobFileIdentity, JobPartsIdentity, JobPlanIdentity, JobPublishRequest,
8
+ JobFileIdentity, JobPartsEnumerator, JobPartsFileReference, JobPartsIdentity, JobPlanIdentity, JobPublishRequest,
7
9
  JobSelector, JobSourceBinding, JobSubject,
8
10
  } from './job-contract.ts';
9
11
  import { checkedPath, readProject, readRegular, type InterviewQuestion } from './interview-project.ts';
10
12
  import { loadReview } from './manifest.ts';
11
13
  import { openKey } from './open.ts';
12
14
  import { assertReviewUnchanged } from './reference.ts';
13
- import { jobHash, jobId, jobPath, jobSha, requestDigest } from './job-api.ts';
15
+ import { jobHash, jobId, jobPartsEnumeratorVersion, jobObject, jobPath, jobSha, jobText, requestDigest } from './job-api.ts';
14
16
  import { JobError } from './job-store.ts';
15
17
 
16
18
  export interface JobRootIdentity {
@@ -119,21 +121,130 @@ function publishedIdentities(context: JobPublishedContext): JobFileIdentity[] {
119
121
  ids.add(step.id);
120
122
  jobSha(step.hash);
121
123
  }
122
- if (context.parts) {
123
- if (!/(^|\/)parts\.json$/.test(context.parts.manifest.path)) throw new JobError('JOB_SOURCE_MISMATCH');
124
- const painting = posix.join(posix.dirname(context.parts.manifest.path), 'painting_in_rig.png');
125
- if (context.parts.images.some(file =>
126
- !/(^|\/)parts\/[^/]+\.png$/.test(file.path) && file.path !== painting)) {
127
- throw new JobError('JOB_SOURCE_MISMATCH');
124
+ for (const file of files) { jobPath(file.path); jobSha(file.sha256); }
125
+ return files;
126
+ }
127
+
128
+ function referenceRow(raw: unknown, row: number, hashed: boolean): JobPartsFileReference & { sha256?: string } {
129
+ let item: Record<string, unknown>;
130
+ let role: string;
131
+ try {
132
+ item = jobObject(raw, hashed ? ['path', 'role', 'sha256'] : ['path', 'role']);
133
+ role = jobText(item.role, 128);
134
+ if (hashed) jobSha(item.sha256);
135
+ } catch { throw new JobError('JOB_SOURCE_MISMATCH', `PARTS_REFERENCE_SET_MISMATCH row=${row}`); }
136
+ let path: string;
137
+ try { path = jobPath(item.path); }
138
+ catch { throw new JobError('JOB_SOURCE_UNRETAINABLE', `PARTS_REFERENCE_PATH_REFUSED row=${row}`); }
139
+ return {path, role, ...(hashed ? {sha256: item.sha256 as string} : {})};
140
+ }
141
+
142
+ /** Membership, order and duplicate semantics belong solely to the trusted public
143
+ * enumerator. Review compares its exact array and validates byte boundaries.
144
+ */
145
+ async function prepareParts(root: string, snapshotRoot: string, claimed: JobPartsIdentity | null,
146
+ enumerator?: JobPartsEnumerator): Promise<{identity: JobPartsIdentity | null; bytes: Map<string, Buffer>}> {
147
+ const bytes = new Map<string, Buffer>();
148
+ if (claimed === null) return {identity: null, bytes};
149
+ if (!enumerator) throw new JobError('JOB_SOURCE_UNRETAINABLE', 'PARTS_ENUMERATOR_UNAVAILABLE');
150
+ jobObject(claimed, ['enumeratorVersion', 'manifest', 'images']);
151
+ const version = jobPartsEnumeratorVersion(claimed.enumeratorVersion);
152
+ if (version !== jobPartsEnumeratorVersion(enumerator.version)) {
153
+ throw new JobError('JOB_SOURCE_UNRETAINABLE',
154
+ `PARTS_ENUMERATOR_VERSION_MISMATCH range="${JOB_PARTS_ENUMERATOR_RANGE}" received="${version}" installed="${enumerator.version}"`);
155
+ }
156
+ let manifestPath: string;
157
+ try {
158
+ jobObject(claimed.manifest, ['path', 'sha256']);
159
+ manifestPath = jobPath(claimed.manifest.path);
160
+ if (posix.basename(manifestPath) !== 'parts.json') throw new Error('Manifest directory API');
161
+ jobSha(claimed.manifest.sha256);
162
+ } catch { throw new JobError('JOB_SOURCE_UNRETAINABLE', 'PARTS_REFERENCE_PATH_REFUSED manifest'); }
163
+ if (!Array.isArray(claimed.images) || claimed.images.length > maxSourceFiles) {
164
+ throw new JobError('JOB_SOURCE_UNRETAINABLE', 'PARTS_REFERENCE_LIMIT');
165
+ }
166
+ let manifestBytes: Buffer;
167
+ try { manifestBytes = sourceBytes(root, manifestPath); }
168
+ catch (error) {
169
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
170
+ throw new JobError('JOB_SOURCE_MISMATCH', 'PARTS_ENUMERATION_REFUSED rule=PARTS_FILE_PRESENT');
128
171
  }
129
- files.push(context.parts.manifest, ...context.parts.images);
130
- const paths = context.parts.images.map(file => file.path);
131
- if (new Set(paths).size !== paths.length || paths.some((path, i) => i > 0 && path < paths[i - 1])) {
132
- throw new JobError('JOB_SOURCE_MISMATCH');
172
+ throw new JobError('JOB_SOURCE_UNRETAINABLE', 'PARTS_REFERENCE_PATH_REFUSED manifest');
173
+ }
174
+ if (jobHash(manifestBytes) !== claimed.manifest.sha256) {
175
+ throw new JobError('JOB_SOURCE_MISMATCH', 'PARTS_REFERENCE_HASH_MISMATCH manifest');
176
+ }
177
+ bytes.set(manifestPath, manifestBytes);
178
+ const enumerationRoot = join(snapshotRoot, 'enumeration-' + randomUUID());
179
+ let references: readonly JobPartsFileReference[];
180
+ try {
181
+ await mkdir(enumerationRoot, {mode: 0o700});
182
+ await writeFile(join(enumerationRoot, 'parts.json'), manifestBytes, {flag: 'wx', mode: 0o600});
183
+ try { references = enumerator.enumerate(enumerationRoot); }
184
+ catch (error) {
185
+ const code = (error as {problems?: {code?: unknown}[]}).problems?.[0]?.code;
186
+ const rule = typeof code === 'string' && /^[A-Z][A-Z0-9_]{1,127}$/.test(code) ? ` rule=${code}` : '';
187
+ throw new JobError('JOB_SOURCE_MISMATCH', 'PARTS_ENUMERATION_REFUSED' + rule);
133
188
  }
189
+ } finally { await rm(enumerationRoot, {recursive: true, force: true}); }
190
+ if (!Array.isArray(references) || references.length > maxSourceFiles) {
191
+ throw new JobError('JOB_SOURCE_UNRETAINABLE', 'PARTS_REFERENCE_LIMIT');
134
192
  }
135
- for (const file of files) { jobPath(file.path); jobSha(file.sha256); }
136
- return files;
193
+ const official = references.map((raw, row) => referenceRow(raw, row, false));
194
+ const supplied = claimed.images.map((raw, row) => referenceRow(raw, row, true));
195
+ const difference = official.findIndex((row, i) => row.path !== supplied[i]?.path || row.role !== supplied[i]?.role);
196
+ if (difference !== -1 || official.length !== supplied.length) {
197
+ throw new JobError('JOB_SOURCE_MISMATCH',
198
+ `PARTS_REFERENCE_SET_MISMATCH row=${difference !== -1 ? difference : official.length}`);
199
+ }
200
+ let total = manifestBytes.length;
201
+ const decoded = new Set<string>();
202
+ const images: JobPartsIdentity['images'][number][] = [];
203
+ for (const [row, reference] of official.entries()) {
204
+ const detail = `row=${row} role=${reference.role} path=${JSON.stringify(reference.path)}`;
205
+ const path = posix.join(posix.dirname(manifestPath), reference.path);
206
+ let data = bytes.get(path);
207
+ if (!data) {
208
+ try {
209
+ if (lstatSync(checkedPath(root, path)).size > maxFileBytes) {
210
+ throw new JobError('JOB_SOURCE_UNRETAINABLE', `PARTS_REFERENCE_LIMIT ${detail}`);
211
+ }
212
+ data = sourceBytes(root, path);
213
+ }
214
+ catch (error) {
215
+ if (error instanceof JobError && error.message.startsWith('PARTS_REFERENCE_LIMIT ')) throw error;
216
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
217
+ throw new JobError('JOB_SOURCE_MISMATCH', `PARTS_REFERENCE_MISSING ${detail}`);
218
+ }
219
+ throw new JobError('JOB_SOURCE_UNRETAINABLE', `PARTS_REFERENCE_PATH_REFUSED ${detail}`);
220
+ }
221
+ total += data.length;
222
+ if (bytes.size >= maxSourceFiles || total > maxSourceBytes) {
223
+ throw new JobError('JOB_SOURCE_UNRETAINABLE', `PARTS_REFERENCE_LIMIT ${detail}`);
224
+ }
225
+ }
226
+ if (!decoded.has(path)) {
227
+ if (data.length < 33 || !data.subarray(0, 8).equals(Buffer.from('89504e470d0a1a0a', 'hex')) ||
228
+ data.readUInt32BE(8) !== 13 || data.toString('ascii', 12, 16) !== 'IHDR') {
229
+ throw new JobError('JOB_SOURCE_MISMATCH', `PARTS_REFERENCE_PNG_INVALID ${detail}`);
230
+ }
231
+ const width = data.readUInt32BE(16), height = data.readUInt32BE(20);
232
+ if (!width || !height) throw new JobError('JOB_SOURCE_MISMATCH', `PARTS_REFERENCE_PNG_INVALID ${detail}`);
233
+ if (width > Math.floor(maxFileBytes / 4 / height)) {
234
+ throw new JobError('JOB_SOURCE_UNRETAINABLE', `PARTS_REFERENCE_LIMIT ${detail}`);
235
+ }
236
+ try { PNG.sync.read(data); }
237
+ catch { throw new JobError('JOB_SOURCE_MISMATCH', `PARTS_REFERENCE_PNG_INVALID ${detail}`); }
238
+ bytes.set(path, data);
239
+ decoded.add(path);
240
+ }
241
+ const sha256 = jobHash(data);
242
+ if (sha256 !== supplied[row].sha256) {
243
+ throw new JobError('JOB_SOURCE_MISMATCH', `PARTS_REFERENCE_HASH_MISMATCH ${detail}`);
244
+ }
245
+ images.push({path: reference.path, role: reference.role, sha256});
246
+ }
247
+ return {identity: {enumeratorVersion: version, manifest: {path: manifestPath, sha256: jobHash(manifestBytes)}, images}, bytes};
137
248
  }
138
249
 
139
250
  function collectQuestionFiles(root: string, questions: readonly InterviewQuestion[]): JobFileIdentity[] {
@@ -160,6 +271,7 @@ export async function prepareJobSource(options: {
160
271
  readonly fingerprint: string;
161
272
  readonly request: JobPublishRequest;
162
273
  readonly readPublished?: JobPublicationReader;
274
+ readonly partsEnumerator?: JobPartsEnumerator;
163
275
  readonly afterSnapshot?: () => void | Promise<void>;
164
276
  readonly afterDirectorySync?: (path: string) => void;
165
277
  }): Promise<JobRetainedSource> {
@@ -218,10 +330,13 @@ export async function prepareJobSource(options: {
218
330
  const seals: JobFileIdentity[] = [];
219
331
  try {
220
332
  await mkdir(snapshotRoot, { recursive: true, mode: 0o700 });
333
+ const parts = await prepareParts(root.path, snapshotRoot, context.parts, options.partsEnumerator);
334
+ for (const [path, bytes] of parts.bytes) add(path, jobHash(bytes));
335
+ if (wanted.size > maxSourceFiles) throw new JobError('JOB_SOURCE_UNRETAINABLE', 'PARTS_REFERENCE_LIMIT');
221
336
  let size = 0;
222
337
  const directories = new Set([snapshotRoot, dirname(snapshotRoot), options.stateRoot]);
223
338
  for (const [path, expected] of [...wanted].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)) {
224
- const bytes = sourceBytes(root.path, path), sha256 = jobHash(bytes);
339
+ const bytes = parts.bytes.get(path) ?? sourceBytes(root.path, path), sha256 = jobHash(bytes);
225
340
  size += bytes.length;
226
341
  if (size > maxSourceBytes) throw new JobError('JOB_SOURCE_UNRETAINABLE');
227
342
  if (expected && sha256 !== expected) throw new JobError(path === record?.path ? 'JOB_RECORD_MOVED' : 'JOB_SOURCE_MISMATCH');
@@ -253,15 +368,15 @@ export async function prepareJobSource(options: {
253
368
  });
254
369
  const source: JobSourceBinding = {
255
370
  sourceHash: project || context.plan || context.parts ? jobHash(JSON.stringify({
256
- schema: 'rig-review-job-source/1', packageSourceHash: review.sourceHash,
257
- record, selector: context.selector, plan: context.plan, parts: context.parts, files: seals,
371
+ schema: 'rig-review-job-source/2', packageSourceHash: review.sourceHash,
372
+ record, selector: context.selector, plan: context.plan, parts: parts.identity, files: seals,
258
373
  })) : review.sourceHash,
259
374
  projectHash: project?.hash ?? null,
260
375
  package: { id: review.manifest.id, revision: review.manifest.revision },
261
376
  selector: context.selector,
262
377
  model: originalIdentity(review.reviewedSource.rig),
263
378
  direction: originalIdentity(review.direction?.file ?? null),
264
- optionSet: null, appliedResult: null, plan: context.plan, parts: context.parts,
379
+ optionSet: null, appliedResult: null, plan: context.plan, parts: parts.identity,
265
380
  };
266
381
  const boundReview = { ...review, sourceHash: source.sourceHash };
267
382
  const prepared: JobRetainedSource = {
package/src/job-store.ts CHANGED
@@ -2,7 +2,7 @@ import { Database } from 'bun:sqlite';
2
2
  import { randomUUID } from 'node:crypto';
3
3
  import { chmodSync, lstatSync, mkdirSync, realpathSync } from 'node:fs';
4
4
  import { join } from 'node:path';
5
- import type { JobErrorCode } from './job-contract.ts';
5
+ import { JOB_API_SCHEMA, JOB_ACT_SCHEMA, type JobErrorCode } from './job-contract.ts';
6
6
 
7
7
  export class JobError extends Error {
8
8
  constructor(readonly code: JobErrorCode, message: string = code) {
@@ -100,7 +100,9 @@ export class JobStore<Data> {
100
100
  active INTEGER NOT NULL CHECK(active IN (0,1)),
101
101
  document TEXT NOT NULL
102
102
  );
103
- CREATE UNIQUE INDEX IF NOT EXISTS jobs_active_root ON jobs(root_key) WHERE active=1;`);
103
+ CREATE UNIQUE INDEX IF NOT EXISTS jobs_active_root ON jobs(root_key) WHERE active=1;
104
+ CREATE INDEX IF NOT EXISTS jobs_active_canonical_root
105
+ ON jobs(json_extract(document, '$.root.path')) WHERE active=1;`);
104
106
  } catch {
105
107
  throw new JobError('JOB_STORAGE_FAILED', 'Private job storage could not be opened');
106
108
  }
@@ -123,8 +125,24 @@ export class JobStore<Data> {
123
125
  return decode<Data>(row);
124
126
  }
125
127
 
126
- open(rootKey: string, initialize: (jobId: string) => Data): StoredJob<Data> {
128
+ open(rootKey: string, initialize: (jobId: string) => Data, canonicalRoot?: string): StoredJob<Data> {
127
129
  return this.transaction(() => {
130
+ if (canonicalRoot !== undefined) {
131
+ // Inspect only bounded scalar details. The guard and allocation share
132
+ // this IMMEDIATE transaction, including across different fingerprints.
133
+ const incompatible = this.db.query<{api_schema: string; act_schema: string}, [string, string, string]>(`
134
+ SELECT substr(json_quote(json_extract(document, '$.apiSchema')), 1, 160) AS api_schema,
135
+ substr(json_quote(json_extract(document, '$.actSchema')), 1, 160) AS act_schema
136
+ FROM jobs
137
+ WHERE active=1 AND json_extract(document, '$.root.path')=?
138
+ AND (json_extract(document, '$.apiSchema') IS NOT ? OR json_extract(document, '$.actSchema') IS NOT ?)
139
+ LIMIT 1
140
+ `).get(canonicalRoot, JOB_API_SCHEMA, JOB_ACT_SCHEMA);
141
+ if (incompatible) {
142
+ throw new JobError('JOB_SOURCE_UNRETAINABLE',
143
+ `JOB_STORED_SCHEMA_MISMATCH root=${JSON.stringify(canonicalRoot)} storedApi=${incompatible.api_schema} storedAct=${incompatible.act_schema} currentApi=${JSON.stringify(JOB_API_SCHEMA)} currentAct=${JSON.stringify(JOB_ACT_SCHEMA)}. Close the old job with the matching older installation.`);
144
+ }
145
+ }
128
146
  const current = this.db.query<JobRow, [string]>(
129
147
  'SELECT * FROM jobs WHERE root_key=? AND active=1',
130
148
  ).get(rootKey);
@@ -0,0 +1,60 @@
1
+ import type {OpenInputs} from './open.ts';
2
+
3
+ export const WORKSPACE_SCHEMA = 'rig-review-open-workspace/1';
4
+ export const WORKSPACE_TARGETS_SCHEMA = 'rig-review-open-targets/1';
5
+ export const WORKSPACE_VISIBILITY_SCHEMA = 'rig-review-workspace-visibility/1';
6
+ export const WORKSPACE_READY_SCHEMA = 'rig-review-workspace-ready/1';
7
+ export const WORKSPACE_TARGET_DOMAIN = 'rig-review-target/1';
8
+ export const WORKSPACE_TARGET_LIMIT = 32;
9
+ export const WORKSPACE_SOCKET_LIMIT = 64;
10
+ export const WORKSPACE_BODY_LIMIT = 64 * 1024;
11
+ export const WORKSPACE_REGISTRATION_QUEUE = 8;
12
+
13
+ export interface WorkspaceDesignation {
14
+ key: string;
15
+ contentHash: string;
16
+ inputs: OpenInputs;
17
+ cwd: string;
18
+ viewOnly: boolean;
19
+ }
20
+
21
+ export interface WorkspaceRecord {
22
+ schema: typeof WORKSPACE_SCHEMA;
23
+ incarnation: string;
24
+ pid: number;
25
+ uid: number;
26
+ origin: string;
27
+ installation: string;
28
+ fingerprint: string;
29
+ runtime: string;
30
+ registrationCapability: string;
31
+ ownerCapability: string;
32
+ }
33
+
34
+ export interface WorkspaceStoredTarget {
35
+ designation: WorkspaceDesignation;
36
+ controlToken?: string;
37
+ }
38
+
39
+ export interface WorkspaceRegistry {
40
+ schema: typeof WORKSPACE_TARGETS_SCHEMA;
41
+ incarnation: string;
42
+ targets: WorkspaceStoredTarget[];
43
+ }
44
+
45
+ export interface WorkspaceTargetView {
46
+ key: string;
47
+ contentHash: string;
48
+ title: string;
49
+ mode: 'single' | 'compare';
50
+ animation: string | null;
51
+ viewOnly: boolean;
52
+ unavailable: string | null;
53
+ entry: string;
54
+ }
55
+
56
+ export interface WorkspaceList {
57
+ schema: typeof WORKSPACE_SCHEMA;
58
+ incarnation: string;
59
+ targets: WorkspaceTargetView[];
60
+ }
@@ -0,0 +1,103 @@
1
+ import {spawn} from 'node:child_process';
2
+ import {randomUUID} from 'node:crypto';
3
+ import {open, readFile, unlink} from 'node:fs/promises';
4
+ import {join} from 'node:path';
5
+ import {appRoot} from './build.ts';
6
+ import {frontPort} from './front.ts';
7
+ import {acquireClaim, defaultStateDir, openFingerprint, prepareOpenTarget, readOpenStatus, releaseClaim,
8
+ type OpenInputs, type OpenOptions} from './open.ts';
9
+ import {canonicalStatePath} from './state-dir.ts';
10
+ import {assertPrivate, parseRegistry, probeWorkspace, readPrivate, targetCapability, workspaceDirectory, workspaceError, writePrivate} from './open-workspace-state.ts';
11
+ import {WORKSPACE_BODY_LIMIT, WORKSPACE_SCHEMA, type WorkspaceDesignation, type WorkspaceRecord} from './open-workspace-contract.ts';
12
+
13
+ async function register(record: WorkspaceRecord, targets: WorkspaceDesignation[]) {
14
+ const text = JSON.stringify({schema: WORKSPACE_SCHEMA, incarnation: record.incarnation, targets});
15
+ if (Buffer.byteLength(text) > WORKSPACE_BODY_LIMIT) throw workspaceError('WORKSPACE_BODY_LIMIT');
16
+ const response = await fetch(record.origin + '/workspace/api/register', {
17
+ method: 'POST', redirect: 'error', signal: AbortSignal.timeout(20_000),
18
+ headers: {'Content-Type': 'application/json', Authorization: 'Bearer ' + record.registrationCapability}, body: text,
19
+ });
20
+ const value = await readOpenStatus(response, 20_000) as {error?: string; schema?: string; incarnation?: string};
21
+ if (!response.ok) throw workspaceError(value.error?.startsWith('WORKSPACE_') ? value.error : 'WORKSPACE_REGISTRATION_REFUSED');
22
+ if (value.schema !== WORKSPACE_SCHEMA || value.incarnation !== record.incarnation) throw workspaceError('WORKSPACE_HOST_MISMATCH');
23
+ }
24
+
25
+ /** Launchers exchange designated package data, never callbacks or human acts. */
26
+ export async function openWorkspace(inputs: readonly OpenInputs[], options: OpenOptions = {}) {
27
+ const fingerprint = await openFingerprint();
28
+ const prepared = [];
29
+ for (const input of inputs) prepared.push(await prepareOpenTarget(input, options, fingerprint));
30
+ if (!prepared.length || inputs.some(input => input.direct)) throw workspaceError('WORKSPACE_REQUEST_INVALID');
31
+ const stateDir = canonicalStatePath(options.stateDir ?? defaultStateDir());
32
+ const designations: WorkspaceDesignation[] = prepared.map(target => ({key: target.key,
33
+ contentHash: target.package.contentHash, cwd: target.cwd, viewOnly: target.viewOnly,
34
+ inputs: {...target.package.inputs, viewOnly: target.viewOnly}}));
35
+ if (Buffer.byteLength(JSON.stringify(designations)) > WORKSPACE_BODY_LIMIT - 256) throw workspaceError('WORKSPACE_BODY_LIMIT');
36
+ const directory = await workspaceDirectory(stateDir), port = frontPort(options.frontPort);
37
+ const nonce = randomUUID();
38
+ const reuse = () => probeWorkspace(directory, fingerprint, port);
39
+ const ready = await reuse();
40
+ const acquired = ready ? {row: ready} : await acquireClaim(directory, 'host', nonce, reuse,
41
+ performance.now() + 20_000, 'WORKSPACE_START_BUSY');
42
+ let child: ReturnType<typeof spawn> | undefined, handedOff = false, request: string | undefined;
43
+ try {
44
+ let record: WorkspaceRecord;
45
+ const reused = 'row' in acquired;
46
+ if ('row' in acquired) record = acquired.row;
47
+ else {
48
+ request = join(directory, nonce + '.request.json');
49
+ await writePrivate(request, {schema: WORKSPACE_SCHEMA, stateDir, fingerprint, port,
50
+ ...(options.idleMs !== undefined ? {idleMs: options.idleMs} : {}),
51
+ ...(options.graceMs !== undefined ? {graceMs: options.graceMs} : {})});
52
+ const logPath = join(directory, nonce + '.log');
53
+ const log = await open(logPath, 'a', 0o600);
54
+ try {
55
+ child = spawn(process.execPath, [join(appRoot, 'src/open-workspace-worker.ts'), request],
56
+ {cwd: directory, detached: true, stdio: ['ignore', log.fd, log.fd], env: process.env});
57
+ child.unref();
58
+ } finally {await log.close();}
59
+ let failure = false;
60
+ child.on('error', () => {failure = true;});
61
+ child.on('exit', () => {failure = true;});
62
+ const deadline = performance.now() + 20_000;
63
+ for (;;) {
64
+ const current = await reuse();
65
+ if (current) {record = current; break;}
66
+ if (failure) {
67
+ const diagnostic = (await readFile(logPath, 'utf8')).trim();
68
+ const occupied = `FRONT_PORT_BUSY: 127.0.0.1:${port} is held by another listener; use --direct (or set RIG_REVIEW_FRONT_PORT)`;
69
+ const safeCodes = ['WORKSPACE_REQUEST_INVALID', 'WORKSPACE_STATE_INVALID', 'WORKSPACE_BODY_LIMIT', 'WORKSPACE_START_REFUSED'];
70
+ throw workspaceError(diagnostic === occupied || safeCodes.includes(diagnostic) ? diagnostic : 'WORKSPACE_START_REFUSED');
71
+ }
72
+ if (performance.now() >= deadline) throw workspaceError('WORKSPACE_START_TIMEOUT');
73
+ await Bun.sleep(30);
74
+ }
75
+ }
76
+ await register(record, designations);
77
+ handedOff = true;
78
+ return {url: record.origin + '/?workspace=' + record.incarnation + '#cap=' + record.ownerCapability, reused, prepared};
79
+ } finally {
80
+ if (child && !handedOff && child.exitCode === null && child.signalCode === null) child.kill('SIGTERM');
81
+ if ('claim' in acquired) await releaseClaim(acquired.claim, nonce);
82
+ if (request) await unlink(request).catch(error => {if (error.code !== 'ENOENT') throw error;});
83
+ }
84
+ }
85
+
86
+ /** Trusted control CLI resolves only its exact opted-in target after authenticating the live workspace. */
87
+ export async function workspaceControlLocator(stateDir: string, key: string) {
88
+ const directory = join(canonicalStatePath(stateDir), 'owner-workspace');
89
+ try {await assertPrivate(directory, true);}
90
+ catch (error) {if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null; throw error;}
91
+ const value = await readPrivate(join(directory, 'host.json'));
92
+ if (!value) return null;
93
+ const record = await probeWorkspace(directory, await openFingerprint());
94
+ if (!record) return null;
95
+ const registry = await readPrivate(join(directory, 'targets.json'));
96
+ if (!registry) throw workspaceError('WORKSPACE_STATE_INVALID');
97
+ const stored = parseRegistry(registry);
98
+ if (stored.incarnation !== record.incarnation) throw workspaceError('WORKSPACE_HOST_MISMATCH');
99
+ const target = stored.targets.find(target => target.designation.key === key);
100
+ if (!target?.controlToken) return null;
101
+ return {origin: record.origin, prefix: '/instances/' + key, controlToken: target.controlToken,
102
+ capability: targetCapability(record.ownerCapability, record.incarnation, key)};
103
+ }
@@ -0,0 +1,125 @@
1
+ import {createHmac, randomUUID} from 'node:crypto';
2
+ import {lstat, mkdir, rename, unlink, writeFile} from 'node:fs/promises';
3
+ import {isAbsolute, join} from 'node:path';
4
+ import {appRoot} from './build.ts';
5
+ import {readOpenStatus, running, smallJson} from './open.ts';
6
+ import {canonicalStatePath} from './state-dir.ts';
7
+ import {capabilityPattern} from './open-protocol.ts';
8
+ import {WORKSPACE_BODY_LIMIT, WORKSPACE_SCHEMA, WORKSPACE_TARGETS_SCHEMA, WORKSPACE_TARGET_DOMAIN, WORKSPACE_TARGET_LIMIT,
9
+ type WorkspaceDesignation, type WorkspaceRecord, type WorkspaceRegistry} from './open-workspace-contract.ts';
10
+
11
+ export function workspaceError(code: string): Error {return new Error(code);}
12
+
13
+ export async function assertPrivate(path: string, directory: boolean) {
14
+ const info = await lstat(path);
15
+ if (!(directory ? info.isDirectory() : info.isFile()) || (info.mode & 0o077) !== 0 ||
16
+ typeof process.getuid === 'function' && info.uid !== process.getuid() || !directory && info.nlink !== 1) throw workspaceError('WORKSPACE_STATE_INVALID');
17
+ }
18
+
19
+ export async function workspaceDirectory(stateDir: string) {
20
+ const directory = join(canonicalStatePath(stateDir), 'owner-workspace');
21
+ await mkdir(directory, {recursive: true, mode: 0o700});
22
+ await assertPrivate(directory, true);
23
+ return directory;
24
+ }
25
+
26
+ export async function readPrivate(path: string): Promise<unknown | null> {
27
+ try {await assertPrivate(path, false); return await smallJson(path);}
28
+ catch (error) {if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null; throw workspaceError('WORKSPACE_STATE_INVALID');}
29
+ }
30
+
31
+ export async function writePrivate(path: string, value: unknown) {
32
+ const text = JSON.stringify(value);
33
+ if (Buffer.byteLength(text) > WORKSPACE_BODY_LIMIT) throw workspaceError('WORKSPACE_BODY_LIMIT');
34
+ await readPrivate(path);
35
+ const temporary = path + '.' + randomUUID() + '.tmp';
36
+ try {
37
+ await writeFile(temporary, text, {flag: 'wx', mode: 0o600});
38
+ await rename(temporary, path);
39
+ } finally {await unlink(temporary).catch(error => {if (error.code !== 'ENOENT') throw error;});}
40
+ }
41
+
42
+ export function targetCapability(ownerCapability: string, incarnation: string, key: string) {
43
+ return createHmac('sha256', ownerCapability).update(WORKSPACE_TARGET_DOMAIN + '\0' + incarnation + '\0' + key).digest('hex');
44
+ }
45
+
46
+ function object(value: unknown): Record<string, unknown> {
47
+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw workspaceError('WORKSPACE_REQUEST_INVALID');
48
+ return value as Record<string, unknown>;
49
+ }
50
+
51
+ export function parseDesignation(value: unknown): WorkspaceDesignation {
52
+ const row = object(value), inputs = object(row.inputs);
53
+ if (Object.keys(row).some(key => !['key', 'contentHash', 'inputs', 'cwd', 'viewOnly'].includes(key)) ||
54
+ !capabilityPattern.test(String(row.key)) || !capabilityPattern.test(String(row.contentHash)) ||
55
+ typeof row.cwd !== 'string' || row.cwd.length > 4096 || !isAbsolute(row.cwd) || typeof row.viewOnly !== 'boolean') {
56
+ throw workspaceError('WORKSPACE_REQUEST_INVALID');
57
+ }
58
+ const strings = ['input', 'compare', 'reference', 'animation', 'config', 'parts', 'source', 'full', 'head', 'keypoints'];
59
+ for (const [key, item] of Object.entries(inputs)) {
60
+ if (strings.includes(key)) {
61
+ if (typeof item !== 'string' || !item || item.length > 4096) throw workspaceError('WORKSPACE_REQUEST_INVALID');
62
+ } else if (key === 'control' || key === 'viewOnly') {
63
+ if (typeof item !== 'boolean') throw workspaceError('WORKSPACE_REQUEST_INVALID');
64
+ } else if (key === 'project') {
65
+ const project = object(item);
66
+ for (const [field, entry] of Object.entries(project)) {
67
+ if (['root', 'picksDir', 'draftId', 'partsVerdictDir'].includes(field)) {
68
+ if (typeof entry !== 'string' || !entry || entry.length > 4096) throw workspaceError('WORKSPACE_REQUEST_INVALID');
69
+ } else if (field === 'version' || field === 'postVersion') {
70
+ if (!Number.isSafeInteger(entry) || Number(entry) < 1) throw workspaceError('WORKSPACE_REQUEST_INVALID');
71
+ } else throw workspaceError('WORKSPACE_REQUEST_INVALID');
72
+ }
73
+ if (typeof project.root !== 'string' || typeof project.picksDir !== 'string') throw workspaceError('WORKSPACE_REQUEST_INVALID');
74
+ } else throw workspaceError('WORKSPACE_REQUEST_INVALID');
75
+ }
76
+ if (typeof inputs.input !== 'string' || !isAbsolute(inputs.input)) throw workspaceError('WORKSPACE_REQUEST_INVALID');
77
+ return row as unknown as WorkspaceDesignation;
78
+ }
79
+
80
+ export function parseRegistry(value: unknown): WorkspaceRegistry {
81
+ const row = object(value);
82
+ if (row.schema !== WORKSPACE_TARGETS_SCHEMA || typeof row.incarnation !== 'string' || !Array.isArray(row.targets) ||
83
+ row.targets.length > WORKSPACE_TARGET_LIMIT) throw workspaceError('WORKSPACE_STATE_INVALID');
84
+ const seen = new Set<string>();
85
+ for (const entry of row.targets) {
86
+ const target = object(entry), designation = parseDesignation(target.designation);
87
+ if (seen.has(designation.key) || target.controlToken !== undefined &&
88
+ (typeof target.controlToken !== 'string' || !/^[a-f0-9-]{36}$/.test(target.controlToken))) throw workspaceError('WORKSPACE_STATE_INVALID');
89
+ seen.add(designation.key);
90
+ }
91
+ return row as unknown as WorkspaceRegistry;
92
+ }
93
+
94
+ export function parseWorkspaceRecord(value: unknown): WorkspaceRecord {
95
+ const row = object(value);
96
+ let origin: URL;
97
+ try {origin = new URL(String(row.origin));} catch {throw workspaceError('WORKSPACE_STATE_INVALID');}
98
+ if (row.schema !== WORKSPACE_SCHEMA || !/^[a-f0-9-]{36}$/.test(String(row.incarnation)) ||
99
+ !Number.isSafeInteger(row.pid) || Number(row.pid) < 1 || !Number.isSafeInteger(row.uid) ||
100
+ typeof row.installation !== 'string' || !isAbsolute(row.installation) || typeof row.runtime !== 'string' ||
101
+ !capabilityPattern.test(String(row.fingerprint)) || !capabilityPattern.test(String(row.registrationCapability)) ||
102
+ !capabilityPattern.test(String(row.ownerCapability)) || origin.origin !== row.origin ||
103
+ origin.protocol !== 'http:' || origin.hostname !== '127.0.0.1' || !origin.port) throw workspaceError('WORKSPACE_STATE_INVALID');
104
+ return row as unknown as WorkspaceRecord;
105
+ }
106
+
107
+ /** A live but silent PID remains owned. A timeout never authorizes replacement. */
108
+ export async function probeWorkspace(directory: string, fingerprint: string, port?: number): Promise<WorkspaceRecord | null> {
109
+ await assertPrivate(directory, true);
110
+ const value = await readPrivate(join(directory, 'host.json'));
111
+ if (value === null) return null;
112
+ const record = parseWorkspaceRecord(value);
113
+ if (record.uid !== (process.getuid?.() ?? 0)) throw workspaceError('WORKSPACE_OWNER_MISMATCH');
114
+ if (!running(record.pid)) return null;
115
+ if (record.fingerprint !== fingerprint || record.installation !== appRoot || record.runtime !== Bun.version ||
116
+ port !== undefined && new URL(record.origin).port !== String(port)) throw workspaceError('WORKSPACE_HOST_MISMATCH');
117
+ const response = await fetch(record.origin + '/workspace/api/status', {
118
+ headers: {Authorization: 'Bearer ' + record.registrationCapability}, redirect: 'error', signal: AbortSignal.timeout(1500),
119
+ }).catch(() => null);
120
+ if (!response?.ok) {void response?.body?.cancel(); throw workspaceError('WORKSPACE_HOST_UNRESPONSIVE');}
121
+ const status = object(await readOpenStatus(response));
122
+ if (status.schema !== WORKSPACE_SCHEMA || status.incarnation !== record.incarnation || status.pid !== record.pid ||
123
+ status.fingerprint !== fingerprint || status.runtime !== record.runtime) throw workspaceError('WORKSPACE_HOST_MISMATCH');
124
+ return record;
125
+ }