@rig-c/review 2.6.0 → 2.7.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-front.ts CHANGED
@@ -1,16 +1,20 @@
1
1
  /** Disjoint live-job routes. The backend receives the original authenticated Request. */
2
- import { JOB_API_SCHEMA, JOB_ACT_SCHEMA, type JobErrorCode, type JobHostPorts, type JobResult } from './job-contract.ts';
3
- import { createJobHostPorts } from './job-api.ts';
2
+ import { JOB_API_SCHEMA, JOB_ACT_SCHEMA, type JobErrorCode, type JobHostPorts, type JobId, type JobResult, type JobReviewerBinding } from './job-contract.ts';
3
+ import { createJobHostPorts, jobBody, jobHash, jobId, jobObject, jobPartsEnumeratorVersion } from './job-api.ts';
4
4
  import { JobSession } from './job-session.ts';
5
+ import { assertJobRoot, captureJobRoot, type JobRootIdentity } from './job-source.ts';
5
6
  import type { JobWorkerOptions } from './job-worker.ts';
6
- import { JobError } from './job-store.ts';
7
+ import { JobError, JobStore } from './job-store.ts';
7
8
  import { loadReview, safeFile, packagePath, type ReviewPackage } from './manifest.ts';
8
9
  import { serveReference, assertReviewUnchanged } from './reference.ts';
9
10
  import { loadPartsView, partsViewJson, servedImage, type PartsViewPackage } from './parts-view.ts';
10
- import { dirname, join, relative } from 'node:path';
11
+ import { destinationDirectory, DestinationDirectoryError } from './destination-directory.ts';
12
+ import { dirname, isAbsolute, join, relative, sep } from 'node:path';
13
+ import { constants, openSync, closeSync, readSync, fstatSync, lstatSync, statSync, type Stats } from 'node:fs';
11
14
  import { lstat, mkdir, rename, writeFile } from 'node:fs/promises';
12
15
  import { randomUUID } from 'node:crypto';
13
- import { acquireClaim, releaseClaim, running, smallJson } from './open.ts';
16
+ import { acquireClaim, readOpenStatus, releaseClaim, running, smallJson } from './open.ts';
17
+ import { WORKSPACE_BODY_LIMIT } from './open-workspace-contract.ts';
14
18
  import { canonicalStatePath } from './state-dir.ts';
