@rig-c/review 1.16.6 → 1.17.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.
@@ -0,0 +1,352 @@
1
+ import { randomBytes, randomUUID } from 'node:crypto';
2
+ import { rm } from 'node:fs/promises';
3
+ import { isAbsolute, relative, sep } from 'node:path';
4
+ import {
5
+ JOB_ENABLED_ACT_KINDS, type JobAct, type JobAgentRequest, type JobDisplayAcknowledgment,
6
+ type JobDisplayPublication, type JobDisplayReceipt, type JobEvent, type JobFetchActRequest,
7
+ type JobNextValue, type JobPendingAsk, type JobPublication, type JobReviewerBinding, type JobStatus,
8
+ } from './job-contract.ts';
9
+ import { bindJobAsk, finalizeJobAct, parseUISubmission } from './job-act.ts';
10
+ import { jobHash, jobWaitLimitMs, requestDigest, sameCapability } from './job-api.ts';
11
+ import {
12
+ assertJobRoot, assertJobSourceCurrent, captureJobRoot, prepareJobSource,
13
+ type JobPublicationReader, type JobRetainedSource, type JobRootIdentity,
14
+ } from './job-source.ts';
15
+ import { JobError, JobStore, type StoredJob } from './job-store.ts';
16
+ import { canonicalStatePath } from './state-dir.ts';
17
+
18
+ interface StoredPublication {
19
+ publication: JobPublication;
20
+ retained: JobRetainedSource;
21
+ }
22
+
23
+ interface Replay {
24
+ digest: string;
25
+ value: unknown;
26
+ }
27
+
28
+ interface JobData {
29
+ root: JobRootIdentity;
30
+ fingerprint: string;
31
+ reviewer: JobReviewerBinding;
32
+ agentCapability: string;
33
+ uiCapability: string;
34
+ fetchCapability: string | null;
35
+ generation: number;
36
+ head: string | null;
37
+ publications: Record<string, StoredPublication>;
38
+ asks: Record<string, JobPendingAsk>;
39
+ acts: Record<string, JobAct>;
40
+ events: JobEvent[];
41
+ replays: Record<string, Replay>;
42
+ pages: Record<string, JobDisplayReceipt>;
43
+ }
44
+
45
+ const maximumEventBytes = 512 * 1024;
46
+
47
+ export interface JobSessionOptions {
48
+ readonly root: string;
49
+ readonly stateDir: string;
50
+ readonly fingerprint: string;
51
+ readonly reviewer: JobReviewerBinding;
52
+ readonly readPublished?: JobPublicationReader;
53
+ /** Deterministic boundary hook for disposable concurrency controls only. */
54
+ readonly afterSnapshot?: () => void | Promise<void>;
55
+ readonly afterDirectorySync?: (path: string) => void;
56
+ }
57
+
58
+ function within(root: string, path: string): boolean {
59
+ const rel = relative(root, path);
60
+ return !rel || rel !== '..' && !rel.startsWith('..' + sep) && !isAbsolute(rel);
61
+ }
62
+
63
+ /** Trusted daemon service. Only createJobHostPorts exposes network operations.
64
+ * Source paths and credentials returned by the trusted host helpers below must
65
+ * never enter an agent response. Create #184 installs its own private binding.
66
+ */
67
+ export class JobSession {
68
+ readonly jobId: string;
69
+ private readonly store: JobStore<JobData>;
70
+ private readonly listeners = new Set<() => void>();
71
+ private operations = 0;
72
+
73
+ constructor(private readonly options: JobSessionOptions) {
74
+ const root = captureJobRoot(options.root), state = canonicalStatePath(options.stateDir);
75
+ if (within(root.path, state)) throw new JobError('JOB_SOURCE_UNRETAINABLE', 'Job state must be outside the designated work root');
76
+ if (!options.reviewer.id || !['owner', 'delegate'].includes(options.reviewer.role)) throw new JobError('JOB_AUTHORITY_REFUSED');
77
+ 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)) {
87
+ this.store.close();
88
+ throw new JobError('JOB_AUTHORITY_REFUSED', 'Active window reviewer binding differs');
89
+ }
90
+ }
91
+
92
+ get busy(): boolean { return this.operations > 0; }
93
+
94
+ private current(): StoredJob<JobData> { return this.store.get(this.jobId); }
95
+
96
+ /** Bootstrap delivery is private host work. Agent and owner credentials go to
97
+ * their separate launch channels. The fetch grant is installed by Create's
98
+ * writer-owned sibling adapter, never printed by the semantic CLI.
99
+ */
100
+ hostCredentials(): { agent: string; ui: string } {
101
+ const { agentCapability, uiCapability } = this.current().data;
102
+ return { agent: agentCapability, ui: uiCapability };
103
+ }
104
+
105
+ writerGrant(): { jobId: string; fetchCapability: string } {
106
+ const current = this.current();
107
+ if (!current.active || !current.data.fetchCapability) throw new JobError('JOB_CLOSED');
108
+ return { jobId: this.jobId, fetchCapability: current.data.fetchCapability };
109
+ }
110
+
111
+ authorize(role: 'agent' | 'ui' | 'consumer', given: string | null): void {
112
+ const current = this.current();
113
+ if (role === 'consumer' && !current.active) throw new JobError('JOB_CLOSED');
114
+ const secret = role === 'agent' ? current.data.agentCapability : role === 'ui' ? current.data.uiCapability : current.data.fetchCapability;
115
+ if (!secret || !sameCapability(given, role === 'ui' ? secret : 'Bearer ' + secret)) {
116
+ throw new JobError('JOB_CAPABILITY_REQUIRED');
117
+ }
118
+ if (role === 'ui' && !current.active) throw new JobError('JOB_CLOSED');
119
+ }
120
+
121
+ status(): JobStatus {
122
+ const current = this.current(), data = current.data;
123
+ return {
124
+ jobId: this.jobId, generation: data.generation, status: current.active ? 'active' : 'closed',
125
+ publication: data.head ? data.publications[data.head].publication : null,
126
+ pending: Object.values(data.asks).filter(ask => ask.status === 'pending'),
127
+ cursor: data.events.at(-1)?.cursor ?? null,
128
+ enabledActKinds: JOB_ENABLED_ACT_KINDS,
129
+ };
130
+ }
131
+
132
+ retainedSource(publicationId: string): JobRetainedSource {
133
+ const stored = this.current().data.publications[publicationId];
134
+ if (!stored) throw new JobError('JOB_PUBLICATION_UNKNOWN');
135
+ return stored.retained;
136
+ }
137
+
138
+ displayPublication(publicationId: string): JobDisplayPublication {
139
+ const stored = this.current().data.publications[publicationId];
140
+ if (!stored) throw new JobError('JOB_PUBLICATION_UNKNOWN');
141
+ const base = `/jobs/${this.jobId}/publications/${publicationId}/instances/${stored.publication.instanceKey}/`;
142
+ return { publication: stored.publication, routes: { entry: base, apiBase: base + 'api/', assetsBase: base + 'assets/' } };
143
+ }
144
+
145
+ private replay(data: JobData, key: string, digest: string): Replay | null {
146
+ const previous = data.replays[key];
147
+ if (previous && previous.digest !== digest) throw new JobError('JOB_IDEMPOTENCY_CONFLICT');
148
+ return previous ?? null;
149
+ }
150
+
151
+ private active(current: StoredJob<JobData>, generation: number): void {
152
+ if (!current.active) throw new JobError('JOB_CLOSED');
153
+ if (current.data.generation !== generation) throw new JobError('JOB_GENERATION_STALE');
154
+ assertJobRoot(current.data.root);
155
+ }
156
+
157
+ private event(data: JobData, value: Omit<JobEvent, 'cursor' | 'jobId' | 'generation'>): void {
158
+ const event = { ...value, cursor: randomUUID(), jobId: this.jobId, generation: data.generation } as JobEvent;
159
+ if (Buffer.byteLength(JSON.stringify(event)) > maximumEventBytes) {
160
+ throw new JobError('JOB_BODY_LIMIT', 'Job event exceeds its delivery bound');
161
+ }
162
+ data.events.push(event);
163
+ }
164
+
165
+ private notify(): void { for (const listener of this.listeners) listener(); }
166
+
167
+ async execute(input: JobAgentRequest | JobFetchActRequest, signal: AbortSignal): Promise<unknown> {
168
+ if (input.jobId !== this.jobId) throw new JobError('JOB_UNKNOWN');
169
+ if (input.verb === 'next') return this.next(input.after, input.waitMs, signal);
170
+ if (input.verb === 'fetch-act') {
171
+ const current = this.current();
172
+ if (!current.active) throw new JobError('JOB_CLOSED');
173
+ const act = current.data.acts[input.actId];
174
+ if (!act) throw new JobError('JOB_ACT_UNKNOWN');
175
+ return act;
176
+ }
177
+ const { requestId: _requestId, ...semantic } = input;
178
+ const digest = requestDigest(semantic), key = 'agent:' + input.idempotencyKey;
179
+ let current = this.current();
180
+ const previous = this.replay(current.data, key, digest);
181
+ if (previous) return previous.value;
182
+ this.active(current, input.expectedGeneration);
183
+ if (signal.aborted) throw new JobError('JOB_REQUEST_INVALID', 'Request cancelled');
184
+ let candidate: JobRetainedSource | null = null;
185
+ let committed = false;
186
+ this.operations++;
187
+ try {
188
+ if (input.verb === 'publish') {
189
+ candidate = await prepareJobSource({ root: current.data.root, stateRoot: this.store.root,
190
+ fingerprint: current.data.fingerprint, request: input,
191
+ readPublished: this.options.readPublished, afterSnapshot: this.options.afterSnapshot,
192
+ afterDirectorySync: this.options.afterDirectorySync });
193
+ }
194
+ if (signal.aborted) throw new JobError('JOB_REQUEST_INVALID', 'Request cancelled');
195
+ current = this.current();
196
+ let result: unknown;
197
+ this.store.update(this.jobId, current.revision, fresh => {
198
+ const raced = this.replay(fresh.data, key, digest);
199
+ if (raced) { result = raced.value; return { data: fresh.data }; }
200
+ this.active(fresh, input.expectedGeneration);
201
+ const data = fresh.data;
202
+ data.generation++;
203
+ switch (input.verb) {
204
+ case 'publish': {
205
+ assertJobSourceCurrent(candidate!);
206
+ const publication: JobPublication = {
207
+ publicationId: randomUUID(), instanceKey: candidate!.instanceKey, generation: data.generation,
208
+ source: candidate!.source, label: candidate!.label, previousPublicationId: data.head, visual: candidate!.visual,
209
+ };
210
+ for (const ask of Object.values(data.asks)) {
211
+ if (ask.status === 'pending') data.asks[ask.askId] = { ...ask, status: 'superseded' };
212
+ }
213
+ data.publications[publication.publicationId] = { publication, retained: candidate! };
214
+ data.head = publication.publicationId;
215
+ this.event(data, { type: 'published', publication } as Omit<JobEvent, 'cursor' | 'jobId' | 'generation'>);
216
+ result = publication;
217
+ break;
218
+ }
219
+ case 'ask': {
220
+ if (data.head !== input.publicationId) throw new JobError('JOB_ACT_SOURCE_STALE');
221
+ const retained = data.publications[input.publicationId].retained;
222
+ assertJobSourceCurrent(retained);
223
+ const ask: JobPendingAsk = { askId: randomUUID(), publicationId: input.publicationId,
224
+ subject: input.subject, source: bindJobAsk(input.subject, retained), status: 'pending' };
225
+ data.asks[ask.askId] = ask;
226
+ this.event(data, { type: 'pending', ask } as Omit<JobEvent, 'cursor' | 'jobId' | 'generation'>);
227
+ result = ask;
228
+ break;
229
+ }
230
+ case 'close':
231
+ data.fetchCapability = null;
232
+ data.pages = {};
233
+ this.event(data, { type: 'closed', reason: input.reason } as Omit<JobEvent, 'cursor' | 'jobId' | 'generation'>);
234
+ result = { status: 'closed', cursor: data.events.at(-1)!.cursor };
235
+ break;
236
+ }
237
+ data.replays[key] = { digest, value: result };
238
+ return { data, active: input.verb !== 'close' };
239
+ });
240
+ committed = candidate === null || Object.values(this.current().data.publications)
241
+ .some(stored => stored.retained.snapshotRoot === candidate!.snapshotRoot);
242
+ this.notify();
243
+ return result;
244
+ } finally {
245
+ this.operations--;
246
+ if (candidate && !committed) await rm(candidate.snapshotRoot, { recursive: true, force: true });
247
+ }
248
+ }
249
+
250
+ ackDisplayed(input: JobDisplayAcknowledgment): JobDisplayReceipt {
251
+ const current = this.current();
252
+ let receipt: JobDisplayReceipt;
253
+ this.store.update(this.jobId, current.revision, fresh => {
254
+ this.active(fresh, fresh.data.generation);
255
+ const publication = fresh.data.publications[input.publicationId]?.publication;
256
+ if (fresh.data.head !== input.publicationId || publication?.source.sourceHash !== input.sourceHash) {
257
+ throw new JobError('JOB_DISPLAY_MISMATCH');
258
+ }
259
+ receipt = { publicationId: input.publicationId, pageId: input.pageId, displayedNonce: randomBytes(32).toString('hex') };
260
+ fresh.data.pages[input.pageId] = receipt;
261
+ return { data: fresh.data };
262
+ });
263
+ return receipt!;
264
+ }
265
+
266
+ async commitUIAct(raw: unknown): Promise<JobAct> {
267
+ const input = parseUISubmission(raw), digest = requestDigest(input), key = `ui:${input.pageId}:${input.submissionId}`;
268
+ const current = this.current();
269
+ const previous = this.replay(current.data, key, digest);
270
+ if (previous) return previous.value as JobAct;
271
+ let act: JobAct;
272
+ this.store.update(this.jobId, current.revision, fresh => {
273
+ // UI captures an observed generation. Unrelated asks may advance it while
274
+ // this same ask/source/publication/nonce stays valid. Agent mutation CAS
275
+ // remains global. Future UI generations cannot describe a displayed state.
276
+ this.active(fresh, fresh.data.generation);
277
+ if (input.expectedGeneration > fresh.data.generation) throw new JobError('JOB_GENERATION_STALE');
278
+ const page = fresh.data.pages[input.pageId];
279
+ if (!page || page.publicationId !== input.publicationId || !sameCapability(input.displayedNonce, page.displayedNonce)) {
280
+ throw new JobError('JOB_DISPLAY_MISMATCH');
281
+ }
282
+ if (fresh.data.head !== input.publicationId) throw new JobError('JOB_ACT_SOURCE_STALE');
283
+ const ask = fresh.data.asks[input.askId];
284
+ if (!ask) throw new JobError('JOB_ASK_INVALID');
285
+ const retained = fresh.data.publications[input.publicationId].retained;
286
+ assertJobSourceCurrent(retained);
287
+ act = finalizeJobAct({ jobId: this.jobId, submission: input, ask, retained, reviewer: fresh.data.reviewer });
288
+ fresh.data.generation++;
289
+ fresh.data.acts[act.actId] = act;
290
+ fresh.data.asks[ask.askId] = { ...ask, status: 'answered' };
291
+ fresh.data.replays[key] = { digest, value: act };
292
+ this.event(fresh.data, { type: 'act', act } as Omit<JobEvent, 'cursor' | 'jobId' | 'generation'>);
293
+ return { data: fresh.data };
294
+ });
295
+ this.notify();
296
+ return act!;
297
+ }
298
+
299
+ private events(after: string | null): JobNextValue {
300
+ const current = this.current(), events = current.data.events;
301
+ const index = after === null ? -1 : events.findIndex(event => event.cursor === after);
302
+ if (after !== null && index < 0) throw new JobError('JOB_CURSOR_INVALID');
303
+ const batch: JobEvent[] = [];
304
+ let size = 0;
305
+ for (const event of events.slice(index + 1, index + 65)) {
306
+ const bytes = Buffer.byteLength(JSON.stringify(event));
307
+ if (bytes > maximumEventBytes) throw new JobError('JOB_BODY_LIMIT', 'Stored job event exceeds its delivery bound');
308
+ if (size + bytes > maximumEventBytes) break;
309
+ size += bytes;
310
+ batch.push(event);
311
+ }
312
+ return { events: batch, cursor: batch.at(-1)?.cursor ?? after,
313
+ status: batch.length ? 'events' : current.active ? 'timeout' : 'closed' };
314
+ }
315
+
316
+ private async next(after: string | null, waitMs: number, signal: AbortSignal): Promise<JobNextValue> {
317
+ if (waitMs < 0 || waitMs > jobWaitLimitMs || !Number.isSafeInteger(waitMs)) throw new JobError('JOB_REQUEST_INVALID');
318
+ if (signal.aborted) throw new JobError('JOB_REQUEST_INVALID', 'Request cancelled');
319
+ const ready = this.events(after);
320
+ if (ready.status !== 'timeout' || !waitMs) return ready;
321
+ await new Promise<void>((resolve, reject) => {
322
+ const finish = () => { clearTimeout(timer); this.listeners.delete(finish); signal.removeEventListener('abort', abort); resolve(); };
323
+ const abort = () => { clearTimeout(timer); this.listeners.delete(finish); signal.removeEventListener('abort', abort); reject(new JobError('JOB_REQUEST_INVALID', 'Request cancelled')); };
324
+ const timer = setTimeout(finish, waitMs);
325
+ this.listeners.add(finish);
326
+ signal.addEventListener('abort', abort, { once: true });
327
+ if (signal.aborted) abort();
328
+ else if (this.events(after).status !== 'timeout') finish();
329
+ });
330
+ return this.events(after);
331
+ }
332
+
333
+ async *subscribe(input: { readonly jobId: string; readonly after: string | null; readonly signal: AbortSignal }): AsyncIterable<JobEvent> {
334
+ if (input.jobId !== this.jobId) throw new JobError('JOB_UNKNOWN');
335
+ let after = input.after;
336
+ while (!input.signal.aborted) {
337
+ let value: JobNextValue;
338
+ try { value = await this.next(after, jobWaitLimitMs, input.signal); }
339
+ catch (error) {
340
+ if (input.signal.aborted && error instanceof JobError && error.code === 'JOB_REQUEST_INVALID') return;
341
+ throw error;
342
+ }
343
+ for (const event of value.events) { after = event.cursor; yield event; }
344
+ if (value.status === 'closed') return;
345
+ }
346
+ }
347
+
348
+ dispose(): void {
349
+ this.notify();
350
+ this.store.close();
351
+ }
352
+ }
@@ -0,0 +1,291 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { lstatSync, realpathSync } from 'node:fs';
3
+ import { mkdir, open, rm } from 'node:fs/promises';
4
+ import { dirname, isAbsolute, join, posix, relative, resolve, sep } from 'node:path';
5
+ import type {
6
+ JobFileIdentity, JobPartsIdentity, JobPlanIdentity, JobPublishRequest,
7
+ JobSelector, JobSourceBinding, JobSubject,
8
+ } from './job-contract.ts';
9
+ import { checkedPath, readProject, readRegular, type InterviewQuestion } from './interview-project.ts';
10
+ import { loadReview } from './manifest.ts';
11
+ import { openKey } from './open.ts';
12
+ import { assertReviewUnchanged } from './reference.ts';
13
+ import { jobHash, jobId, jobPath, jobSha, requestDigest } from './job-api.ts';
14
+ import { JobError } from './job-store.ts';
15
+
16
+ export interface JobRootIdentity {
17
+ readonly path: string;
18
+ readonly dev: number;
19
+ readonly ino: number;
20
+ }
21
+
22
+ /** Trusted Create #184 adapter boundary. These are host return values, not new
23
+ * project record keys or an agent API payload. Until the producer publishes its
24
+ * actual read contract, no default adapter invents plan/parts bindings. Parts
25
+ * referenced-image enumeration belongs to the public Parts #1163 surface.
26
+ */
27
+ export interface JobPublishedContext {
28
+ readonly selector: JobSelector | null;
29
+ readonly plan: JobPlanIdentity | null;
30
+ readonly parts: JobPartsIdentity | null;
31
+ readonly subjects: readonly JobSubject[];
32
+ readonly partIds: readonly string[];
33
+ readonly files: readonly JobFileIdentity[];
34
+ }
35
+
36
+ export type JobPublicationReader = (input: {
37
+ readonly root: string;
38
+ readonly record: JobFileIdentity;
39
+ readonly result: JobPublishRequest['result'];
40
+ }) => Promise<JobPublishedContext>;
41
+
42
+ export interface JobRetainedSource {
43
+ readonly root: JobRootIdentity;
44
+ readonly record: JobFileIdentity | null;
45
+ readonly seals: readonly JobFileIdentity[];
46
+ readonly snapshotRoot: string;
47
+ readonly manifestPath: string;
48
+ readonly source: JobSourceBinding;
49
+ readonly instanceKey: string;
50
+ readonly label: string;
51
+ readonly visual: { readonly status: 'available' } | { readonly status: 'unavailable'; readonly code: string };
52
+ readonly subjects: readonly JobSubject[];
53
+ readonly questions: readonly InterviewQuestion[];
54
+ readonly partIds: readonly string[];
55
+ }
56
+
57
+ const maxSourceBytes = 256 * 1024 * 1024;
58
+ const maxSourceFiles = 4096;
59
+ const maxFileBytes = 64 * 1024 * 1024;
60
+
61
+ export function captureJobRoot(path: string): JobRootIdentity {
62
+ try {
63
+ const canonical = realpathSync(path), info = lstatSync(path);
64
+ if (!info.isDirectory()) throw new Error('Directory required');
65
+ return { path: canonical, dev: info.dev, ino: info.ino };
66
+ } catch { throw new JobError('JOB_ROOT_REPLACED'); }
67
+ }
68
+
69
+ export function assertJobRoot(root: JobRootIdentity): void {
70
+ const now = captureJobRoot(root.path);
71
+ if (now.path !== root.path || now.dev !== root.dev || now.ino !== root.ino) throw new JobError('JOB_ROOT_REPLACED');
72
+ }
73
+
74
+ function rootRelative(root: string, absolute: string): string {
75
+ const path = relative(root, absolute).split(sep).join('/');
76
+ if (isAbsolute(path) || !path || path === '..' || path.startsWith('../')) throw new JobError('JOB_SOURCE_UNRETAINABLE');
77
+ return jobPath(path);
78
+ }
79
+
80
+ function sourceBytes(root: string, path: string): Buffer {
81
+ const file = checkedPath(root, jobPath(path));
82
+ const before = lstatSync(file), bytes = readRegular(file, maxFileBytes), after = lstatSync(file);
83
+ if (before.dev !== after.dev || before.ino !== after.ino || before.size !== after.size ||
84
+ before.mtimeMs !== after.mtimeMs || before.ctimeMs !== after.ctimeMs) throw new JobError('JOB_SOURCE_MISMATCH');
85
+ return bytes;
86
+ }
87
+
88
+ function assertRecord(root: JobRootIdentity, record: JobFileIdentity | null): void {
89
+ assertJobRoot(root);
90
+ if (record) {
91
+ try {
92
+ if (jobHash(sourceBytes(root.path, record.path)) !== record.sha256) throw new Error('Changed');
93
+ } catch { throw new JobError('JOB_RECORD_MOVED'); }
94
+ }
95
+ }
96
+
97
+ /** Synchronous final read is used inside local CAS. The producer must still hold
98
+ * its external freeze. This does not lock an independent producer's filesystem.
99
+ */
100
+ export function assertJobSourceCurrent(source: JobRetainedSource): void {
101
+ assertRecord(source.root, source.record);
102
+ for (const file of source.seals) {
103
+ try {
104
+ if (jobHash(sourceBytes(source.root.path, file.path)) !== file.sha256) throw new Error('Changed');
105
+ } catch (error) {
106
+ if (file.path === source.record?.path) throw new JobError('JOB_RECORD_MOVED');
107
+ if (error instanceof JobError && error.code === 'JOB_ROOT_REPLACED') throw error;
108
+ throw new JobError('JOB_SOURCE_MISMATCH');
109
+ }
110
+ }
111
+ assertRecord(source.root, source.record);
112
+ }
113
+
114
+ function publishedIdentities(context: JobPublishedContext): JobFileIdentity[] {
115
+ const files = [...context.files];
116
+ const ids = new Set<string>();
117
+ for (const step of context.plan?.steps ?? []) {
118
+ if (ids.has(jobId(step.id))) throw new JobError('JOB_SOURCE_MISMATCH');
119
+ ids.add(step.id);
120
+ jobSha(step.hash);
121
+ }
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');
128
+ }
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');
133
+ }
134
+ }
135
+ for (const file of files) { jobPath(file.path); jobSha(file.sha256); }
136
+ return files;
137
+ }
138
+
139
+ function collectQuestionFiles(root: string, questions: readonly InterviewQuestion[]): JobFileIdentity[] {
140
+ const result: JobFileIdentity[] = [];
141
+ function visit(value: unknown): void {
142
+ if (Array.isArray(value)) { value.forEach(visit); return; }
143
+ if (value === null || typeof value !== 'object') return;
144
+ const entry = value as Record<string, unknown>;
145
+ if (typeof entry.path === 'string' && typeof entry.sha256 === 'string') {
146
+ result.push({ path: jobPath(entry.path), sha256: jobSha(entry.sha256) });
147
+ }
148
+ Object.values(entry).forEach(visit);
149
+ }
150
+ for (const question of questions) {
151
+ result.push(question.ref, ...question.images.map(image => image.ref));
152
+ visit(JSON.parse(sourceBytes(root, question.ref.path).toString('utf8')));
153
+ }
154
+ return result;
155
+ }
156
+
157
+ export async function prepareJobSource(options: {
158
+ readonly root: JobRootIdentity;
159
+ readonly stateRoot: string;
160
+ readonly fingerprint: string;
161
+ readonly request: JobPublishRequest;
162
+ readonly readPublished?: JobPublicationReader;
163
+ readonly afterSnapshot?: () => void | Promise<void>;
164
+ readonly afterDirectorySync?: (path: string) => void;
165
+ }): Promise<JobRetainedSource> {
166
+ const { root, request } = options;
167
+ assertJobRoot(root);
168
+ const record = request.freeze.record;
169
+ let project: ReturnType<typeof readProject> | null = null;
170
+ try {
171
+ let hasProject = false;
172
+ try { lstatSync(join(root.path, 'project.json')); hasProject = true; }
173
+ catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; }
174
+ if (hasProject && record?.path !== 'project.json') throw new JobError('JOB_FREEZE_REQUIRED');
175
+ if (record) {
176
+ const bytes = sourceBytes(root.path, record.path);
177
+ if (jobHash(bytes) !== record.sha256) throw new JobError('JOB_RECORD_MOVED');
178
+ try { JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)); }
179
+ catch { throw new JobError('JOB_RECORD_INCOMPLETE'); }
180
+ if (record.path === 'project.json') project = readProject(root.path);
181
+ } else {
182
+ try { lstatSync(join(root.path, 'project.json')); throw new JobError('JOB_FREEZE_REQUIRED'); }
183
+ catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; }
184
+ }
185
+ } catch (error) {
186
+ if (error instanceof JobError) throw error;
187
+ throw new JobError('JOB_RECORD_INCOMPLETE');
188
+ }
189
+ const context: JobPublishedContext = options.readPublished && record ? await options.readPublished({
190
+ root: root.path, record, result: request.result,
191
+ }) : { selector: request.result.selector, plan: null, parts: null, subjects: [], partIds: [], files: [] };
192
+ if (project && !options.readPublished) {
193
+ throw new JobError('JOB_SOURCE_UNRETAINABLE', 'CREATE_PUBLICATION_CONTRACT_UNAVAILABLE');
194
+ }
195
+ if (requestDigest(context.selector) !== requestDigest(request.result.selector)) throw new JobError('JOB_SOURCE_MISMATCH');
196
+ const declared = publishedIdentities(context);
197
+ let review: Awaited<ReturnType<typeof loadReview>>;
198
+ try {
199
+ const target = checkedPath(root.path, request.result.path, lstatSync(join(root.path, request.result.path)).isDirectory());
200
+ review = await loadReview(target);
201
+ } catch { throw new JobError('JOB_SOURCE_MISMATCH'); }
202
+ const wanted = new Map<string, string | null>();
203
+ function add(path: string, sha256: string | null = null): void {
204
+ jobPath(path);
205
+ const existing = wanted.get(path);
206
+ if (existing && sha256 && existing !== sha256) throw new JobError('JOB_SOURCE_MISMATCH');
207
+ wanted.set(path, sha256 ?? existing ?? null);
208
+ }
209
+ for (const path of review.files) add(rootRelative(root.path, resolve(review.root, path)));
210
+ for (const file of review.handoff?.record.files ?? []) add(rootRelative(root.path, resolve(review.root, file.path)), file.sha256);
211
+ if (review.handoff?.source && review.handoff.record.source) {
212
+ add(rootRelative(root.path, review.handoff.source), review.handoff.record.source.sha256);
213
+ }
214
+ if (record) add(record.path, record.sha256);
215
+ for (const file of [...declared, ...collectQuestionFiles(root.path, project?.questions ?? [])]) add(file.path, file.sha256);
216
+ if (wanted.size > maxSourceFiles) throw new JobError('JOB_SOURCE_UNRETAINABLE');
217
+ const snapshotRoot = join(options.stateRoot, 'snapshots', randomUUID());
218
+ const seals: JobFileIdentity[] = [];
219
+ try {
220
+ await mkdir(snapshotRoot, { recursive: true, mode: 0o700 });
221
+ let size = 0;
222
+ const directories = new Set([snapshotRoot, dirname(snapshotRoot), options.stateRoot]);
223
+ 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);
225
+ size += bytes.length;
226
+ if (size > maxSourceBytes) throw new JobError('JOB_SOURCE_UNRETAINABLE');
227
+ if (expected && sha256 !== expected) throw new JobError(path === record?.path ? 'JOB_RECORD_MOVED' : 'JOB_SOURCE_MISMATCH');
228
+ const destination = join(snapshotRoot, path);
229
+ await mkdir(dirname(destination), { recursive: true, mode: 0o700 });
230
+ const file = await open(destination, 'wx', 0o600);
231
+ try { await file.writeFile(bytes); await file.sync(); }
232
+ finally { await file.close(); }
233
+ let directory = dirname(destination);
234
+ while (directory !== snapshotRoot) {
235
+ directories.add(directory);
236
+ directory = dirname(directory);
237
+ }
238
+ seals.push({ path, sha256 });
239
+ }
240
+ for (const directory of [...directories].sort((a, b) => b.length - a.length)) {
241
+ const handle = await open(directory, 'r');
242
+ try { await handle.sync(); }
243
+ finally { await handle.close(); }
244
+ options.afterDirectorySync?.(directory);
245
+ }
246
+ await assertReviewUnchanged(review);
247
+ const retained = await loadReview(join(snapshotRoot, request.result.path));
248
+ if (retained.sourceHash !== review.sourceHash || requestDigest(retained.reviewedSource) !== requestDigest(review.reviewedSource)) {
249
+ throw new JobError('JOB_SOURCE_UNRETAINABLE');
250
+ }
251
+ const originalIdentity = (file: { path: string; sha256: string } | null): JobFileIdentity | null => file && ({
252
+ path: rootRelative(root.path, resolve(review.root, file.path)), sha256: file.sha256,
253
+ });
254
+ const source: JobSourceBinding = {
255
+ 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,
258
+ })) : review.sourceHash,
259
+ projectHash: project?.hash ?? null,
260
+ package: { id: review.manifest.id, revision: review.manifest.revision },
261
+ selector: context.selector,
262
+ model: originalIdentity(review.reviewedSource.rig),
263
+ direction: originalIdentity(review.direction?.file ?? null),
264
+ optionSet: null, appliedResult: null, plan: context.plan, parts: context.parts,
265
+ };
266
+ const boundReview = { ...review, sourceHash: source.sourceHash };
267
+ const prepared: JobRetainedSource = {
268
+ root, record, seals, snapshotRoot,
269
+ manifestPath: retained.manifestPath,
270
+ source,
271
+ instanceKey: openKey({ mode: 'single', p: boundReview, inputs: { input: review.manifestPath },
272
+ contentHash: source.sourceHash, selection: null }, options.fingerprint),
273
+ label: review.manifest.title,
274
+ visual: review.manifest.model || review.manifest.references.length ? { status: 'available' } :
275
+ { status: 'unavailable', code: 'MODEL_UNAVAILABLE' },
276
+ subjects: context.subjects,
277
+ questions: (project?.questions ?? []).map(question => {
278
+ const { answer, ...fields } = question;
279
+ return answer === undefined ? fields : question;
280
+ }),
281
+ partIds: context.partIds,
282
+ };
283
+ await options.afterSnapshot?.();
284
+ assertJobSourceCurrent(prepared);
285
+ return prepared;
286
+ } catch (error) {
287
+ await rm(snapshotRoot, { recursive: true, force: true });
288
+ if (error instanceof JobError) throw error;
289
+ throw new JobError('JOB_SOURCE_MISMATCH');
290
+ }
291
+ }