rig-review 2.5.0 → 2.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/src/job-cli.ts CHANGED
@@ -1,9 +1,9 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import {closeSync, constants, fstatSync, fsyncSync, lstatSync, openSync, readFileSync, renameSync, unlinkSync, writeSync} from 'node:fs';
3
3
  import {join} from 'node:path';
4
- import { JOB_API_SCHEMA, JOB_ACT_SCHEMA, JOB_RIG_REVIEW_ACT_SCHEMA, jobRawActMediaType, jobStillByteLimit,
5
- type JobAct, type JobAgentRequest } from './job-contract.ts';
6
- import { assertJobApiSchema, jobFailure, jobHash, jobId, jobObject, parseJobRequest } from './job-api.ts';
4
+ import { JOB_API_SCHEMA, JOB_ACT_SCHEMA, JOB_RIG_REVIEW_ACT_SCHEMA, JOB_ENABLED_ACT_KINDS, jobRawActMediaType, jobStillByteLimit,
5
+ type JobAct, type JobAgentRequest, type JobNextRequest, type JobNextValue } from './job-contract.ts';
6
+ import { assertJobApiSchema, jobFailure, jobHash, jobId, jobInteger, jobObject, jobWaitLimitMs, parseJobRequest } from './job-api.ts';
7
7
  import { JobError } from './job-store.ts';
8
8
  import {validatePngBytes} from './comment-crops.ts';
9
9
  import {destinationDirectory} from './destination-directory.ts';
@@ -29,7 +29,7 @@ const commonFlags = ['generation', 'key', 'request-id'];
29
29
  const verbFlags: Record<string, readonly string[]> = {
30
30
  publish: [...commonFlags, 'result', 'selector', 'freeze-hold', 'record', 'record-hash'],
31
31
  ask: [...commonFlags, 'publication', 'subject'],
32
- next: ['after', 'wait-ms', 'request-id'],
32
+ next: ['after', 'wait-ms', 'request-id', 'until'],
33
33
  close: [...commonFlags, 'reason'],
34
34
  };
35
35
 