15
19
  const headers = {
16
20
  'Cache-Control': 'no-store',
@@ -302,20 +306,77 @@ export interface JobHostRecord {
302
306
  origin: string;
303
307
  fingerprint: string;
304
308
  pid: number;
309
+ /** Absent on older records or when adding it would exceed the 65,536-byte metadata limit. */
310
+ listenerIncarnation?: string;
305
311
  /** Absent on older records whose hook identity cannot be established. */
306
312
  readerId?: string | null;
307
313
  bindingId?: string | null;
308
314
  }
309
315
 
316
+ export type JobHostListenerIncarnation = string;
317
+
318
+ export interface JobHostReuseBinding {
319
+ readonly root: string;
320
+ readonly stateDir: string;
321
+ readonly fingerprint: string;
322
+ readonly reviewer: JobReviewerBinding;
323
+ readonly readerId: string | null;
324
+ readonly bindingId: string | null;
325
+ readonly partsEnumeratorId: string | null;
326
+ readonly partsEnumeratorVersion: string | null;
327
+ readonly apiSchema: typeof JOB_API_SCHEMA;
328
+ readonly actSchema: typeof JOB_ACT_SCHEMA;
329
+ }
330
+
331
+ export interface JobHostReuseExpectation {
332
+ readonly jobId: JobId;
333
+ readonly origin: string;
334
+ readonly listenerIncarnation: JobHostListenerIncarnation;
335
+ readonly binding: JobHostReuseBinding;
336
+ }
337
+
338
+ export type JobHostAttachField =
339
+ | 'jobId'
340
+ | 'origin'
341
+ | 'listenerIncarnation'
342
+ | 'root'
343
+ | 'stateDir'
344
+ | 'fingerprint'
345
+ | 'reviewer.id'
346
+ | 'reviewer.role'
347
+ | 'readerId'
348
+ | 'bindingId'
349
+ | 'partsEnumeratorId'
350
+ | 'partsEnumeratorVersion'
351
+ | 'apiSchema'
352
+ | 'actSchema'
353
+ | 'port';
354
+
355
+ export type JobHostAttachFailure =
356
+ | {
357
+ readonly code: 'JOB_HOST_ATTACH_REFUSED';
358
+ readonly reason: 'missing' | 'closed' | 'incarnation-missing' | 'replaced' | 'read' | 'probe' | 'stopped' | 'race';
359
+ readonly phase: 'input' | 'state' | 'record' | 'probe' | 'adoption' | 'acceptance';
360
+ }
361
+ | {
362
+ readonly code: 'JOB_HOST_REUSE_MISMATCH';
363
+ readonly field: JobHostAttachField;
364
+ readonly expected: string | null;
365
+ readonly actual: string | null;
366
+ };
367
+
310
368
  /** Callers declare stable hook semantics. Equal IDs permit reuse across processes. */
311
369
  export interface JobHostOptions extends JobWorkerOptions {
312
370
  readonly readerId?: string;
313
371
  readonly bindingId?: string;
314
372
  readonly partsEnumeratorId?: string;
373
+ readonly reuseOnly?: {
374
+ readonly expected: JobHostReuseExpectation;
375
+ };
315
376
  }
316
377
 
317
378
  type JobHostOptionName = 'readPublished' | 'installWriterBinding' | 'partsEnumerator' |
318
- 'partsEnumeratorVersion' | 'apiSchema' | 'actSchema';
379
+ 'partsEnumeratorVersion' | 'apiSchema' | 'actSchema' | JobHostAttachField;
319
380
 
320
381
  class JobHostOptionError extends Error {
321
382
  constructor(
@@ -331,6 +392,23 @@ class JobHostOptionError extends Error {
331
392
  }
332
393
  }
333
394
 
395
+ class JobHostAttachError extends Error {
396
+ readonly code = 'JOB_HOST_ATTACH_REFUSED' as const;
397
+ constructor(
398
+ readonly reason: 'missing' | 'closed' | 'incarnation-missing' | 'replaced' | 'read' | 'probe' | 'stopped' | 'race',
399
+ readonly phase: 'input' | 'state' | 'record' | 'probe' | 'adoption' | 'acceptance',
400
+ ) {
401
+ super(`JOB_HOST_ATTACH_REFUSED: ${reason} (${phase})`);
402
+ this.name = 'JobHostAttachError';
403
+ }
404
+ }
405
+
406
+ function reuseMismatch(field: JobHostAttachField, expected: string | null, actual: string | null):
407
+ Error & {code: 'JOB_HOST_REUSE_MISMATCH'; field: JobHostAttachField; expected: string | null; actual: string | null} {
408
+ return Object.assign(new Error(`JOB_HOST_REUSE_MISMATCH: ${field}`),
409
+ {code: 'JOB_HOST_REUSE_MISMATCH' as const, field, expected, actual});
410
+ }
411
+
334
412
  function declaredHostId(option: JobHostOptionName, hook: unknown, id: string | undefined): string | null {
335
413
  if (hook === undefined && id === undefined) return null;
336
414
  if (typeof hook !== 'function' || typeof id !== 'string' || id.length === 0) {
@@ -345,9 +423,79 @@ export interface JobOwnerHost {
345
423
  readonly origin: string;
346
424
  readonly ownerUrl: string;
347
425
  readonly reused: boolean;
426
+ readonly attachment: JobHostReuseExpectation | null;
348
427
  stop(): void;
349
428
  }
350
429
 
430
+ const UUID_V4_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
431
+ function parseJobHostListenerIncarnation(value: unknown): JobHostListenerIncarnation {
432
+ if (typeof value !== 'string' || !UUID_V4_RE.test(value)) throw new JobError('JOB_REQUEST_INVALID');
433
+ return value;
434
+ }
435
+
436
+ function isPlainObject(value: unknown): value is Record<string, unknown> {
437
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return false;
438
+ const proto = Object.getPrototypeOf(value);
439
+ return proto === Object.prototype || proto === null;
440
+ }
441
+
442
+ function exactKeys(value: unknown, allowed: readonly string[]): Record<string, unknown> {
443
+ if (!isPlainObject(value)) throw new JobError('JOB_REQUEST_INVALID');
444
+ const keys = Reflect.ownKeys(value);
445
+ if (keys.length !== allowed.length || keys.some(key => typeof key !== 'string' || !allowed.includes(key))) {
446
+ throw new JobError('JOB_REQUEST_INVALID');
447
+ }
448
+ return ownData(value);
449
+ }
450
+
451
+ function ownData(value: unknown): Record<string, unknown> {
452
+ if (!isPlainObject(value)) throw new JobError('JOB_REQUEST_INVALID');
453
+ const copy: Record<string, unknown> = {};
454
+ for (const key of Reflect.ownKeys(value)) {
455
+ const descriptor = Object.getOwnPropertyDescriptor(value, key)!;
456
+ if (typeof key !== 'string' || !('value' in descriptor)) throw new JobError('JOB_REQUEST_INVALID');
457
+ Object.defineProperty(copy, key, {value: descriptor.value, enumerable: true, configurable: true, writable: true});
458
+ }
459
+ return copy;
460
+ }
461
+
462
+ function parseLoopbackOrigin(raw: unknown): {port: string; origin: string} {
463
+ if (typeof raw !== 'string') throw new JobError('JOB_REQUEST_INVALID');
464
+ const match = /^http:\/\/127\.0\.0\.1:([1-9][0-9]{0,4})$/.exec(raw);
465
+ if (!match || Number(match[1]) > 65535) throw new JobError('JOB_REQUEST_INVALID');
466
+ return {port: match[1]!, origin: new URL(raw).origin};
467
+ }
468
+
469
+ function withinPath(root: string, target: string): boolean {
470
+ const rel = relative(root, target);
471
+ return !rel || rel !== '..' && !rel.startsWith('..' + sep) && !isAbsolute(rel);
472
+ }
473
+
474
+ function freezeExpectation(value: JobHostReuseExpectation): JobHostReuseExpectation {
475
+ const reviewer: JobReviewerBinding = Object.freeze({
476
+ id: value.binding.reviewer.id,
477
+ role: value.binding.reviewer.role,
478
+ });
479
+ const binding: JobHostReuseBinding = Object.freeze({
480
+ root: value.binding.root,
481
+ stateDir: value.binding.stateDir,
482
+ fingerprint: value.binding.fingerprint,
483
+ reviewer,
484
+ readerId: value.binding.readerId,
485
+ bindingId: value.binding.bindingId,
486
+ partsEnumeratorId: value.binding.partsEnumeratorId,
487
+ partsEnumeratorVersion: value.binding.partsEnumeratorVersion,
488
+ apiSchema: value.binding.apiSchema,
489
+ actSchema: value.binding.actSchema,
490
+ });
491
+ return Object.freeze({
492
+ jobId: value.jobId,
493
+ origin: value.origin,
494
+ listenerIncarnation: value.listenerIncarnation,
495
+ binding,
496
+ });
497
+ }
498
+
351
499
  export function jobHostIdentity(startup: JobHostOptions) {
352
500
  const readerId = declaredHostId('readPublished', startup.readPublished, startup.readerId);
353
501
  const bindingId = declaredHostId('installWriterBinding', startup.installWriterBinding, startup.bindingId);
@@ -376,38 +524,617 @@ export function assertJobHostCompatible(record: JobHostRecord, identity: ReturnT
376
524
  }
377
525
  }
378
526
 
379
- /** One live job request context. Its caller owns the listener and session lifetime. */
527
+ function buildAttachment(session: JobSession, origin: string, listenerIncarnation: string,
528
+ identity: ReturnType<typeof jobHostIdentity>): JobHostReuseExpectation {
529
+ const live = session.attestation();
530
+ assertJobRoot(live.root);
531
+ if (live.status !== 'active') throw new JobHostAttachError('closed', 'acceptance');
532
+ return freezeExpectation({jobId: session.jobId, origin, listenerIncarnation, binding: {
533
+ root: live.root.path, stateDir: live.stateDir, fingerprint: live.fingerprint,
534
+ reviewer: live.reviewer, ...identity, apiSchema: live.apiSchema, actSchema: live.actSchema,
535
+ }});
536
+ }
537
+
538
+ type ObservedFileIdentity = {readonly dev: number; readonly ino: number};
539
+ type ObservedFiles = {readonly root: ObservedFileIdentity; readonly stateDir: ObservedFileIdentity;
540
+ readonly store: ObservedFileIdentity; readonly record: ObservedFileIdentity};
541
+ const observedFields = ['root', 'stateDir', 'store', 'record'] as const;
542
+ function fileIdentity(info: ObservedFileIdentity): ObservedFileIdentity { return {dev: info.dev, ino: info.ino}; }
543
+ function sameFile(a: ObservedFileIdentity, b: ObservedFileIdentity): boolean {return a.dev === b.dev && a.ino === b.ino;}
544
+ function observeFiles(expected: JobHostReuseExpectation): ObservedFiles {
545
+ const paths = {root: expected.binding.root, stateDir: expected.binding.stateDir,
546
+ store: join(expected.binding.stateDir, 'jobs.sqlite'),
547
+ record: join(expected.binding.stateDir, 'job-ui', expected.jobId + '.json')};
548
+ const values = {} as Record<typeof observedFields[number], ObservedFileIdentity>;
549
+ for (const key of observedFields) {
550
+ const info = lstatSync(paths[key]);
551
+ if (key === 'root') {if (!info.isDirectory()) throw new JobHostAttachError('replaced', 'acceptance');}
552
+ else assertPrivateStat(info, key === 'stateDir', 'acceptance');
553
+ values[key] = fileIdentity(info);
554
+ }
555
+ return values;
556
+ }
557
+ function parseObserved(raw: unknown): ObservedFiles {
558
+ const input = exactKeys(raw, observedFields), output = {} as Record<typeof observedFields[number], ObservedFileIdentity>;
559
+ for (const key of observedFields) {
560
+ const item = exactKeys(input[key], ['dev', 'ino']);
561
+ if (!Number.isSafeInteger(item.dev) || (item.dev as number) < 0 ||
562
+ !Number.isSafeInteger(item.ino) || (item.ino as number) < 0) throw new JobError('JOB_REQUEST_INVALID');
563
+ output[key] = {dev: item.dev as number, ino: item.ino as number};
564
+ }
565
+ return output;
566
+ }
567
+ function compareAttachment(expected: JobHostReuseExpectation, actual: JobHostReuseExpectation): void {
568
+ for (const field of ['jobId', 'origin', 'listenerIncarnation'] as const) {
569
+ if (expected[field] !== actual[field]) throw reuseMismatch(field, expected[field], actual[field]);
570
+ }
571
+ for (const field of ['root', 'stateDir', 'fingerprint'] as const) {
572
+ if (expected.binding[field] !== actual.binding[field]) throw reuseMismatch(field, expected.binding[field], actual.binding[field]);
573
+ }
574
+ for (const field of ['id', 'role'] as const) {
575
+ if (expected.binding.reviewer[field] !== actual.binding.reviewer[field]) {
576
+ throw reuseMismatch(`reviewer.${field}`, expected.binding.reviewer[field], actual.binding.reviewer[field]);
577
+ }
578
+ }
579
+ for (const field of ['readerId', 'bindingId', 'partsEnumeratorId', 'partsEnumeratorVersion', 'apiSchema', 'actSchema'] as const) {
580
+ if (expected.binding[field] !== actual.binding[field]) throw reuseMismatch(field, expected.binding[field], actual.binding[field]);
581
+ }
582
+ }
583
+ function attachFailure(error: unknown): Response {
584
+ if (error instanceof JobHostAttachError) return Response.json({ok: false,
585
+ error: {code: error.code, reason: error.reason, phase: error.phase}},
586
+ {status: error.reason === 'stopped' ? 503 : 409, headers});
587
+ if ((error as {code?: string})?.code === 'JOB_HOST_REUSE_MISMATCH') {
588
+ const {field, expected, actual} = error as Extract<JobHostAttachFailure, {field: unknown}>;
589
+ return Response.json({ok: false, error: {code: 'JOB_HOST_REUSE_MISMATCH', field, expected, actual}}, {status: 409, headers});
590
+ }
591
+ const code = error instanceof JobError ? error.code : 'JOB_REQUEST_INVALID';
592
+ return failure(code, code === 'JOB_BODY_LIMIT' ? 413 : ['JOB_CAPABILITY_REQUIRED', 'JOB_AUTHORITY_REFUSED'].includes(code) ? 403 : 400);
593
+ }
594
+
595
+ /** One live job request context. Its caller publishes it only after descriptor installation. */
380
596
  export function createJobRequestContext(session: JobSession, startup: JobHostOptions, origin: string,
381
- identity: ReturnType<typeof jobHostIdentity>, resource = jobWindowResources(), hubIncarnation?: string) {
382
- const ports = createJobHostPorts(session, origin);
597
+ identity: ReturnType<typeof jobHostIdentity>, resource = jobWindowResources(), hubIncarnation?: string,
598
+ listenerIncarnation: string = hubIncarnation ?? randomUUID(), accepting: () => boolean = () => true) {
599
+ const ports = createJobHostPorts(session, new URL(origin).origin);
600
+ // This legacy GET projection and its property order are deliberately unchanged.
383
601
  const record: JobHostRecord = {schema: 'rig-review-job-host/1', apiSchema: JOB_API_SCHEMA, actSchema: JOB_ACT_SCHEMA,
384
602
  ...identity, jobId: session.jobId, origin, fingerprint: startup.fingerprint, pid: process.pid};
385
603
  const front = createJobFront({origin, ports, resource, hubIncarnation, publication: retainedPublicationRoutes(session)});
386
- let requests = 0;
604
+ let requests = 0, stopped = false, published = false;
605
+ let captured: ObservedFiles;
606
+ let descriptorBytes: string;
607
+ const normalizedOrigin = new URL(origin).origin;
608
+ function descriptor(): {readonly record: JobHostRecord; readonly hasIncarnation: boolean} {
609
+ const withIncarnation = {...record, listenerIncarnation};
610
+ if (Buffer.byteLength(JSON.stringify(withIncarnation)) <= WORKSPACE_BODY_LIMIT) return {record: withIncarnation, hasIncarnation: true};
611
+ return {record: {...record}, hasIncarnation: false};
612
+ }
613
+ function attachment(): JobHostReuseExpectation | null {
614
+ if (!published || stopped || !accepting() || !descriptor().hasIncarnation) return null;
615
+ try {
616
+ const value = buildAttachment(session, origin, listenerIncarnation, identity);
617
+ return Buffer.byteLength(JSON.stringify({expected: value, observed: captured})) <= WORKSPACE_BODY_LIMIT &&
618
+ Buffer.byteLength(JSON.stringify({ok: true, attachment: value, pid: process.pid})) <= WORKSPACE_BODY_LIMIT ? value : null;
619
+ } catch {return null;}
620
+ }
387
621
  return {
388
- ports, record,
622
+ ports, record, listenerIncarnation, descriptor, attachment,
623
+ // Embedded owners already hold the binding; its public tuple remains available
624
+ // even when a compact descriptor cannot carry strict transport metadata.
625
+ ownerAttachment: () => buildAttachment(session, origin, listenerIncarnation, identity),
626
+ publish() {
627
+ if (!descriptor().hasIncarnation) {published = true; return;}
628
+ const value = buildAttachment(session, origin, listenerIncarnation, identity);
629
+ captured = observeFiles(value);
630
+ descriptorBytes = readDescriptor(join(value.binding.stateDir, 'job-ui', value.jobId + '.json')).bytes;
631
+ published = true;
632
+ },
389
633
  get busy() {return requests > 0 || session.busy;},
390
634
  async fetch(request: Request): Promise<Response> {
391
635
  requests++;
392
636
  try {
393
637
  const url = new URL(request.url);
394
638
  if (url.pathname === `/jobs/${session.jobId}/host`) {
395
- if (url.origin !== origin || request.method !== 'GET' || url.search ||
396
- request.headers.get('sec-fetch-site') === 'cross-site' ||
397
- request.headers.get('origin') !== null && request.headers.get('origin') !== origin) return failure('JOB_REQUEST_INVALID', 403);
398
- try {session.authorize('ui', request.headers.get('X-Review-Capability'));}
399
- catch {return failure('JOB_CAPABILITY_REQUIRED', 403);}
400
- return Response.json(record, {headers});
639
+ if (url.origin !== normalizedOrigin || url.search || request.headers.get('sec-fetch-site') === 'cross-site' ||
640
+ request.headers.get('origin') !== null && request.headers.get('origin') !== normalizedOrigin) return failure('JOB_REQUEST_INVALID', 403);
641
+ if (request.method === 'GET') {
642
+ try {session.authorize('ui', request.headers.get('X-Review-Capability'));}
643
+ catch {return failure('JOB_CAPABILITY_REQUIRED', 403);}
644
+ return Response.json(record, {headers});
645
+ }
646
+ if (request.method === 'POST') {
647
+ if (request.headers.get('origin') !== normalizedOrigin) return failure('JOB_SAME_ORIGIN_REQUIRED', 403);
648
+ try {
649
+ if (request.headers.get('content-type') !== 'application/json') throw new JobError('JOB_REQUEST_INVALID');
650
+ const body = exactKeys(await jobBody(request, WORKSPACE_BODY_LIMIT), ['expected', 'observed']);
651
+ const expected = parseReuseOnlyExpectation({expected: body.expected}), observed = parseObserved(body.observed);
652
+ const live = () => {if (stopped || !published || !accepting()) throw new JobHostAttachError('stopped', 'acceptance');
653
+ if (request.signal.aborted) throw new JobHostAttachError('probe', 'acceptance');};
654
+ live();
655
+ const payload = session.inspectAttach(() => {
656
+ live();
657
+ try {session.authorize('ui', request.headers.get('X-Review-Capability'));}
658
+ catch (error) {if (error instanceof JobError && error.code === 'JOB_CLOSED') throw new JobHostAttachError('closed', 'acceptance'); throw error;}
659
+ const actual = buildAttachment(session, origin, listenerIncarnation, identity);
660
+ compareAttachment(expected, actual);
661
+ if (!descriptor().hasIncarnation) throw new JobHostAttachError('incarnation-missing', 'acceptance');
662
+ const current = observeFiles(actual);
663
+ for (const key of observedFields) {
664
+ if (!sameFile(current[key], captured[key]) || !sameFile(observed[key], captured[key])) throw new JobHostAttachError('replaced', 'acceptance');
665
+ }
666
+ const path = join(actual.binding.stateDir, 'job-ui', actual.jobId + '.json');
667
+ if (readDescriptor(path).bytes !== descriptorBytes) throw new JobHostAttachError('replaced', 'acceptance');
668
+ live();
669
+ const value = Object.freeze({ok: true as const, attachment: actual, pid: process.pid});
670
+ if (Buffer.byteLength(JSON.stringify(value)) > WORKSPACE_BODY_LIMIT) throw new JobError('JOB_BODY_LIMIT');
671
+ return value;
672
+ });
673
+ return Response.json(payload, {headers});
674
+ } catch (error) {
675
+ if (error instanceof JobError && ['JOB_STORAGE_FAILED', 'JOB_ROOT_REPLACED'].includes(error.code) ||
676
+ ['ENOENT', 'ENOTDIR', 'ELOOP'].includes((error as NodeJS.ErrnoException)?.code ?? '')) {
677
+ return attachFailure(new JobHostAttachError('replaced', 'acceptance'));
678
+ }
679
+ return attachFailure(error);
680
+ }
681
+ }
682
+ return failure('JOB_REQUEST_INVALID', 403);
401
683
  }
402
684
  return await front.fetch(request) ?? failure('JOB_REQUEST_INVALID', 404);
403
685
  } finally {requests--;}
404
686
  },
405
- stop() {front.stop();},
687
+ stop() {stopped = true; front.stop();},
688
+ };
689
+ }
690
+
691
+ function readDescriptor(path: string): {value: Record<string, unknown>; bytes: string; info: Stats} {
692
+ const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
693
+ try {
694
+ const before = fstatSync(fd); assertPrivateStat(before, false, 'record');
695
+ if (!before.size || before.size > WORKSPACE_BODY_LIMIT) throw new JobHostAttachError('read', 'record');
696
+ const buffer = Buffer.alloc(before.size + 1);
697
+ let length = 0;
698
+ while (length < buffer.length) {const count = readSync(fd, buffer, length, buffer.length - length, length); if (!count) break; length += count;}
699
+ const after = fstatSync(fd);
700
+ if (length !== before.size || before.size !== after.size || before.mtimeMs !== after.mtimeMs) throw new JobHostAttachError('read', 'record');
701
+ const bytes = new TextDecoder('utf-8', {fatal: true}).decode(buffer.subarray(0, length)), value: unknown = JSON.parse(bytes);
702
+ if (!isPlainObject(value)) throw new JobHostAttachError('read', 'record');
703
+ return {value, bytes, info: before};
704
+ } finally {closeSync(fd);}
705
+ }
706
+
707
+ interface StoredAttachJobData {
708
+ apiSchema: string;
709
+ actSchema: string;
710
+ root: JobRootIdentity;
711
+ fingerprint: string;
712
+ reviewer: JobReviewerBinding;
713
+ agentCapability: string;
714
+ uiCapability: string;
715
+ fetchCapability: string | null;
716
+ }
717
+
718
+ function parseReuseOnlyExpectation(rawReuseOnly: unknown, requireSchemas = true): JobHostReuseExpectation {
719
+ const wrapper = exactKeys(rawReuseOnly, ['expected']);
720
+ const exp = exactKeys(wrapper.expected, ['jobId', 'origin', 'listenerIncarnation', 'binding']);
721
+ const bind = exactKeys(exp.binding, [
722
+ 'root', 'stateDir', 'fingerprint', 'reviewer',
723
+ 'readerId', 'bindingId', 'partsEnumeratorId', 'partsEnumeratorVersion',
724
+ 'apiSchema', 'actSchema',
725
+ ]);
726
+ const rev = exactKeys(bind.reviewer, ['id', 'role']);
727
+ const parsedJobId = jobId(exp.jobId);
728
+ parseLoopbackOrigin(exp.origin);
729
+ const incarnation = parseJobHostListenerIncarnation(exp.listenerIncarnation);
730
+ if (typeof bind.root !== 'string' || !bind.root || bind.root.includes('\0') || !isAbsolute(bind.root) || join(bind.root) !== bind.root ||
731
+ typeof bind.stateDir !== 'string' || !bind.stateDir || bind.stateDir.includes('\0') || !isAbsolute(bind.stateDir) || join(bind.stateDir) !== bind.stateDir ||
732
+ typeof bind.fingerprint !== 'string' || !bind.fingerprint ||
733
+ typeof rev.id !== 'string' || !rev.id ||
734
+ (rev.role !== 'owner' && rev.role !== 'delegate')) {
735
+ throw new JobError('JOB_REQUEST_INVALID');
736
+ }
737
+ for (const key of ['readerId', 'bindingId', 'partsEnumeratorId'] as const) {
738
+ const val = bind[key];
739
+ if (val !== null && (typeof val !== 'string' || !val)) {
740
+ throw new JobError('JOB_REQUEST_INVALID');
741
+ }
742
+ }
743
+ if (bind.partsEnumeratorId === null) {
744
+ if (bind.partsEnumeratorVersion !== null) throw new JobError('JOB_REQUEST_INVALID');
745
+ } else {
746
+ if (typeof bind.partsEnumeratorVersion !== 'string' || !bind.partsEnumeratorVersion) {
747
+ throw new JobError('JOB_REQUEST_INVALID');
748
+ }
749
+ try { jobPartsEnumeratorVersion(bind.partsEnumeratorVersion); }
750
+ catch { throw new JobError('JOB_REQUEST_INVALID'); }
751
+ }
752
+ if (typeof bind.apiSchema !== 'string' || typeof bind.actSchema !== 'string' ||
753
+ requireSchemas && (bind.apiSchema !== JOB_API_SCHEMA || bind.actSchema !== JOB_ACT_SCHEMA)) {
754
+ throw new JobError('JOB_REQUEST_INVALID');
755
+ }
756
+ return freezeExpectation({
757
+ jobId: parsedJobId,
758
+ origin: exp.origin as string,
759
+ listenerIncarnation: incarnation,
760
+ binding: {
761
+ root: bind.root,
762
+ stateDir: bind.stateDir,
763
+ fingerprint: bind.fingerprint,
764
+ reviewer: { id: rev.id, role: rev.role },
765
+ readerId: bind.readerId as string | null,
766
+ bindingId: bind.bindingId as string | null,
767
+ partsEnumeratorId: bind.partsEnumeratorId as string | null,
768
+ partsEnumeratorVersion: bind.partsEnumeratorVersion as string | null,
769
+ apiSchema: bind.apiSchema as typeof JOB_API_SCHEMA,
770
+ actSchema: bind.actSchema as typeof JOB_ACT_SCHEMA,
771
+ },
772
+ });
773
+ }
774
+
775
+ function assertPrivateStat(info: Stats, directory: boolean, phase: 'state' | 'record' | 'adoption' | 'acceptance'): void {
776
+ if (info.isSymbolicLink() || !(directory ? info.isDirectory() : info.isFile()) ||
777
+ (info.mode & 0o077) !== 0 || (!directory && info.nlink !== 1) ||
778
+ (typeof process.getuid === 'function' && info.uid !== process.getuid())) {
779
+ throw new JobHostAttachError('read', phase);
780
+ }
781
+ }
782
+
783
+ function assertNoSqliteSidecars(sqliteFile: string, phase: 'state' | 'adoption'): void {
784
+ for (const suffix of ['-journal', '-wal', '-shm']) {
785
+ try {
786
+ lstatSync(sqliteFile + suffix);
787
+ throw new JobHostAttachError('read', phase);
788
+ } catch (error) {
789
+ if (error instanceof JobHostAttachError) throw error;
790
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
791
+ throw new JobHostAttachError('read', phase);
792
+ }
793
+ }
794
+ }
795
+ }
796
+
797
+ async function attachJobHost(options: JobHostOptions): Promise<JobOwnerHost> {
798
+ // Step 1 (phase: 'input'): Validate reuseOnly and top-level options before any filesystem or store work.
799
+ const expected = parseReuseOnlyExpectation(options.reuseOnly);
800
+ const rootInput = options.root;
801
+ const stateInput = options.stateDir;
802
+ const fingerprint = options.fingerprint;
803
+ if (typeof rootInput !== 'string' || !rootInput || rootInput.includes('\0') ||
804
+ typeof stateInput !== 'string' || !stateInput || stateInput.includes('\0') ||
805
+ typeof fingerprint !== 'string' || !fingerprint) {
806
+ throw new JobError('JOB_REQUEST_INVALID');
807
+ }
808
+ if (!options.reviewer || typeof options.reviewer !== 'object' ||
809
+ typeof options.reviewer.id !== 'string' || !options.reviewer.id ||
810
+ !['owner', 'delegate'].includes(options.reviewer.role)) {
811
+ throw new JobError('JOB_AUTHORITY_REFUSED');
812
+ }
813
+ const reviewerData = exactKeys(options.reviewer, ['id', 'role']);
814
+ const reviewer: JobReviewerBinding = {id: reviewerData.id as string, role: reviewerData.role as JobReviewerBinding['role']};
815
+ const port = options.port;
816
+ if (port !== undefined && (!Number.isSafeInteger(port) || port < 0 || port > 65535)) {
817
+ throw new JobError('JOB_REQUEST_INVALID');
818
+ }
819
+ const identity = jobHostIdentity(options);
820
+ if (options.partsEnumerator) jobPartsEnumeratorVersion(options.partsEnumerator.version);
821
+ const sanitizedStartup: JobHostOptions = {
822
+ root: rootInput,
823
+ stateDir: stateInput,
824
+ fingerprint,
825
+ reviewer,
826
+ ...(port !== undefined ? { port } : {}),
827
+ ...(options.readPublished ? { readPublished: options.readPublished, readerId: identity.readerId! } : {}),
828
+ ...(options.installWriterBinding ? { installWriterBinding: options.installWriterBinding, bindingId: identity.bindingId! } : {}),
829
+ ...(options.partsEnumerator ? { partsEnumerator: {...options.partsEnumerator}, partsEnumeratorId: identity.partsEnumeratorId! } : {}),
830
+ ...(options.afterSnapshot ? { afterSnapshot: options.afterSnapshot } : {}),
831
+ ...(options.afterDirectorySync ? { afterDirectorySync: options.afterDirectorySync } : {}),
406
832
  };
833
+
834
+ // Step 2 (phase: 'input' / 'state'): Canonical path resolution, disjointness, and options vs expected comparison.
835
+ const root = captureJobRoot(rootInput);
836
+ const stateCandidate = canonicalStatePath(stateInput);
837
+ if (withinPath(root.path, stateCandidate)) {
838
+ throw new JobError('JOB_SOURCE_UNRETAINABLE', 'Job state must be outside the designated work root');
839
+ }
840
+ if (withinPath(stateCandidate, root.path)) {
841
+ throw new JobError('JOB_SOURCE_UNRETAINABLE', 'The designated work root must be outside job state');
842
+ }
843
+ let state: string;
844
+ try {
845
+ state = destinationDirectory(stateInput, 'STATE_DIRECTORY_INVALID', false);
846
+ } catch (error) {
847
+ if (error instanceof DestinationDirectoryError) {
848
+ const causeCode = (error.cause as NodeJS.ErrnoException | undefined)?.code;
849
+ if (causeCode === 'ENOENT') throw new JobHostAttachError('missing', 'state');
850
+ throw new JobError('JOB_SOURCE_UNRETAINABLE', error.message);
851
+ }
852
+ throw error;
853
+ }
854
+ let stateInfo: Stats;
855
+ let stateRealInfo: Stats;
856
+ try {
857
+ stateInfo = lstatSync(stateInput);
858
+ stateRealInfo = statSync(state);
859
+ } catch (error) {
860
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') throw new JobHostAttachError('missing', 'state');
861
+ throw new JobHostAttachError('read', 'state');
862
+ }
863
+ if (stateInfo.isSymbolicLink() || stateInfo.dev !== stateRealInfo.dev || stateInfo.ino !== stateRealInfo.ino) {
864
+ throw new JobError('JOB_SOURCE_UNRETAINABLE', 'STATE_DIRECTORY_INVALID');
865
+ }
866
+ assertPrivateStat(stateInfo, true, 'state');
867
+
868
+ if (root.path !== expected.binding.root) throw reuseMismatch('root', expected.binding.root, root.path);
869
+ if (state !== expected.binding.stateDir) throw reuseMismatch('stateDir', expected.binding.stateDir, state);
870
+ if (fingerprint !== expected.binding.fingerprint) throw reuseMismatch('fingerprint', expected.binding.fingerprint, fingerprint);
871
+ if (reviewer.id !== expected.binding.reviewer.id) throw reuseMismatch('reviewer.id', expected.binding.reviewer.id, reviewer.id);
872
+ if (reviewer.role !== expected.binding.reviewer.role) throw reuseMismatch('reviewer.role', expected.binding.reviewer.role, reviewer.role);
873
+ if (identity.readerId !== expected.binding.readerId) throw reuseMismatch('readerId', expected.binding.readerId, identity.readerId);
874
+ if (identity.bindingId !== expected.binding.bindingId) throw reuseMismatch('bindingId', expected.binding.bindingId, identity.bindingId);
875
+ if (identity.partsEnumeratorId !== expected.binding.partsEnumeratorId) {
876
+ throw reuseMismatch('partsEnumeratorId', expected.binding.partsEnumeratorId, identity.partsEnumeratorId);
877
+ }
878
+ if (identity.partsEnumeratorVersion !== expected.binding.partsEnumeratorVersion) {
879
+ throw reuseMismatch('partsEnumeratorVersion', expected.binding.partsEnumeratorVersion, identity.partsEnumeratorVersion);
880
+ }
881
+ const expectedPort = parseLoopbackOrigin(expected.origin).port;
882
+ if (port !== undefined && String(port) !== expectedPort) {
883
+ throw reuseMismatch('port', expectedPort, String(port));
884
+ }
885
+
886
+ // Step 3 (phase: 'state'): Read-only SQLite inspection without WAL/SHM/journal side effects.
887
+ const sqliteFile = join(state, 'jobs.sqlite');
888
+ let sqliteInfo: Stats;
889
+ try {
890
+ sqliteInfo = lstatSync(sqliteFile);
891
+ } catch (error) {
892
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') throw new JobHostAttachError('missing', 'state');
893
+ throw new JobHostAttachError('read', 'state');
894
+ }
895
+ assertPrivateStat(sqliteInfo, false, 'state');
896
+ assertNoSqliteSidecars(sqliteFile, 'state');
897
+
898
+ const rootKey = jobHash(JSON.stringify([root.path, expected.binding.fingerprint]));
899
+ let store: JobStore<StoredAttachJobData>;
900
+ try {
901
+ store = new JobStore<StoredAttachJobData>(state, { readonly: true });
902
+ } catch {
903
+ throw new JobHostAttachError('read', 'state');
904
+ }
905
+ let uiCapability: string, inspectedRevision: number;
906
+ try {
907
+ let row: ReturnType<JobStore<StoredAttachJobData>['get']>;
908
+ try {
909
+ row = store.inspect(() => store.get(expected.jobId));
910
+ } catch (error) {
911
+ if (error instanceof JobError && error.code === 'JOB_UNKNOWN') {
912
+ throw new JobHostAttachError('missing', 'state');
913
+ }
914
+ throw new JobHostAttachError('read', 'state');
915
+ }
916
+ const data = row.data;
917
+ if (!data || typeof data !== 'object' || !data.root || typeof data.root.path !== 'string' ||
918
+ typeof data.fingerprint !== 'string' || typeof data.apiSchema !== 'string' || typeof data.actSchema !== 'string' || !data.reviewer ||
919
+ typeof data.reviewer.id !== 'string' || typeof data.reviewer.role !== 'string') {
920
+ throw new JobHostAttachError('read', 'state');
921
+ }
922
+ if (data.root.path !== expected.binding.root) throw reuseMismatch('root', expected.binding.root, data.root.path);
923
+ if (data.fingerprint !== expected.binding.fingerprint) throw reuseMismatch('fingerprint', expected.binding.fingerprint, data.fingerprint);
924
+ if (data.reviewer.id !== expected.binding.reviewer.id) throw reuseMismatch('reviewer.id', expected.binding.reviewer.id, data.reviewer.id);
925
+ if (data.reviewer.role !== expected.binding.reviewer.role) throw reuseMismatch('reviewer.role', expected.binding.reviewer.role, data.reviewer.role);
926
+ if (data.apiSchema !== expected.binding.apiSchema) {
927
+ throw reuseMismatch('apiSchema', expected.binding.apiSchema, typeof data.apiSchema === 'string' ? data.apiSchema : null);
928
+ }
929
+ if (data.actSchema !== expected.binding.actSchema) {
930
+ throw reuseMismatch('actSchema', expected.binding.actSchema, typeof data.actSchema === 'string' ? data.actSchema : null);
931
+ }
932
+ if (data.root.dev !== root.dev || data.root.ino !== root.ino) {
933
+ throw new JobHostAttachError('replaced', 'state');
934
+ }
935
+ try { assertJobRoot(data.root); }
936
+ catch { throw new JobHostAttachError('replaced', 'state'); }
937
+ if (!row.active) throw new JobHostAttachError('closed', 'state');
938
+ if (row.rootKey !== rootKey ||
939
+ typeof data.uiCapability !== 'string' || !/^[a-f0-9]{64}$/.test(data.uiCapability) ||
940
+ typeof data.agentCapability !== 'string' || !/^[a-f0-9]{64}$/.test(data.agentCapability)) {
941
+ throw new JobHostAttachError('read', 'state');
942
+ }
943
+ uiCapability = data.uiCapability; inspectedRevision = row.revision;
944
+ } finally {
945
+ store.close();
946
+ }
947
+
948
+ // Step 4 (phase: 'record'): Verify job-ui/<jobId>.json metadata, fields, and PID liveness.
949
+ const control = join(state, 'job-ui');
950
+ let controlInfo: Stats;
951
+ try {
952
+ controlInfo = lstatSync(control);
953
+ } catch (error) {
954
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') throw new JobHostAttachError('missing', 'record');
955
+ throw new JobHostAttachError('read', 'record');
956
+ }
957
+ assertPrivateStat(controlInfo, true, 'record');
958
+ const recordPath = join(control, expected.jobId + '.json');
959
+ let recordInfo: Stats;
960
+ try {
961
+ recordInfo = lstatSync(recordPath);
962
+ } catch (error) {
963
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') throw new JobHostAttachError('missing', 'record');
964
+ throw new JobHostAttachError('read', 'record');
965
+ }
966
+ assertPrivateStat(recordInfo, false, 'record');
967
+ if (recordInfo.size > WORKSPACE_BODY_LIMIT) throw new JobHostAttachError('read', 'record');
968
+ let recordBytes: string, descriptor: Record<string, unknown>;
969
+ try {
970
+ const read = readDescriptor(recordPath);
971
+ if (!sameFile(read.info, recordInfo)) throw new JobHostAttachError('replaced', 'record');
972
+ recordBytes = read.bytes; descriptor = read.value;
973
+ } catch (error) {
974
+ if (error instanceof JobHostAttachError) throw error;
975
+ throw new JobHostAttachError('read', 'record');
976
+ }
977
+ if (descriptor.schema !== 'rig-review-job-host/1' ||
978
+ typeof descriptor.pid !== 'number' || !Number.isSafeInteger(descriptor.pid) || descriptor.pid <= 0 ||
979
+ typeof descriptor.jobId !== 'string' || !descriptor.jobId ||
980
+ typeof descriptor.origin !== 'string' || !descriptor.origin ||
981
+ typeof descriptor.fingerprint !== 'string' || !descriptor.fingerprint) {
982
+ throw new JobHostAttachError('read', 'record');
983
+ }
984
+ let descriptorOrigin: ReturnType<typeof parseLoopbackOrigin>;
985
+ try { descriptorOrigin = parseLoopbackOrigin(descriptor.origin); }
986
+ catch { throw new JobHostAttachError('read', 'record'); }
987
+ if (descriptor.jobId !== expected.jobId) throw reuseMismatch('jobId', expected.jobId, descriptor.jobId);
988
+ if (descriptor.origin !== expected.origin) throw reuseMismatch('origin', expected.origin, descriptor.origin);
989
+ if (!Object.hasOwn(descriptor, 'listenerIncarnation') || descriptor.listenerIncarnation === undefined) {
990
+ throw new JobHostAttachError('incarnation-missing', 'record');
991
+ }
992
+ if (typeof descriptor.listenerIncarnation !== 'string' || !UUID_V4_RE.test(descriptor.listenerIncarnation)) throw new JobHostAttachError('read', 'record');
993
+ if (descriptor.listenerIncarnation !== expected.listenerIncarnation) {
994
+ throw reuseMismatch('listenerIncarnation', expected.listenerIncarnation, descriptor.listenerIncarnation);
995
+ }
996
+ if (descriptor.fingerprint !== expected.binding.fingerprint) {
997
+ throw reuseMismatch('fingerprint', expected.binding.fingerprint, descriptor.fingerprint);
998
+ }
999
+ for (const field of ['readerId', 'bindingId', 'partsEnumeratorId', 'partsEnumeratorVersion'] as const) {
1000
+ const val = descriptor[field];
1001
+ if (!Object.hasOwn(descriptor, field) || val !== null && (typeof val !== 'string' || !val)) {
1002
+ throw new JobHostAttachError('read', 'record');
1003
+ }
1004
+ if (val !== expected.binding[field]) {
1005
+ throw reuseMismatch(field, expected.binding[field], (val ?? null) as string | null);
1006
+ }
1007
+ }
1008
+ for (const field of ['apiSchema', 'actSchema'] as const) {
1009
+ const val = descriptor[field];
1010
+ if (typeof val !== 'string' || !val) {
1011
+ throw new JobHostAttachError('read', 'record');
1012
+ }
1013
+ if (val !== expected.binding[field]) {
1014
+ throw reuseMismatch(field, expected.binding[field], (val ?? null) as string | null);
1015
+ }
1016
+ }
1017
+ if (port !== undefined && descriptorOrigin.port !== String(port)) {
1018
+ throw reuseMismatch('port', expectedPort, descriptorOrigin.port);
1019
+ }
1020
+ const descriptorPid = descriptor.pid;
1021
+ if (!running(descriptorPid)) throw new JobHostAttachError('probe', 'record');
1022
+
1023
+ // Stage the exact job on its own readonly handle BEFORE the single final probe.
1024
+ let session: JobSession;
1025
+ try {session = JobSession.openReadOnly(sanitizedStartup, expected.jobId);}
1026
+ catch (error) {
1027
+ if (error instanceof JobError && error.code === 'JOB_CLOSED') throw new JobHostAttachError('closed', 'adoption');
1028
+ throw new JobHostAttachError('race', 'adoption');
1029
+ }
1030
+ try {
1031
+ const observed: ObservedFiles = {root: fileIdentity(root), stateDir: fileIdentity(stateInfo),
1032
+ store: fileIdentity(sqliteInfo), record: fileIdentity(recordInfo)};
1033
+ try {
1034
+ assertJobRoot(root);
1035
+ const current = observeFiles(expected);
1036
+ for (const field of observedFields) if (!sameFile(current[field], observed[field])) throw new JobHostAttachError('race', 'adoption');
1037
+ if (!sameFile(lstatSync(control), controlInfo) || readDescriptor(recordPath).bytes !== recordBytes) throw new JobHostAttachError('race', 'adoption');
1038
+ assertNoSqliteSidecars(sqliteFile, 'adoption');
1039
+ session.inspectAttach(() => {
1040
+ const live = session.attestation();
1041
+ if (live.revision !== inspectedRevision || session.hostCredentials().ui !== uiCapability) throw new JobHostAttachError('race', 'adoption');
1042
+ compareAttachment(expected, buildAttachment(session, expected.origin, expected.listenerIncarnation, identity));
1043
+ });
1044
+ } catch (error) {
1045
+ if (error instanceof JobHostAttachError) throw error;
1046
+ throw new JobHostAttachError('race', 'adoption');
1047
+ }
1048
+ const body = JSON.stringify({expected, observed});
1049
+ if (Buffer.byteLength(body) > WORKSPACE_BODY_LIMIT) throw new JobError('JOB_BODY_LIMIT');
1050
+ const start = performance.now();
1051
+ let response: Response, remote: unknown;
1052
+ try {
1053
+ response = await fetch(expected.origin + `/jobs/${expected.jobId}/host`, {
1054
+ method: 'POST', headers: {'Content-Type': 'application/json', Origin: new URL(expected.origin).origin,
1055
+ 'X-Review-Capability': uiCapability}, body, redirect: 'error', signal: AbortSignal.timeout(1500),
1056
+ });
1057
+ const remaining = 1500 - (performance.now() - start);
1058
+ if (remaining <= 0) {void response.body?.cancel(); throw new Error('deadline');}
1059
+ remote = await readOpenStatus(response, remaining);
1060
+ } catch {throw new JobHostAttachError('probe', 'probe');}
1061
+ if (!response.ok) {
1062
+ const refusal = validatedHostRefusal(remote, response.status);
1063
+ if (refusal) throw refusal;
1064
+ throw new JobHostAttachError('probe', 'probe');
1065
+ }
1066
+ if (!isPlainObject(remote)) throw new JobHostAttachError('read', 'probe');
1067
+ let actual: JobHostReuseExpectation;
1068
+ try {
1069
+ const success = exactKeys(remote, ['ok', 'attachment', 'pid']);
1070
+ if (success.ok !== true || success.pid !== descriptorPid) throw new JobHostAttachError('read', 'probe');
1071
+ if (isPlainObject(success.attachment) && !Object.hasOwn(success.attachment, 'listenerIncarnation')) {
1072
+ throw new JobHostAttachError('incarnation-missing', 'probe');
1073
+ }
1074
+ actual = parseReuseOnlyExpectation({expected: success.attachment}, false);
1075
+ } catch (error) {
1076
+ if (error instanceof JobHostAttachError) throw error;
1077
+ throw new JobHostAttachError('read', 'probe');
1078
+ }
1079
+ compareAttachment(expected, actual);
1080
+ // No filesystem work or new session adoption follows accepted validation.
1081
+ return {session, ports: createJobHostPorts(session, new URL(expected.origin).origin), origin: expected.origin,
1082
+ ownerUrl: expected.origin + `/jobs/${expected.jobId}/#cap=${uiCapability}`, reused: true,
1083
+ attachment: freezeExpectation(actual), stop: () => session.dispose()};
1084
+ } catch (error) {session.dispose(); throw error;}
1085
+ }
1086
+
1087
+ function validatedHostRefusal(raw: unknown, status: number): Error | null {
1088
+ try {
1089
+ const value = exactKeys(raw, ['ok', 'error']); if (value.ok !== false) return null;
1090
+ if (!isPlainObject(value.error)) return null;
1091
+ if (value.error.code === 'JOB_HOST_ATTACH_REFUSED') {
1092
+ const item = exactKeys(value.error, ['code', 'reason', 'phase']);
1093
+ if (!['missing', 'closed', 'incarnation-missing', 'replaced', 'read', 'probe', 'stopped', 'race'].includes(item.reason as string) ||
1094
+ !['input', 'state', 'record', 'probe', 'adoption', 'acceptance'].includes(item.phase as string) ||
1095
+ status !== (item.reason === 'stopped' ? 503 : 409)) return null;
1096
+ return new JobHostAttachError(item.reason as JobHostAttachError['reason'], item.phase as JobHostAttachError['phase']);
1097
+ }
1098
+ if (value.error.code === 'JOB_HOST_REUSE_MISMATCH' && status === 409) {
1099
+ const item = exactKeys(value.error, ['code', 'field', 'expected', 'actual']);
1100
+ if (!['jobId', 'origin', 'listenerIncarnation', 'root', 'stateDir', 'fingerprint', 'reviewer.id', 'reviewer.role',
1101
+ 'readerId', 'bindingId', 'partsEnumeratorId', 'partsEnumeratorVersion', 'apiSchema', 'actSchema', 'port'].includes(item.field as string) ||
1102
+ [item.expected, item.actual].some(v => v !== null && typeof v !== 'string')) return null;
1103
+ return reuseMismatch(item.field as JobHostAttachField, item.expected as string | null, item.actual as string | null);
1104
+ }
1105
+ } catch { /* A malformed failure is a transport refusal, never trusted host evidence. */ }
1106
+ return null;
1107
+ }
1108
+
1109
+ function snapshotHostOptions(options: JobHostOptions): JobHostOptions {
1110
+ const copy = ownData(options);
1111
+ if (copy.reuseOnly !== undefined && Object.keys(copy).some(key => ![
1112
+ 'root', 'stateDir', 'fingerprint', 'reviewer', 'readPublished', 'readerId', 'installWriterBinding',
1113
+ 'bindingId', 'partsEnumerator', 'partsEnumeratorId', 'port', 'reuseOnly', 'afterSnapshot', 'afterDirectorySync',
1114
+ ].includes(key))) throw new JobError('JOB_REQUEST_INVALID');
1115
+ if (copy.partsEnumerator !== undefined) copy.partsEnumerator = {...exactKeys(copy.partsEnumerator, ['version', 'enumerate'])};
1116
+ if (copy.reviewer !== undefined) copyReviewer();
1117
+ function copyReviewer() {
1118
+ const data = ownData(copy.reviewer);
1119
+ Object.defineProperty(copy, 'reviewer', {value: {...data}, enumerable: true, configurable: true});
1120
+ }
1121
+ return copy as unknown as JobHostOptions;
1122
+ }
1123
+
1124
+ function reuseOnlyDescriptor(value: object): PropertyDescriptor | undefined {
1125
+ for (let current: object | null = value; current; current = Object.getPrototypeOf(current)) {
1126
+ const descriptor = Object.getOwnPropertyDescriptor(current, 'reuseOnly');
1127
+ if (descriptor) return descriptor;
1128
+ }
1129
+ return undefined;
407
1130
  }
408
1131
 
409
1132
  /** Full standing owner host. #489 can publish this seam after its own contract review. */
410
1133
  export async function startJobHost(options: JobHostOptions): Promise<JobOwnerHost> {
1134
+ if (!options || typeof options !== 'object') throw new JobError('JOB_REQUEST_INVALID');
1135
+ const reuseOnly = reuseOnlyDescriptor(options);
1136
+ if (reuseOnly && !('value' in reuseOnly)) throw new JobError('JOB_REQUEST_INVALID');
1137
+ if (reuseOnly?.value !== undefined) return attachJobHost(snapshotHostOptions(options));
411
1138
  const startup = {...options};
412
1139
  const identity = jobHostIdentity(startup);
413
1140
  const session = new JobSession(startup);
@@ -451,10 +1178,19 @@ export async function startJobHost(options: JobHostOptions): Promise<JobOwnerHos
451
1178
  performance.now() + 20_000, 'JOB_STORAGE_FAILED');
452
1179
  if ('row' in acquired) {
453
1180
  const origin = acquired.row.origin;
454
- const ports = createJobHostPorts(session, origin);
1181
+ const ports = createJobHostPorts(session, new URL(origin).origin);
455
1182
  await installBinding(origin);
1183
+ // Preserve the GET decision. A separate explicit POST may supply complete attestation.
1184
+ let attachment: JobHostReuseExpectation | null = null;
1185
+ if (typeof acquired.row.listenerIncarnation === 'string' && UUID_V4_RE.test(acquired.row.listenerIncarnation)) {
1186
+ try {
1187
+ const expected = buildAttachment(session, origin, acquired.row.listenerIncarnation, identity);
1188
+ const attached = await attachJobHost({...startup, reviewer: expected.binding.reviewer, reuseOnly: {expected}});
1189
+ attachment = attached.attachment; attached.stop();
1190
+ } catch { /* Added metadata never changes ordinary reuse's existing decision. */ }
1191
+ }
456
1192
  return {session, ports, origin, ownerUrl: origin + `/jobs/${session.jobId}/#cap=${credentials.ui}`,
457
- reused: true, stop: () => session.dispose()};
1193
+ reused: true, attachment, stop: () => session.dispose()};
458
1194
  }
459
1195
  claim = acquired.claim;
460
1196
  let context: ReturnType<typeof createJobRequestContext>;
@@ -464,7 +1200,7 @@ export async function startJobHost(options: JobHostOptions): Promise<JobOwnerHos
464
1200
  });