@@ -59,15 +59,24 @@ function semanticJSON(value: string): unknown {
59
59
  /** Public semantic request construction only. There is no act-writing or
60
60
  * consumer-fetch verb, no internal JSON input file and no Review state access.
61
61
  */
62
- export function parseJobCLI(args: readonly string[]): { readonly endpoint: string; readonly request: JobAgentRequest } {
62
+ export function parseJobCLI(args: readonly string[]): { readonly endpoint: string; readonly request: JobAgentRequest; readonly waitUntilActMs?: number } {
63
63
  const [verb, locator, ...rest] = args;
64
64
  if (!verbFlags[verb]) throw new JobError('JOB_REQUEST_INVALID');
65
65
  const {url, job} = jobLocator(locator);
66
66
  const values = flags(rest, verbFlags[verb]);
67
67
  const base = { schema: JOB_API_SCHEMA, verb, jobId: job, requestId: values.get('request-id') ?? randomUUID() };
68
68
  let payload: unknown;
69
+ let waitUntilActMs: number | undefined;
69
70
  if (verb === 'next') {
70
- payload = { ...base, after: values.get('after') ?? null, waitMs: Number(values.get('wait-ms') ?? '0') };
71
+ let waitMs = Number(values.get('wait-ms') ?? '0');
72
+ if (values.has('until')) {
73
+ if (values.get('until') !== 'act' || !Number.isSafeInteger(waitMs) || waitMs < 1 || waitMs > 600_000) {
74
+ throw new JobError('JOB_REQUEST_INVALID');
75
+ }
76
+ waitUntilActMs = waitMs;
77
+ waitMs = Math.min(waitMs, jobWaitLimitMs);
78
+ }
79
+ payload = { ...base, after: values.get('after') ?? null, waitMs };
71
80
  } else {
72
81
  const mutation = { ...base, expectedGeneration: Number(required(values, 'generation')), idempotencyKey: required(values, 'key') };
73
82
  switch (verb) {
@@ -89,7 +98,7 @@ export function parseJobCLI(args: readonly string[]): { readonly endpoint: strin
89
98
  }
90
99
  const request = parseJobRequest(payload);
91
100
  if (request.verb === 'fetch-act') throw new JobError('JOB_AUTHORITY_REFUSED');
92
- return { endpoint: `${url.origin}/jobs/${job}/api`, request };
101
+ return { endpoint: `${url.origin}/jobs/${job}/api`, request, ...(waitUntilActMs === undefined ? {} : {waitUntilActMs}) };
93
102
  }
94
103
 
95
104
  function jobLocator(locator: string): {url: URL; job: string} {
@@ -170,32 +179,46 @@ function outputConsumerAct(actBytes: Buffer, png: Buffer | undefined, act: JobAc
170
179
  let temporaryIdentity: {dev: number; ino: number} | undefined;
171
180
  let installed: string | undefined;
172
181
  let installedIdentity: {dev: number; ino: number} | undefined;
182
+ let pngDescriptor: number | undefined;
173
183
  let lock: string | undefined;
174
184
  let lockDescriptor: number | undefined;
175
185
  let emitted = 0;
176
186
  try {
177
187
  if (png && destination && act.schema === JOB_RIG_REVIEW_ACT_SCHEMA) {
178
188
  const directory = destinationDirectory(destination, 'JOB_STILL_OUTPUT_FAILED', false);
179
- lock = join(directory, '.rig-review-still.lock');
180
- lockDescriptor = openSync(lock, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600);
181
- const target = join(directory, act.still.path);
182
- let existing = false;
189
+ const directoryDescriptor = openSync(directory, constants.O_RDONLY | (constants.O_DIRECTORY ?? 0) | constants.O_NOFOLLOW);
183
190
  try {
184
- const descriptor = openSync(target, constants.O_RDONLY | constants.O_NOFOLLOW);
191
+ const directoryIdentity = fstatSync(directoryDescriptor);
192
+ if (!directoryIdentity.isDirectory()) throw new JobError('JOB_STILL_OUTPUT_FAILED');
193
+ lock = join(directory, '.rig-review-still.lock');
185
194
  try {
186
- const info = fstatSync(descriptor);
187
- if (!info.isFile() || info.size > jobStillByteLimit || jobHash(readFileSync(descriptor)) !== act.still.sha256) {
188
- throw new JobError('JOB_STILL_OUTPUT_FAILED');
195
+ lockDescriptor = openSync(lock, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600);
196
+ } catch (error) {
197
+ if ((error as NodeJS.ErrnoException).code === 'EEXIST') {
198
+ throw new JobError('JOB_STILL_OUTPUT_FAILED',
199
+ `JOB_STILL_OUTPUT_FAILED: retained lock ${lock} already exists; wait for another writer to finish or remove ${lock} if a killed process left it`);
189
200
  }
190
- existing = true;
191
- } finally { closeSync(descriptor); }
192
- } catch (error) {
193
- if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
194
- }
195
- if (!existing) {
196
- temporary = join(directory, '.rig-review-still-' + randomUUID() + '.tmp');
197
- const descriptor = openSync(temporary, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600);
201
+ throw error;
202
+ }
203
+ const target = join(directory, act.still.path);
204
+ let existing = false;
198
205
  try {
206
+ const descriptor = openSync(target, constants.O_RDONLY | constants.O_NOFOLLOW);
207
+ try {
208
+ const info = fstatSync(descriptor);
209
+ if (!info.isFile() || info.size > jobStillByteLimit || jobHash(readFileSync(descriptor)) !== act.still.sha256) {
210
+ throw new JobError('JOB_STILL_OUTPUT_FAILED');
211
+ }
212
+ existing = true;
213
+ } finally { closeSync(descriptor); }
214
+ } catch (error) {
215
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
216
+ }
217
+ if (!existing) {
218
+ temporary = join(directory, '.rig-review-still-' + randomUUID() + '.tmp');
219
+ const descriptor = openSync(temporary, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600);
220
+ // Pin this inode through output and ownership cleanup, even if its path is replaced.
221
+ pngDescriptor = descriptor;
199
222
  const owned = fstatSync(descriptor);
200
223
  temporaryIdentity = {dev: owned.dev, ino: owned.ino};
201
224
  let offset = 0;
@@ -207,11 +230,16 @@ function outputConsumerAct(actBytes: Buffer, png: Buffer | undefined, act: JobAc
207
230
  fsyncSync(descriptor);
208
231
  const info = fstatSync(descriptor);
209
232
  installedIdentity = {dev: info.dev, ino: info.ino};
210
- } finally { closeSync(descriptor); }
211
- renameSync(temporary, target);
212
- temporary = undefined;
213
- installed = target;
214
- }
233
+ renameSync(temporary, target);
234
+ temporary = undefined;
235
+ installed = target;
236
+ }
237
+ const currentDirectory = lstatSync(directory);
238
+ if (currentDirectory.dev !== directoryIdentity.dev || currentDirectory.ino !== directoryIdentity.ino) {
239
+ throw new JobError('JOB_STILL_OUTPUT_FAILED');
240
+ }
241
+ fsyncSync(directoryDescriptor);
242
+ } finally { closeSync(directoryDescriptor); }
215
243
  }
216
244
  if (options.write && !options.writeBytes) {
217
245
  // A legacy callback cannot report partial progress, so preserve an installed PNG on a thrown write.
@@ -225,17 +253,23 @@ function outputConsumerAct(actBytes: Buffer, png: Buffer | undefined, act: JobAc
225
253
  emitted += written;
226
254
  }
227
255
  }
228
- } catch {
256
+ } catch (error) {
229
257
  if (emitted === 0 && installed && installedIdentity) {
230
258
  unlinkOwned(installed, installedIdentity);
231
259
  }
232
- throw new JobError('JOB_STILL_OUTPUT_FAILED');
260
+ throw error instanceof JobError ? error : new JobError('JOB_STILL_OUTPUT_FAILED');
233
261
  } finally {
234
- if (temporary && temporaryIdentity) unlinkOwned(temporary, temporaryIdentity);
235
- if (lockDescriptor !== undefined) {
236
- const owned = fstatSync(lockDescriptor);
237
- closeSync(lockDescriptor);
238
- unlinkOwned(lock!, owned);
262
+ try {
263
+ try {
264
+ if (temporary && temporaryIdentity) unlinkOwned(temporary, temporaryIdentity);
265
+ } finally {
266
+ if (lockDescriptor !== undefined) {
267
+ try { unlinkOwned(lock!, fstatSync(lockDescriptor)); }
268
+ finally { closeSync(lockDescriptor); }
269
+ }
270
+ }
271
+ } finally {
272
+ if (pngDescriptor !== undefined) closeSync(pngDescriptor);
239
273
  }
240
274
  }
241
275
  }
@@ -283,29 +317,14 @@ async function fetchActCommand(args: readonly string[], options: JobCLIOptions):
283
317
  outputConsumerAct(bytes, png, act, destination, options);
284
318
  }
285
319
 
286
- export async function jobCommand(args: readonly string[], options: JobCLIOptions = {}): Promise<void> {
287
- if (args[0] === 'fetch-act') return fetchActCommand(args, options);
288
- const write = options.write ?? (text => console.log(text));
289
- if (args[0] === 'open') {
290
- if (args.length !== 2 || !options.open) throw new JobError('JOB_AUTHORITY_REFUSED', 'Managed job opening requires the Review host');
291
- write((await options.open(args[1])).ownerUrl);
292
- return;
293
- }
294
- const input = parseJobCLI(args);
295
- const capability = options.agentCapability ?? process.env.RIG_REVIEW_JOB_AGENT_CAPABILITY;
296
- if (!capability) throw new JobError('JOB_CAPABILITY_REQUIRED');
297
- const response = await (options.fetch ?? fetch)(input.endpoint, {
298
- method: 'POST', redirect: 'error', signal: options.signal,
299
- headers: { 'Content-Type': 'application/json', Authorization: 'Bearer ' + capability },
300
- body: JSON.stringify(input.request),
301
- });
320
+ async function readJobResponse(response: Response, interrupted?: Promise<never>): Promise<unknown> {
302
321
  const reader = response.body?.getReader();
303
322
  if (!reader) throw new JobError('JOB_REQUEST_INVALID');
304
323
  const chunks: Uint8Array[] = [];
305
324
  let size = 0;
306
325
  try {
307
326
  for (;;) {
308
- const { done, value } = await reader.read();
327
+ const { done, value } = await (interrupted ? Promise.race([reader.read(), interrupted]) : reader.read());
309
328
  if (done) break;
310
329
  size += value.byteLength;
311
330
  if (size > 1024 * 1024) {
@@ -314,6 +333,11 @@ export async function jobCommand(args: readonly string[], options: JobCLIOptions
314
333
  }
315
334
  chunks.push(value);
316
335
  }
336
+ } catch (error) {
337
+ if (interrupted) {
338
+ try { void reader.cancel().catch(() => {}); } catch {}
339
+ }
340
+ throw error;
317
341
  } finally {
318
342
  reader.releaseLock();
319
343
  }
@@ -321,6 +345,149 @@ export async function jobCommand(args: readonly string[], options: JobCLIOptions
321
345
  try { value = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks, size))); }
322
346
  catch { throw new JobError('JOB_REQUEST_INVALID'); }
323
347
  assertJobApiSchema(value !== null && typeof value === 'object' ? (value as { schema?: unknown }).schema : undefined);
348
+ return value;
349
+ }
350
+
351
+ /** Check the complete existing next batch before accepting its read cursor. */
352
+ function nextValue(value: unknown, request: JobNextRequest): JobNextValue {
353
+ const result = jobObject(value, ['schema', 'verb', 'jobId', 'requestId', 'generation', 'ok', 'value']);
354
+ if (result.ok !== true || result.verb !== 'next' || result.jobId !== request.jobId) throw new JobError('JOB_REQUEST_INVALID');
355
+ jobInteger(result.generation);
356
+ const batch = jobObject(result.value, ['capabilities', 'events', 'cursor', 'status']);
357
+ if (!Array.isArray(batch.events) || !['events', 'timeout', 'closed'].includes(batch.status as string)) throw new JobError('JOB_REQUEST_INVALID');
358
+ if (batch.cursor !== null) jobId(batch.cursor);
359
+ for (const raw of batch.events) {
360
+ const event = jobObject(raw, ['cursor', 'jobId', 'generation', 'type', 'publication', 'ask', 'act', 'reason']);
361
+ jobId(event.cursor);
362
+ jobInteger(event.generation);
363
+ if (event.jobId !== request.jobId) throw new JobError('JOB_REQUEST_INVALID');
364
+ switch (event.type) {
365
+ case 'act': {
366
+ const actId = jobId((event.act as {actId?: unknown} | null)?.actId);
367
+ const act = parseConsumerAct(Buffer.from(JSON.stringify(event.act)), request.jobId, actId);
368
+ if (!(JOB_ENABLED_ACT_KINDS as readonly string[]).includes(act.kind)) throw new JobError('JOB_ACT_INVALID');
369
+ break;
370
+ }
371
+ case 'published':
372
+ case 'pending': {
373
+ const payload = event.type === 'published' ? event.publication : event.ask;
374
+ if (payload === null || typeof payload !== 'object' || Array.isArray(payload)) throw new JobError('JOB_REQUEST_INVALID');
375
+ break;
376
+ }
377
+ case 'closed':
378
+ if (typeof event.reason !== 'string') throw new JobError('JOB_REQUEST_INVALID');
379
+ break;
380
+ default: throw new JobError('JOB_REQUEST_INVALID');
381
+ }
382
+ }
383
+ const last = batch.events.at(-1);
384
+ if (batch.cursor !== (last?.cursor ?? request.after) || (batch.status === 'events') !== (batch.events.length > 0)) {
385
+ throw new JobError('JOB_REQUEST_INVALID');
386
+ }
387
+ return batch as unknown as JobNextValue;
388
+ }
389
+
390
+ async function waitForAct(endpoint: string, initial: JobNextRequest, waitMs: number, capability: string,
391
+ write: (text: string) => void, options: JobCLIOptions): Promise<void> {
392
+ const controller = new AbortController();
393
+ const timeout = new Error('JOB_NEXT_TIMEOUT');
394
+ const cancel = () => controller.abort(options.signal?.reason);
395
+ options.signal?.addEventListener('abort', cancel, {once: true});
396
+ if (options.signal?.aborted) cancel();
397
+ const deadline = performance.now() + waitMs;
398
+ let timer: ReturnType<typeof setTimeout> | undefined;
399
+ const expire = () => {
400
+ if (controller.signal.aborted) return;
401
+ const budget = deadline - performance.now();
402
+ if (budget <= 0) controller.abort(timeout);
403
+ else timer = setTimeout(expire, Math.ceil(budget));
404
+ };
405
+ timer = setTimeout(expire, waitMs);
406
+ const interrupted = new Promise<never>((_resolve, reject) => {
407
+ controller.signal.addEventListener('abort', () => reject(controller.signal.reason), {once: true});
408
+ if (controller.signal.aborted) reject(controller.signal.reason);
409
+ });
410
+ // Pre-cancellation can reject before the first network race is installed.
411
+ void interrupted.catch(() => {});
412
+ function remaining(): number {
413
+ const budget = deadline - performance.now();
414
+ if (!controller.signal.aborted && budget <= 0) controller.abort(timeout);
415
+ controller.signal.throwIfAborted();
416
+ return budget;
417
+ }
418
+ let after = initial.after;
419
+ let lastResponse: unknown;
420
+ try {
421
+ for (;;) {
422
+ const budget = remaining();
423
+ const request = {...initial, after, waitMs: Math.max(0, Math.floor(Math.min(budget, jobWaitLimitMs)))};
424
+ // A delayed transport must also dispose its body if cancellation won the race.
425
+ const pending = (options.fetch ?? fetch)(endpoint, {
426
+ method: 'POST', redirect: 'error', signal: controller.signal,
427
+ headers: {'Content-Type': 'application/json', Authorization: 'Bearer ' + capability},
428
+ body: JSON.stringify(request),
429
+ }).then(response => {
430
+ if (controller.signal.aborted) {
431
+ try { void response.body?.cancel().catch(() => {}); } catch {}
432
+ controller.signal.throwIfAborted();
433
+ }
434
+ return response;
435
+ });
436
+ const response = await Promise.race([pending, interrupted]);
437
+ const value = await readJobResponse(response, interrupted);
438
+ remaining();
439
+ if (!response.ok || (value as {ok?: unknown}).ok === false) {
440
+ write(JSON.stringify(value));
441
+ process.exitCode = 1;
442
+ return;
443
+ }
444
+ const batch = nextValue(value, request);
445
+ remaining();
446
+ if (batch.events.some(event => event.type === 'act')) {
447
+ write(JSON.stringify(value));
448
+ return;
449
+ }
450
+ if (batch.status === 'closed' || batch.events.some(event => event.type === 'closed')) {
451
+ write(JSON.stringify(value));
452
+ console.error('JOB_CLOSED');
453
+ process.exitCode = 1;
454
+ return;
455
+ }
456
+ lastResponse = value;
457
+ after = batch.cursor;
458
+ }
459
+ } catch (error) {
460
+ if (!controller.signal.aborted && performance.now() >= deadline) controller.abort(timeout);
461
+ if (controller.signal.reason !== timeout) throw error;
462
+ if (lastResponse !== undefined) write(JSON.stringify(lastResponse));
463
+ console.error('JOB_NEXT_TIMEOUT');
464
+ process.exitCode = 3;
465
+ } finally {
466
+ clearTimeout(timer);
467
+ options.signal?.removeEventListener('abort', cancel);
468
+ }
469
+ }
470
+
471
+ export async function jobCommand(args: readonly string[], options: JobCLIOptions = {}): Promise<void> {
472
+ if (args[0] === 'fetch-act') return fetchActCommand(args, options);
473
+ const write = options.write ?? (text => console.log(text));
474
+ if (args[0] === 'open') {
475
+ if (args.length !== 2 || !options.open) throw new JobError('JOB_AUTHORITY_REFUSED', 'Managed job opening requires the Review host');
476
+ write((await options.open(args[1])).ownerUrl);
477
+ return;
478
+ }
479
+ const input = parseJobCLI(args);
480
+ const capability = options.agentCapability ?? process.env.RIG_REVIEW_JOB_AGENT_CAPABILITY;
481
+ if (!capability) throw new JobError('JOB_CAPABILITY_REQUIRED');
482
+ if (input.waitUntilActMs !== undefined && input.request.verb === 'next') {
483
+ return waitForAct(input.endpoint, input.request, input.waitUntilActMs, capability, write, options);
484
+ }
485
+ const response = await (options.fetch ?? fetch)(input.endpoint, {
486
+ method: 'POST', redirect: 'error', signal: options.signal,
487
+ headers: { 'Content-Type': 'application/json', Authorization: 'Bearer ' + capability },
488
+ body: JSON.stringify(input.request),
489
+ });
490
+ const value = await readJobResponse(response);
324
491
  write(JSON.stringify(value));
325
492
  if (!response.ok) process.exitCode = 1;
326
493
  }
@@ -6,7 +6,7 @@ import { accessGate } from './open-protocol.ts';
6
6
  import { createLiveLifecycle, LIVE_PATH, type LiveExitInfo, type UpgradableServer } from './live-lifecycle.ts';
7
7
  import {preparePartsComment} from './parts-comment-crops.ts';
8
8
  import {serveReference} from './reference.ts';
9
- import { partsDifference, partsViewJson, exportPartsVerdict, assertPartsUnchanged, readVerdict, saveVerdict, servedImage, type PartsViewPackage } from './parts-view.ts';
9
+ import { partsDifference, partsViewJson, exportPartsVerdict, assertPartsUnchanged, readVerdict, saveVerdictWithReceipt, servedImage, type PartsViewPackage, type PartsSaveReceipt } from './parts-view.ts';
10
10
 
11
11
  const headers = { 'X-Content-Type-Options': 'nosniff', 'Cache-Control': 'no-store', 'Content-Security-Policy': "default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' blob: data:; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'" };
12
12
  const json = (value: unknown, status = 200) => Response.json(value, { status, headers });
@@ -36,13 +36,47 @@ async function bodyJson(req: Request): Promise<unknown> {
36
36
  return JSON.parse(new TextDecoder().decode(body));
37
37
  }
38
38
 
39
- export interface PartsServerOptions { port?: number; capability?: string; exitOnClose?: boolean; graceMs?: number; unopenedTimeoutMs?: number; onClose?: (info: LiveExitInfo) => void | Promise<void>; log?: (line: string) => void }
39
+ export interface PartsSavedEvent extends PartsSaveReceipt { saveCount: number }
40
+ export interface PartsServerOptions {
41
+ port?: number; capability?: string; exitOnClose?: boolean; graceMs?: number; unopenedTimeoutMs?: number;
42
+ onClose?: (info: LiveExitInfo) => void | Promise<void>; log?: (line: string) => void;
43
+ by?: string;
44
+ onSaved?: (event: PartsSavedEvent) => Promise<void>;
45
+ onNotifyFailure?: (error: Error) => void;
46
+ onWriteFailure?: (error: Error) => void;
47
+ }
40
48
 
41
49
  export async function startPartsServer(pkg: PartsViewPackage, options: PartsServerOptions = {}) {
50
+ const by = options.by;
51
+ if (by !== undefined && (typeof by !== 'string' || !by.trim())) throw new Error('PARTS_VERDICT_INVALID: reviewer name must be nonblank');
42
52
  const bundle = await buildWeb('parts');
43
53
  let rawStop: ((closeActiveConnections?: boolean) => void) | null = null;
44
- let saving = false;
45
- const live = createLiveLifecycle({ label: 'review parts', graceMs: options.graceMs, unopenedTimeoutMs: options.unopenedTimeoutMs, exitOnClose: options.exitOnClose, onClose: options.onClose, log: options.log, busy: () => saving, stopServer: () => { rawStop?.(true); } });
54
+ let pendingSaves = 0, saveCount = 0;
55
+ let saveQueue: Promise<void> = Promise.resolve();
56
+ let closing = false;
57
+ let notifyFailure: Error | null = null;
58
+ const live = createLiveLifecycle({ label: 'review parts', graceMs: options.graceMs, unopenedTimeoutMs: options.unopenedTimeoutMs, exitOnClose: options.exitOnClose, onClose: options.onClose, log: options.log, busy: () => pendingSaves > 0, stopServer: () => { rawStop?.(true); } });
59
+ const save = (req: Request) => {
60
+ if (closing) throw new Error('PARTS_VERDICT_WRITE_FAILED: server is closing');
61
+ pendingSaves++;
62
+ const result = saveQueue.then(async () => {
63
+ if (notifyFailure) throw notifyFailure;
64
+ if (saveCount === Number.MAX_SAFE_INTEGER) throw new Error('PARTS_VERDICT_WRITE_FAILED: save count exhausted');
65
+ const {verdict, receipt} = await saveVerdictWithReceipt(pkg, await bodyJson(req), undefined, by);
66
+ const event = {...receipt, saveCount: ++saveCount};
67
+ try { await options.onSaved?.(event); }
68
+ catch (error) {
69
+ notifyFailure = new Error('PARTS_VERDICT_NOTIFY_FAILED: durable save notification failed', {cause: error});
70
+ options.onNotifyFailure?.(notifyFailure);
71
+ throw notifyFailure;
72
+ }
73
+ return verdict;
74
+ });
75
+ saveQueue = result.then(() => {}, error => {
76
+ if (error instanceof Error && error.message.startsWith('PARTS_VERDICT_WRITE_FAILED:')) options.onWriteFailure?.(error);
77
+ }).finally(() => { pendingSaves--; });
78
+ return result;
79
+ };
46
80
  const handle = async (req: Request, port: number | undefined, srv: UpgradableServer): Promise<Response | undefined> => {
47
81
  try {
48
82
  const url = new URL(req.url), origin = `http://127.0.0.1:${port}`;
@@ -60,8 +94,7 @@ export async function startPartsServer(pkg: PartsViewPackage, options: PartsServ
60
94
  if(url.pathname==='/api/parts/export'&&req.method==='GET'){await assertPartsUnchanged(pkg);const saved=await readVerdict(pkg);if(!saved.verdict)return json({error:'PARTS_VERDICT_UNAVAILABLE: save a verdict first'},409);return new Response(exportPartsVerdict(saved.verdict,url.searchParams.get('format')==='issue'?'issue':'json'),{headers:{...headers,'Content-Type':url.searchParams.get('format')==='issue'?'text/markdown':'application/json'}});}
61
95
  if (url.pathname === '/api/parts/verdict' && req.method === 'POST') {
62
96
  if (req.headers.get('origin') !== origin) return json({ error: 'Same-origin Origin required' }, 403);
63
- saving = true;
64
- try { return json({ verdict: await saveVerdict(pkg, await bodyJson(req)) }); } finally { saving = false; }
97
+ return json({ verdict: await save(req) });
65
98
  }
66
99
  if(url.pathname==='/api/parts/painting'&&req.method==='GET'){if(!pkg.painting)return json({error:'PARTS_REFERENCE_UNAVAILABLE: supply --painting to compare the original painting'},404);return serveReference(req,pkg.painting.abs,pkg.painting.sha256,headers);}
67
100
  const difference=/^\/api\/parts\/difference\/(\d+)$/.exec(url.pathname);
@@ -92,5 +125,11 @@ export async function startPartsServer(pkg: PartsViewPackage, options: PartsServ
92
125
  const server = Bun.serve({ hostname: '127.0.0.1', port: options.port ?? 4317, websocket: live.websocket, async fetch(req, srv) { const res = await handle(req, srv.port, srv); return res as Response; } });
93
126
  rawStop = server.stop.bind(server);
94
127
  server.stop = ((closeActiveConnections?: boolean) => { live.stop(); return rawStop!(closeActiveConnections); }) as typeof server.stop;
95
- return Object.assign(server, { live });
128
+ const shutdown = async () => {
129
+ closing = true;
130
+ await saveQueue;
131
+ live.stop();
132
+ await server.stop(false);
133
+ };
134
+ return Object.assign(server, { live, shutdown });
96
135
  }
package/src/parts-view.ts CHANGED
@@ -21,13 +21,14 @@ import {preparePartsComment,validateStoredPartsComment} from './parts-comment-cr
21
21
  import {resolvedCropPath} from './comment-crops.ts';
22
22
  import { createHash } from 'node:crypto';
23
23
  import { existsSync } from 'node:fs';
24
- import { mkdir, readFile, realpath, rename, rm, stat, writeFile } from 'node:fs/promises';
24
+ import { mkdir, open, readFile, realpath, rename, rm, stat } from 'node:fs/promises';
25
25
  import { basename, dirname, isAbsolute, join, posix, relative, resolve, sep } from 'node:path';
26
26
  import { PNG } from 'pngjs';
27
27
  import { loadReview, safeFile, packagePath, type ReviewPackage } from './manifest.ts';
28
28
  import { destinationDirectory } from './destination-directory.ts';
29
29
 
30
30
  export const PARTS_VERDICT_SCHEMA = 'rig-review-parts-verdict/2';
31
+ const NAMED_VERDICT_SCHEMA = 'rig-review-parts-verdict/3';
31
32
  export const PARTS_VERDICT_FILE = 'parts-review.json';
32
33
  export const PARTS_NOTE_LIMIT = 10000;
33
34
  export type PartsViewMode = 'parts' | 'atlas';
@@ -553,8 +554,20 @@ async function packageVersion(): Promise<string> {
553
554
  return (JSON.parse(await readFile(new URL('../package.json', import.meta.url), 'utf8')) as { version: string }).version;
554
555
  }
555
556
 
556
- /** Writes the verdict atomically at its designated destination. */
557
- export async function saveVerdict(pkg: PartsViewPackage, input: unknown, assertCurrent?: () => Promise<void>): Promise<PartsVerdict> {
557
+ async function verdictWrite<T>(operation: string, action: () => Promise<T>): Promise<T> {
558
+ try { return await action(); }
559
+ catch (error) {
560
+ const code = (error as NodeJS.ErrnoException).code ?? 'IO';
561
+ throw new Error(`PARTS_VERDICT_WRITE_FAILED: ${operation} (${code})`, {cause: error});
562
+ }
563
+ }
564
+
565
+ export interface PartsSaveReceipt { verdictPath: string; sha256: string; status: VerdictStatus }
566
+
567
+ /** One durable buffer, shared by standalone and joined saves. Attribution is launch configuration only. */
568
+ export async function saveVerdictWithReceipt(pkg: PartsViewPackage, input: unknown,
569
+ assertCurrent?: () => Promise<void>, by?: string): Promise<{verdict: PartsVerdict; receipt: PartsSaveReceipt}> {
570
+ if (by !== undefined && (typeof by !== 'string' || !by.trim())) refuse('PARTS_VERDICT_INVALID', 'reviewer name must be nonblank');
558
571
  await assertCurrent?.();
559
572
  await assertVerdictDestination(pkg);
560
573
  await assertPartsUnchanged(pkg);
@@ -562,14 +575,37 @@ export async function saveVerdict(pkg: PartsViewPackage, input: unknown, assertC
562
575
  const verdict = buildVerdict(pkg, input, await packageVersion());
563
576
  for(const comment of verdict.comments)await preparePartsComment(pkg,comment,true);
564
577
  await assertPartsUnchanged(pkg);
565
- await mkdir(dirname(pkg.verdictPath), { recursive: true });
578
+ const stored = by === undefined ? verdict : {...verdict, schema: NAMED_VERDICT_SCHEMA, by};
579
+ const bytes = Buffer.from(JSON.stringify(stored, null, 2) + '\n');
580
+ const parent = dirname(pkg.verdictPath);
581
+ const firstCreated = await verdictWrite('mkdir', () => mkdir(parent, { recursive: true }));
566
582
  const tmp = `${pkg.verdictPath}.${crypto.randomUUID()}.tmp`;
567
583
  try {
568
- await writeFile(tmp, JSON.stringify(verdict, null, 2) + '\n', { flag: 'wx' });
584
+ await verdictWrite('write/fsync', async () => {
585
+ const file = await open(tmp, 'wx');
586
+ try { await file.writeFile(bytes); await file.sync(); }
587
+ finally { await file.close(); }
588
+ });
569
589
  await assertVerdictDestination(pkg);
570
590
  await assertCurrent?.();
571
- await rename(tmp, pkg.verdictPath);
572
- } finally { await rm(tmp, { force: true }); }
591
+ await assertPartsUnchanged(pkg);
592
+ await verdictWrite('rename', () => rename(tmp, pkg.verdictPath));
593
+ // Flush the file's entry and every newly created directory's entry in its parent.
594
+ const last = firstCreated ? dirname(firstCreated) : parent;
595
+ for (let directory = parent; ; directory = dirname(directory)) {
596
+ await verdictWrite('directory fsync', async () => {
597
+ const handle = await open(directory, 'r');
598
+ try { await handle.sync(); } finally { await handle.close(); }
599
+ });
600
+ if (directory === last) break;
601
+ }
602
+ } finally { await verdictWrite('temporary cleanup', () => rm(tmp, { force: true })); }
603
+ return {verdict, receipt: {verdictPath: pkg.verdictPath, sha256: createHash('sha256').update(bytes).digest('hex'), status: verdict.status}};
604
+ }
605
+
606
+ /** Shared callers retain the ordinary normalized verdict and produce no save notification. */
607
+ export async function saveVerdict(pkg: PartsViewPackage, input: unknown, assertCurrent?: () => Promise<void>): Promise<PartsVerdict> {
608
+ const {verdict} = await saveVerdictWithReceipt(pkg, input, assertCurrent);
573
609
  return verdict;
574
610
  }
575
611
 
@@ -581,16 +617,42 @@ export type VerdictStale = 'files' | 'flags' | null;
581
617
  * `source.sha256` alone; the page also requires `source.flags`, so a reviewer never sees a sign-off over flags they
582
618
  * were not shown.
583
619
  */
584
- export async function readVerdict(pkg: PartsViewPackage): Promise<{ verdict: PartsVerdict | null; stale: VerdictStale }> {
620
+ async function readVerdictSnapshot(pkg: PartsViewPackage): Promise<{
621
+ verdict: PartsVerdict | null; stale: VerdictStale; by: string | null; savedFileSha256: string | null;
622
+ }> {
585
623
  let raw: unknown;
586
- let text:string;try{text=await readFile(pkg.verdictPath,'utf8');}catch(error){if((error as NodeJS.ErrnoException).code==='ENOENT')return {verdict:null,stale:null};throw new Error('PARTS_VERDICT_READ: saved verdict cannot be read');}
587
- try{raw=JSON.parse(text);}catch{throw new Error('PARTS_VERDICT_INVALID: saved verdict is not valid JSON');}
624
+ const unavailable = {verdict: null, by: null, savedFileSha256: null};
625
+ let bytes: Buffer;
626
+ try { bytes = await readFile(pkg.verdictPath); }
627
+ catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return {...unavailable, stale: null}; throw new Error('PARTS_VERDICT_READ: saved verdict cannot be read'); }
628
+ try{raw=JSON.parse(bytes.toString('utf8'));}catch{throw new Error('PARTS_VERDICT_INVALID: saved verdict is not valid JSON');}
588
629
  const v = record(raw), source = record(v?.source), now = verdictSource(pkg);
589
- if(!v||![PARTS_VERDICT_SCHEMA,'rig-review-parts-verdict/1'].includes(String(v.schema))||typeof source?.sha256!=='string')throw new Error('PARTS_VERDICT_INVALID: saved verdict schema or binding is invalid');
590
- if(v.mode!==pkg.mode||source.sha256!==now.sha256)return {verdict:null,stale:'files'};
591
- if (JSON.stringify(source.flags) !== JSON.stringify(now.flags)) return { verdict: null, stale: 'flags' };
630
+ if(!v||![PARTS_VERDICT_SCHEMA,'rig-review-parts-verdict/1',NAMED_VERDICT_SCHEMA].includes(String(v.schema))||typeof source?.sha256!=='string')throw new Error('PARTS_VERDICT_INVALID: saved verdict schema or binding is invalid');
631
+ let by: string | null = null;
632
+ if (v.schema === NAMED_VERDICT_SCHEMA) {
633
+ if (typeof v.by !== 'string' || !v.by.trim()) refuse('PARTS_VERDICT_INVALID', 'saved reviewer name must be nonblank');
634
+ by = v.by as string;
635
+ }
636
+ if(v.mode!==pkg.mode||source.sha256!==now.sha256)return {...unavailable,stale:'files'};
637
+ if (JSON.stringify(source.flags) !== JSON.stringify(now.flags)) return { ...unavailable, stale: 'flags' };
592
638
  const date=new Date(String(v.updatedAt));if(!Number.isFinite(date.getTime()))throw new Error('PARTS_VERDICT_INVALID: saved verdict date is invalid');
593
- const normalized=buildVerdict(pkg,{...v,comments:v.schema==='rig-review-parts-verdict/1'?[]:v.comments},String(record(v.tool)?.version??''),date);for(const c of normalized.comments)await validateStoredPartsComment(pkg,c);return {verdict:normalized,stale:null};
639
+ const normalized=buildVerdict(pkg,{...v,comments:v.schema==='rig-review-parts-verdict/1'?[]:v.comments},String(record(v.tool)?.version??''),date);
640
+ for(const c of normalized.comments)await validateStoredPartsComment(pkg,c);
641
+ return {verdict:normalized,stale:null,by,savedFileSha256:createHash('sha256').update(bytes).digest('hex')};
642
+ }
643
+
644
+ /** Explicitly project the shared response so retrieval metadata cannot escape through joined wrappers. */
645
+ export async function readVerdict(pkg: PartsViewPackage): Promise<{verdict: PartsVerdict | null; stale: VerdictStale}> {
646
+ const {verdict, stale} = await readVerdictSnapshot(pkg);
647
+ return {verdict, stale};
648
+ }
649
+
650
+ /** Standalone CLI retrieval metadata and content come from one validated saved-file buffer. */
651
+ export async function readPartsVerdictJson(pkg: PartsViewPackage): Promise<string> {
652
+ const saved = await readVerdictSnapshot(pkg);
653
+ if (!saved.verdict) refuse('PARTS_VERDICT_UNAVAILABLE', 'save a verdict first');
654
+ await assertPartsUnchanged(pkg);
655
+ return JSON.stringify({...JSON.parse(exportPartsVerdict(saved.verdict!, 'json')), by: saved.by, savedFileSha256: saved.savedFileSha256}, null, 2) + '\n';
594
656
  }
595
657
 
596
658
  /** What the page reads: no absolute path leaves the server but the verdict file's name. */
package/web/catalog-en.ts CHANGED
@@ -3286,6 +3286,15 @@ export const enCatalog: Readonly<Record<string, string>> = {
3286
3286
  "PARTS_VERDICT_INVALID: saved verdict is not valid JSON": "PARTS_VERDICT_INVALID: saved verdict is not valid JSON",
3287
3287
  "PARTS_VERDICT_INVALID: saved verdict schema or binding is invalid": "PARTS_VERDICT_INVALID: saved verdict schema or binding is invalid",
3288
3288
  "PARTS_VERDICT_INVALID: saved verdict date is invalid": "PARTS_VERDICT_INVALID: saved verdict date is invalid",
3289
+ "PARTS_VERDICT_INVALID: reviewer name must be nonblank": "PARTS_VERDICT_INVALID: reviewer name must be nonblank",
3290
+ "PARTS_VERDICT_INVALID: saved reviewer name must be nonblank": "PARTS_VERDICT_INVALID: saved reviewer name must be nonblank",
3291
+ "PARTS_VERDICT_WRITE_FAILED: {0} ({1})": "PARTS_VERDICT_WRITE_FAILED: {0} ({1})",
3292
+ "PARTS_VERDICT_WRITE_FAILED: server is closing": "PARTS_VERDICT_WRITE_FAILED: server is closing",
3293
+ "PARTS_VERDICT_WRITE_FAILED: save count exhausted": "PARTS_VERDICT_WRITE_FAILED: save count exhausted",
3294
+ "PARTS_VERDICT_NOTIFY_FAILED: durable save notification failed": "PARTS_VERDICT_NOTIFY_FAILED: durable save notification failed",
3295
+ "PARTS_VERDICT_NOTIFY_FAILED: stdout failed": "PARTS_VERDICT_NOTIFY_FAILED: stdout failed",
3296
+ "--by: expected a nonblank reviewer name": "--by: expected a nonblank reviewer name",
3297
+ "--by: launch only; incompatible with export or correction options": "--by: launch only; incompatible with export or correction options",
3289
3298
  "Painting comparison": "Painting comparison",
3290
3299
  "Overlay": "Overlay",
3291
3300
  "Part opacity": "Part opacity",
package/web/catalog-ko.ts CHANGED
@@ -3286,6 +3286,15 @@ export const koCatalog: Readonly<Record<string, string>> = {
3286
3286
  "PARTS_VERDICT_INVALID: saved verdict is not valid JSON": "PARTS_VERDICT_INVALID: 저장된 판정이 올바른 JSON이 아니에요",
3287
3287
  "PARTS_VERDICT_INVALID: saved verdict schema or binding is invalid": "PARTS_VERDICT_INVALID: 저장된 판정의 스키마나 원본 연결이 잘못됐어요",
3288
3288
  "PARTS_VERDICT_INVALID: saved verdict date is invalid": "PARTS_VERDICT_INVALID: 저장된 판정의 날짜가 잘못됐어요",
3289
+ "PARTS_VERDICT_INVALID: reviewer name must be nonblank": "PARTS_VERDICT_INVALID: 검토자 이름은 공백이 아닌 문자열이어야 해요",
3290
+ "PARTS_VERDICT_INVALID: saved reviewer name must be nonblank": "PARTS_VERDICT_INVALID: 저장된 판정의 검토자 이름이 비어 있거나 잘못됐어요",
3291
+ "PARTS_VERDICT_WRITE_FAILED: {0} ({1})": "PARTS_VERDICT_WRITE_FAILED: 판정을 저장하지 못했어요 — {0} ({1})",
3292
+ "PARTS_VERDICT_WRITE_FAILED: server is closing": "PARTS_VERDICT_WRITE_FAILED: 서버가 종료 중이라 판정을 저장할 수 없어요",
3293
+ "PARTS_VERDICT_WRITE_FAILED: save count exhausted": "PARTS_VERDICT_WRITE_FAILED: 저장 횟수 한도에 도달해 판정을 저장할 수 없어요",
3294
+ "PARTS_VERDICT_NOTIFY_FAILED: durable save notification failed": "PARTS_VERDICT_NOTIFY_FAILED: 판정은 저장됐지만 저장 완료 알림을 전달하지 못했어요",
3295
+ "PARTS_VERDICT_NOTIFY_FAILED: stdout failed": "PARTS_VERDICT_NOTIFY_FAILED: 표준 출력(stdout)으로 저장 알림을 기록하지 못했어요",
3296
+ "--by: expected a nonblank reviewer name": "--by: 공백이 아닌 검토자 이름이 필요해요",
3297
+ "--by: launch only; incompatible with export or correction options": "--by: 실행 전용 옵션이라 내보내기 또는 수정 인계 옵션과 함께 쓸 수 없어요",
3289
3298
  "Painting comparison": "원화 비교",
3290
3299
  "Overlay": "오버레이",
3291
3300
  "Part opacity": "파츠 불투명도",