465
1201
  const origin = `http://127.0.0.1:${server.port}`;
466
1202
  context = createJobRequestContext(session, startup, origin, identity);
467
- const {ports, record} = context;
1203
+ const {ports} = context;
468
1204
  const closed = new AbortController();
469
1205
  let stopped = false;
470
1206
  stop = () => {
@@ -476,9 +1212,12 @@ export async function startJobHost(options: JobHostOptions): Promise<JobOwnerHos
476
1212
  session.dispose();
477
1213
  };
478
1214
  await installBinding(origin);
1215
+ const desc = context.descriptor();
479
1216
  const temporary = recordPath + '.' + nonce + '.tmp';
480
- await writeFile(temporary, JSON.stringify(record), {flag: 'wx', mode: 0o600});
1217
+ await writeFile(temporary, JSON.stringify(desc.record), {flag: 'wx', mode: 0o600});
481
1218
  await rename(temporary, recordPath);
1219
+ context.publish();
1220
+ const attachment = context.attachment();
482
1221
  void (async () => {
483
1222
  try {
484
1223
  for await (const event of session.subscribe({jobId: session.jobId, after: null, signal: closed.signal})) {
@@ -490,7 +1229,8 @@ export async function startJobHost(options: JobHostOptions): Promise<JobOwnerHos
490
1229
  }
491
1230
  } catch { /* Shutdown aborts the subscription. */ }
492
1231
  })();
493
- return {session, ports, origin, ownerUrl: origin + `/jobs/${session.jobId}/#cap=${credentials.ui}`, reused: false, stop};
1232
+ return {session, ports, origin, ownerUrl: origin + `/jobs/${session.jobId}/#cap=${credentials.ui}`,
1233
+ reused: false, attachment, stop};
494
1234
  } catch (error) {
495
1235
  if (stop) stop(); else session.dispose();
496
1236
  throw error;