@aviaratech/ai-delivery 0.3.31 → 0.3.32

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,8 +2,9 @@ import assert from 'node:assert/strict';
2
2
  import { execFileSync, spawn, spawnSync } from 'node:child_process';
3
3
  import { chmodSync, cpSync, existsSync, truncateSync, linkSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, symlinkSync, utimesSync, writeFileSync, } from 'node:fs';
4
4
  import { tmpdir } from 'node:os';
5
- import { dirname, join } from 'node:path';
5
+ import { dirname, join, relative, isAbsolute, sep } from 'node:path';
6
6
  import { afterEach, test, vi } from 'vitest';
7
+ import { z } from 'zod';
7
8
  import { loadDeliveryConfig } from './config/deliveryConfig.js';
8
9
  import * as privateFiles from './delivery/common.js';
9
10
  import { digestBytes, digestValue } from './delivery/index.js';
@@ -64,10 +65,24 @@ function beginControllerObservation(mode) {
64
65
  }
65
66
  const syncFailure = vi.hoisted(() => ({ directory: '' }));
66
67
  const sharedOutputRead = vi.hoisted(() => ({ path: '', unboundedReads: 0 }));
68
+ const retirementFailure = vi.hoisted(() => ({ directory: '', error: undefined, hits: 0 }));
67
69
  vi.mock('node:fs', async (original) => {
68
70
  const actual = await original();
69
71
  return {
70
72
  ...actual,
73
+ rmdirSync: (...args) => {
74
+ const result = actual.rmdirSync(...args);
75
+ const path = String(args[0]);
76
+ if (retirementFailure.error !== undefined &&
77
+ dirname(dirname(path)) === retirementFailure.directory &&
78
+ /^[a-f0-9]{64}[/\\][a-f0-9-]{36}$/u.test(path.slice(retirementFailure.directory.length + 1))) {
79
+ retirementFailure.hits++;
80
+ const error = retirementFailure.error;
81
+ retirementFailure.error = undefined;
82
+ throw error;
83
+ }
84
+ return result;
85
+ },
71
86
  readFileSync: (...args) => {
72
87
  if (sharedOutputRead.path && String(args[0]) === sharedOutputRead.path) {
73
88
  sharedOutputRead.unboundedReads++;
@@ -158,7 +173,7 @@ async function producer() {
158
173
  function git(root, ...args) {
159
174
  return execFileSync('git', args, { cwd: root, encoding: 'utf8' }).trim();
160
175
  }
161
- async function fixture(native = false) {
176
+ async function fixture(native = false, parent = tmpdir()) {
162
177
  actors.author = 'host-user';
163
178
  actors.reviewer = 'reviewer[bot]';
164
179
  actors.access = true;
@@ -168,7 +183,7 @@ async function fixture(native = false) {
168
183
  actors.authorStarted = false;
169
184
  actors.authorAborted = false;
170
185
  actors.pauseAuthor = false;
171
- const base = realpathSync(mkdtempSync(join(tmpdir(), 'ai-delivery-setup-')));
186
+ const base = realpathSync(mkdtempSync(join(parent, 'ai-delivery-setup-')));
172
187
  const root = join(base, 'consumer');
173
188
  mkdirSync(root);
174
189
  git(root, 'init', '-q', '-b', 'main');
@@ -232,7 +247,7 @@ async function fixture(native = false) {
232
247
  const counter = join(base, 'installs');
233
248
  const marker = join(base, 'installer-running');
234
249
  // Synthetic installer boundary: the real owned command copies fixture bytes; no process manager is mocked.
235
- writeFileSync(join(bin, 'npm'), `#!${process.execPath}\nconst fs=require('fs'),cp=require('child_process'),path=require('path');\nconst args=process.argv.slice(2);\nif(args[0]!=='install'||!['--omit=dev','--ignore-scripts','--no-audit','--no-fund'].every(x=>args.includes(x)))process.exit(9);\nfs.appendFileSync(${JSON.stringify(counter)},'x');\nfs.writeFileSync(${JSON.stringify(marker)},String(process.pid));\nconst prefix=args[args.indexOf('--prefix')+1],archive=args.at(-1);\nfs.writeFileSync(${JSON.stringify(join(base, 'installer-settings'))},JSON.stringify({args,cwd:process.cwd(),TMPDIR:process.env.TMPDIR,TMP:process.env.TMP,TEMP:process.env.TEMP}));\nfs.writeFileSync(${JSON.stringify(join(base, 'installer-archive'))},archive);\nconst original=${JSON.stringify(archivePath)},replacement=${JSON.stringify(join(base, 'replacement.tgz'))};\nconst saved=fs.existsSync(replacement)?fs.readFileSync(original):undefined;\nif(saved)fs.copyFileSync(replacement,original);\nconst target=path.join(prefix,'node_modules/@aviaratech/ai-delivery');fs.mkdirSync(target,{recursive:true});\ntry{cp.execFileSync('tar',['-xzf',archive,'--strip-components=1','-C',target]);}finally{if(saved)fs.writeFileSync(original,saved);}\nfs.mkdirSync(path.join(prefix,'node_modules/.bin'),{recursive:true});\nfs.symlinkSync('../@aviaratech/ai-delivery/dist/cli.js',path.join(prefix,'node_modules/.bin/ai-delivery'));\nconst logs=${JSON.stringify(join(base, 'log-bytes'))};\nif(fs.existsSync(logs))process.stdout.write(Buffer.alloc(Number(fs.readFileSync(logs,'utf8')),65),()=>{if(fs.existsSync(${JSON.stringify(join(base, 'fail'))}))process.exit(7);});\nelse if(fs.existsSync(${JSON.stringify(join(base, 'fail'))}))process.exit(7);\nconst memory=${JSON.stringify(join(base, 'memory-bytes'))};\nif(fs.existsSync(memory)){globalThis.fixtureAllocation=Buffer.alloc(Number(fs.readFileSync(memory,'utf8')),1);setInterval(()=>{},1000);}\nif(fs.existsSync(${JSON.stringify(join(base, 'wait'))}))setInterval(()=>{},1000);\n`);
250
+ writeFileSync(join(bin, 'npm'), `#!${process.execPath}\nconst fs=require('fs'),cp=require('child_process'),path=require('path');\nconst args=process.argv.slice(2);\nif(args[0]!=='install'||!['--omit=dev','--ignore-scripts','--no-audit','--no-fund'].every(x=>args.includes(x)))process.exit(9);\nfs.appendFileSync(${JSON.stringify(counter)},'x');\nfs.writeFileSync(${JSON.stringify(marker)},String(process.pid));\nconst prefix=args[args.indexOf('--prefix')+1],archive=args.at(-1);\nfs.writeFileSync(${JSON.stringify(join(base, 'installer-settings'))},JSON.stringify({args,cwd:process.cwd(),TMPDIR:process.env.TMPDIR,TMP:process.env.TMP,TEMP:process.env.TEMP}));\nfs.writeFileSync(${JSON.stringify(join(base, 'installer-archive'))},archive);\nconst original=${JSON.stringify(archivePath)},replacement=${JSON.stringify(join(base, 'replacement.tgz'))};\nconst saved=fs.existsSync(replacement)?fs.readFileSync(original):undefined;\nif(saved)fs.copyFileSync(replacement,original);\nconst target=path.join(prefix,'node_modules/@aviaratech/ai-delivery');fs.mkdirSync(target,{recursive:true});\ntry{cp.execFileSync('tar',['-xzf',archive,'--strip-components=1','-C',target]);}finally{if(saved)fs.writeFileSync(original,saved);}\nconst dependency={'@aviaratech/ai-delivery':'file:reviewed-archive.tgz'};fs.writeFileSync(path.join(prefix,'package.json'),JSON.stringify({dependencies:dependency}));\nif(!args.includes('--package-lock=false')){const targetPackage=JSON.parse(fs.readFileSync(path.join(target,'package.json'),'utf8')),integrity='sha512-'+require('node:crypto').createHash('sha512').update(fs.readFileSync(archive)).digest('base64');fs.writeFileSync(path.join(prefix,'package-lock.json'),JSON.stringify({lockfileVersion:3,packages:{'':{dependencies:dependency},'node_modules/@aviaratech/ai-delivery':{version:targetPackage.version,resolved:'file:reviewed-archive.tgz',integrity}}}));}\nfs.mkdirSync(path.join(prefix,'node_modules/.bin'),{recursive:true});\nfs.symlinkSync('../@aviaratech/ai-delivery/dist/cli.js',path.join(prefix,'node_modules/.bin/ai-delivery'));\nconst logs=${JSON.stringify(join(base, 'log-bytes'))};\nif(fs.existsSync(logs))process.stdout.write(Buffer.alloc(Number(fs.readFileSync(logs,'utf8')),65),()=>{if(fs.existsSync(${JSON.stringify(join(base, 'fail'))}))process.exit(7);});\nelse if(fs.existsSync(${JSON.stringify(join(base, 'fail'))}))process.exit(7);\nconst memory=${JSON.stringify(join(base, 'memory-bytes'))};\nif(fs.existsSync(memory)){globalThis.fixtureAllocation=Buffer.alloc(Number(fs.readFileSync(memory,'utf8')),1);setInterval(()=>{},1000);}\nif(fs.existsSync(${JSON.stringify(join(base, 'wait'))}))setInterval(()=>{},1000);\n`);
236
251
  chmodSync(join(bin, 'npm'), 0o755);
237
252
  const previousPath = process.env.PATH;
238
253
  process.env.PATH = `${bin}:${previousPath ?? ''}`;
@@ -878,6 +893,213 @@ for (const mode of ['success', 'failure', 'cancel']) {
878
893
  }
879
894
  });
880
895
  }
896
+ test('real npm keeps the reviewed tarball closure after hidden-lock invalidation and completed reuse', async () => {
897
+ const api = await producer();
898
+ const realPath = process.env.PATH;
899
+ const f = await fixture();
900
+ try {
901
+ const npmRoot = join(dirname(process.execPath), '../lib/node_modules/npm');
902
+ const npmCli = join(npmRoot, 'bin/npm-cli.js');
903
+ assert.equal(JSON.parse(readFileSync(join(npmRoot, 'package.json'), 'utf8')).version, '11.19.0');
904
+ const bin = join(f.base, 'real-npm-bin');
905
+ mkdirSync(bin);
906
+ writeFileSync(join(bin, 'npm'), `#!${process.execPath}\nconst fs=require('node:fs');if(process.argv[2]==='install')fs.appendFileSync(${JSON.stringify(f.counter)},'x');require(${JSON.stringify(npmCli)});\n`);
907
+ chmodSync(join(bin, 'npm'), 0o755);
908
+ process.env.PATH = `${bin}:${realPath ?? ''}`;
909
+ const manifestPath = join(f.base, 'archive/package/package.json');
910
+ const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'));
911
+ manifest.scripts = { preinstall: 'node -e "process.exit(91)"', install: 'node -e "process.exit(92)"' };
912
+ writeFileSync(manifestPath, JSON.stringify(manifest));
913
+ execFileSync('tar', ['-czf', f.input.archivePath, '-C', join(f.base, 'archive'), 'package']);
914
+ f.input.expectedArchiveSha256 = digestBytes(readFileSync(f.input.archivePath));
915
+ const installed = join(f.input.runtimeDirectory, 'node_modules');
916
+ const hidden = join(installed, '.package-lock.json');
917
+ const stage = await api.stageRuntime(f.input);
918
+ const completeBytes = readFileSync(join(f.input.runtimeDirectory, 'runtime-stage.json'));
919
+ const metadataPaths = ['package.json', 'package-lock.json'].map((name) => join(f.input.runtimeDirectory, name));
920
+ const metadataBytes = metadataPaths.map((path) => readFileSync(path));
921
+ const inspectClosure = () => spawnSync(process.execPath, [npmCli, 'ls', '--prefix', f.input.runtimeDirectory, '--omit=dev', '--all', '--json', '--logs-max', '0'], { cwd: f.root, encoding: 'utf8', maxBuffer: 1024 ** 2 });
922
+ const closure = () => {
923
+ const result = inspectClosure();
924
+ assert.equal(result.error, undefined);
925
+ assert.equal(result.status, 0, result.stderr + result.stdout);
926
+ const graph = JSON.parse(result.stdout);
927
+ assert.equal(graph.problems, undefined);
928
+ const target = graph.dependencies['@aviaratech/ai-delivery'];
929
+ assert.equal(target.version, '0.3.5');
930
+ assert.equal(target.invalid, undefined);
931
+ assert.equal(target.missing, undefined);
932
+ assert.equal(target.resolved, `file:${join(f.input.runtimeDirectory, 'reviewed-archive.tgz')}`);
933
+ };
934
+ closure();
935
+ const lockTime = lstatSync(hidden).mtime;
936
+ utimesSync(installed, new Date(lockTime.getTime() + 2000), new Date(lockTime.getTime() + 2000));
937
+ assert.ok(lstatSync(installed).mtimeMs > lstatSync(hidden).mtimeMs);
938
+ closure();
939
+ assert.deepEqual(await api.stageRuntime(f.input), { ...stage, reused: true });
940
+ assert.deepEqual(readFileSync(join(f.input.runtimeDirectory, 'runtime-stage.json')), completeBytes);
941
+ assert.deepEqual(metadataPaths.map((path) => readFileSync(path)), metadataBytes);
942
+ rmSync(hidden);
943
+ closure();
944
+ assert.deepEqual(await api.stageRuntime(f.input), { ...stage, reused: true });
945
+ await api.admitRuntime(admitInput(f.input, stage.stageId));
946
+ assert.equal(readFileSync(f.counter, 'utf8'), 'x', 'completed reuse must never reinstall');
947
+ assert.deepEqual(readFileSync(join(f.input.runtimeDirectory, 'runtime-stage.json')), completeBytes);
948
+ assert.deepEqual(metadataPaths.map((path) => readFileSync(path)), metadataBytes);
949
+ const admissionPath = join(f.root, '.git/ai-delivery/runtime-admission.json');
950
+ const admissionBytes = readFileSync(admissionPath);
951
+ for (const { field, edges, problem } of [
952
+ { field: 'optionalDependencies', edges: { '@aviaratech/ai-delivery': 'file:other.tgz' }, problem: /invalid:/u },
953
+ { field: 'peerDependencies', edges: { 'missing-runtime-stage-peer': '1.0.0' }, problem: /missing:/u },
954
+ ]) {
955
+ const changed = JSON.parse(metadataBytes[0].toString('utf8'));
956
+ changed[field] = edges;
957
+ writeFileSync(metadataPaths[0], JSON.stringify(changed));
958
+ const damaged = readFileSync(metadataPaths[0]);
959
+ const native = inspectClosure();
960
+ assert.equal(native.error, undefined);
961
+ assert.equal(native.status, 1, native.stderr + native.stdout);
962
+ const graph = JSON.parse(native.stdout);
963
+ assert.equal(graph.error?.code, 'ELSPROBLEMS');
964
+ assert.ok(graph.problems?.some((entry) => problem.test(entry)));
965
+ await assert.rejects(api.stageRuntime(f.input), /dependency metadata/iu);
966
+ await assert.rejects(api.admitRuntime(admitInput(f.input, stage.stageId)), /dependency metadata/iu);
967
+ assert.deepEqual(readFileSync(metadataPaths[0]), damaged);
968
+ assert.deepEqual(readFileSync(metadataPaths[1]), metadataBytes[1]);
969
+ assert.deepEqual(readFileSync(join(f.input.runtimeDirectory, 'runtime-stage.json')), completeBytes);
970
+ assert.deepEqual(readFileSync(admissionPath), admissionBytes);
971
+ assert.equal(readFileSync(f.counter, 'utf8'), 'x');
972
+ writeFileSync(metadataPaths[0], metadataBytes[0]);
973
+ }
974
+ }
975
+ finally {
976
+ f.cleanup();
977
+ process.env.PATH = realPath;
978
+ }
979
+ });
980
+ test('completed stages refuse missing, corrupt or incompatible dependency metadata without reinstalling or rewriting', async () => {
981
+ const api = await producer();
982
+ const f = await fixture();
983
+ try {
984
+ const staged = await api.stageRuntime(f.input);
985
+ const record = join(f.input.runtimeDirectory, 'runtime-stage.json');
986
+ const complete = readFileSync(record);
987
+ const paths = ['package.json', 'package-lock.json'].map((name) => join(f.input.runtimeDirectory, name));
988
+ const retained = paths.map((path) => (existsSync(path) ? readFileSync(path) : undefined));
989
+ for (const [index, path] of paths.entries()) {
990
+ for (const fault of [
991
+ 'missing',
992
+ 'corrupt',
993
+ 'incompatible',
994
+ 'symlink',
995
+ 'hardlink',
996
+ 'fifo',
997
+ ...(index === 1 ? ['version', 'resolved', 'integrity'] : []),
998
+ ]) {
999
+ const sentinel = join(f.base, `unrelated-metadata-${index}-${fault}`);
1000
+ if (fault === 'missing')
1001
+ rmSync(path, { force: true });
1002
+ else if (fault === 'symlink' || fault === 'hardlink') {
1003
+ writeFileSync(sentinel, retained[index]);
1004
+ rmSync(path);
1005
+ if (fault === 'symlink')
1006
+ symlinkSync(sentinel, path);
1007
+ else
1008
+ linkSync(sentinel, path);
1009
+ }
1010
+ else if (fault === 'fifo') {
1011
+ rmSync(path);
1012
+ execFileSync('mkfifo', [path]);
1013
+ }
1014
+ else if (['version', 'resolved', 'integrity'].includes(fault)) {
1015
+ const lock = JSON.parse(retained[index].toString('utf8'));
1016
+ lock.packages['node_modules/@aviaratech/ai-delivery'][fault] = 'incompatible';
1017
+ writeFileSync(path, JSON.stringify(lock));
1018
+ }
1019
+ else
1020
+ writeFileSync(path, fault === 'corrupt'
1021
+ ? '{'
1022
+ : JSON.stringify(index === 0
1023
+ ? { dependencies: { '@aviaratech/ai-delivery': 'file:other.tgz' } }
1024
+ : { lockfileVersion: 99, packages: {} }));
1025
+ const damaged = fault !== 'fifo' && existsSync(path) ? readFileSync(path) : undefined;
1026
+ await assert.rejects(api.stageRuntime(f.input), fault === 'symlink' ? /symbolic link/iu : fault === 'fifo' ? /unsupported file/iu : /dependency metadata/iu);
1027
+ await assert.rejects(api.admitRuntime(admitInput(f.input, staged.stageId)), /dependency metadata/iu);
1028
+ assert.deepEqual(readFileSync(record), complete);
1029
+ if (fault === 'fifo')
1030
+ assert.equal(lstatSync(path).isFIFO(), true);
1031
+ else
1032
+ assert.deepEqual(existsSync(path) ? readFileSync(path) : undefined, damaged);
1033
+ if (fault === 'symlink' || fault === 'hardlink') {
1034
+ assert.deepEqual(readFileSync(sentinel), retained[index]);
1035
+ assert.equal(lstatSync(path).isSymbolicLink(), fault === 'symlink');
1036
+ }
1037
+ assert.equal(readFileSync(f.counter, 'utf8'), 'x', 'metadata refusal must not reinstall');
1038
+ rmSync(path, { force: true });
1039
+ if (retained[index] !== undefined)
1040
+ writeFileSync(path, retained[index]);
1041
+ }
1042
+ }
1043
+ }
1044
+ finally {
1045
+ f.cleanup();
1046
+ }
1047
+ });
1048
+ for (const metadata of ['package.json', 'package-lock.json']) {
1049
+ test(`lost completion response refuses ${metadata} drift during final preflight without reinstalling`, async () => {
1050
+ const api = await producer();
1051
+ const f = await fixture();
1052
+ let operation;
1053
+ try {
1054
+ const record = join(f.input.runtimeDirectory, 'runtime-stage.json');
1055
+ const target = join(f.input.runtimeDirectory, metadata);
1056
+ let complete;
1057
+ let notifyWritten;
1058
+ const written = new Promise((resolve) => {
1059
+ notifyWritten = resolve;
1060
+ });
1061
+ const actual = atomicJson.writePrivateJsonFileAtomically;
1062
+ vi.spyOn(atomicJson, 'writePrivateJsonFileAtomically').mockImplementation((path, value) => {
1063
+ actual(path, value);
1064
+ if (path === record && value.status === 'complete') {
1065
+ complete = readFileSync(record);
1066
+ actors.authorStarted = false;
1067
+ actors.pauseAuthor = true;
1068
+ notifyWritten();
1069
+ throw new Error('Synthetic completion response lost after durable write');
1070
+ }
1071
+ });
1072
+ operation = api.stageRuntime(f.input);
1073
+ const settled = operation.then((value) => ({ status: 'fulfilled', value }), (error) => ({ status: 'rejected', error }));
1074
+ const prematurelySettled = settled.then((result) => {
1075
+ if (result.status === 'rejected')
1076
+ throw result.error;
1077
+ throw new Error('Stage completed before the recovery fault was injected.');
1078
+ });
1079
+ await Promise.race([written, prematurelySettled]);
1080
+ while (!actors.authorStarted)
1081
+ await Promise.race([new Promise((resolve) => setTimeout(resolve, 10)), prematurelySettled]);
1082
+ assert.ok(complete);
1083
+ assert.equal(JSON.parse(complete.toString('utf8')).status, 'complete');
1084
+ if (metadata === 'package.json')
1085
+ rmSync(target);
1086
+ else
1087
+ writeFileSync(target, '{');
1088
+ const damaged = existsSync(target) ? readFileSync(target) : undefined;
1089
+ await assert.rejects(operation, /dependency metadata/iu);
1090
+ assert.deepEqual(readFileSync(record), complete);
1091
+ assert.deepEqual(existsSync(target) ? readFileSync(target) : undefined, damaged);
1092
+ assert.equal(readFileSync(f.counter, 'utf8'), 'x');
1093
+ assert.equal(existsSync(join(f.root, '.git/ai-delivery/runtime-admission.json')), false);
1094
+ }
1095
+ finally {
1096
+ await operation?.catch(() => undefined);
1097
+ actors.pauseAuthor = false;
1098
+ vi.restoreAllMocks();
1099
+ f.cleanup();
1100
+ }
1101
+ });
1102
+ }
881
1103
  test('public producer stages exact bytes, explicitly admits and reuses completed work without installing again', async () => {
882
1104
  const api = await producer();
883
1105
  const f = await fixture();
@@ -1123,6 +1345,44 @@ test('post-rename errors reconcile desired bytes and never overwrite third-party
1123
1345
  f.cleanup();
1124
1346
  }
1125
1347
  });
1348
+ async function cancelNativeStageWhenReady(running, input, controller, onReady = () => { }) {
1349
+ const settled = running.then(() => ({ status: 'fulfilled' }), (reason) => ({ status: 'rejected', reason }));
1350
+ let failed = false;
1351
+ let failure;
1352
+ let outcome;
1353
+ try {
1354
+ // The real operation retains its native request/resource/cancellation/drain guards.
1355
+ // Readiness is an installer condition, not an assumed elapsed preparation duration.
1356
+ while (!existsSync(join(input.runtimeDirectory, 'node_modules/.bin/ai-delivery'))) {
1357
+ const outcome = await Promise.race([
1358
+ settled,
1359
+ new Promise((resolve) => setTimeout(resolve, 20, undefined)),
1360
+ ]);
1361
+ if (outcome?.status === 'rejected')
1362
+ throw outcome.reason;
1363
+ assert.notEqual(outcome?.status, 'fulfilled', 'Stage completed before the pending installer became ready');
1364
+ }
1365
+ assert.equal(digestBytes(readFileSync(join(input.runtimeDirectory, 'reviewed-archive.tgz'))), input.expectedArchiveSha256);
1366
+ onReady();
1367
+ controller.abort();
1368
+ await assert.rejects(running, /cancelled/u);
1369
+ }
1370
+ catch (error) {
1371
+ failed = true;
1372
+ failure = error;
1373
+ }
1374
+ finally {
1375
+ controller.abort();
1376
+ outcome = await settled;
1377
+ }
1378
+ if (outcome?.status === 'rejected' && !/cancelled/u.test(String(outcome.reason)) && outcome.reason !== failure) {
1379
+ if (failed)
1380
+ throw new AggregateError([failure, outcome.reason], 'Native fixture assertion and staging both failed');
1381
+ throw outcome.reason;
1382
+ }
1383
+ if (failed)
1384
+ throw failure;
1385
+ }
1126
1386
  for (const native of [false, true]) {
1127
1387
  test(`${native ? 'native ' : ''}failure and cancellation remove only the owned incomplete stage and preserve unrelated output`, async () => {
1128
1388
  const api = await producer();
@@ -1138,12 +1398,16 @@ for (const native of [false, true]) {
1138
1398
  rmSync(join(f.base, 'fail'));
1139
1399
  writeFileSync(join(f.base, 'wait'), 'go');
1140
1400
  const running = api.stageRuntime({ ...f.input, signal: controller.signal });
1141
- void running.catch(() => undefined);
1142
- for (let i = 0; i < 100 && !existsSync(join(f.input.runtimeDirectory, 'node_modules/.bin/ai-delivery')); i++)
1143
- await new Promise((resolve) => setTimeout(resolve, 20));
1144
- assert.equal(digestBytes(readFileSync(join(f.input.runtimeDirectory, 'reviewed-archive.tgz'))), f.input.expectedArchiveSha256);
1145
- controller.abort();
1146
- await assert.rejects(running, /cancelled/u);
1401
+ if (native)
1402
+ await cancelNativeStageWhenReady(running, f.input, controller);
1403
+ else {
1404
+ void running.catch(() => undefined);
1405
+ for (let i = 0; i < 100 && !existsSync(join(f.input.runtimeDirectory, 'node_modules/.bin/ai-delivery')); i++)
1406
+ await new Promise((resolve) => setTimeout(resolve, 20));
1407
+ assert.equal(digestBytes(readFileSync(join(f.input.runtimeDirectory, 'reviewed-archive.tgz'))), f.input.expectedArchiveSha256);
1408
+ controller.abort();
1409
+ await assert.rejects(running, /cancelled/u);
1410
+ }
1147
1411
  assert.equal(existsSync(f.input.runtimeDirectory), false);
1148
1412
  assert.equal(readFileSync(join(unrelated, 'keep'), 'utf8'), 'keep');
1149
1413
  assert.equal(digestBytes(readFileSync(f.input.archivePath)), f.input.expectedArchiveSha256);
@@ -1156,6 +1420,266 @@ for (const native of [false, true]) {
1156
1420
  }
1157
1421
  });
1158
1422
  }
1423
+ test('native cancellation fixture waits for delayed installer readiness', async () => {
1424
+ const api = await producer();
1425
+ const f = await fixture(true);
1426
+ const controller = new AbortController();
1427
+ writeFileSync(join(f.base, 'wait'), 'go');
1428
+ writeFileSync(join(f.base, 'unrelated'), 'keep');
1429
+ actors.pauseAuthor = true;
1430
+ const running = api.stageRuntime({ ...f.input, signal: controller.signal });
1431
+ const settled = running.then(() => 'fulfilled', () => 'rejected');
1432
+ try {
1433
+ await cancelNativeStageWhenReady(running, f.input, controller);
1434
+ assert.equal(actors.authorStarted, true);
1435
+ assert.equal(readFileSync(f.counter, 'utf8'), 'x');
1436
+ assert.equal(existsSync(f.input.runtimeDirectory), false);
1437
+ assert.equal(readFileSync(join(f.base, 'unrelated'), 'utf8'), 'keep');
1438
+ assert.equal(digestBytes(readFileSync(f.input.archivePath)), f.input.expectedArchiveSha256);
1439
+ assert.equal(readFileSync(join(f.input.nativePluginRoot, 'README.md'), 'utf8'), 'Synthetic copied native plugin.\n');
1440
+ }
1441
+ finally {
1442
+ controller.abort();
1443
+ await settled;
1444
+ actors.pauseAuthor = false;
1445
+ f.cleanup();
1446
+ }
1447
+ });
1448
+ test('native cancellation fixture preserves an early staging rejection', async () => {
1449
+ const api = await producer();
1450
+ const f = await fixture(true);
1451
+ const controller = new AbortController();
1452
+ const input = { ...f.input, authority: '', signal: controller.signal };
1453
+ const running = api.stageRuntime(input);
1454
+ const settled = running.then(() => 'fulfilled', () => 'rejected');
1455
+ try {
1456
+ await assert.rejects(cancelNativeStageWhenReady(running, input, controller), /Explicit runtime:stage authority is required/u);
1457
+ assert.equal(existsSync(f.counter), false);
1458
+ assert.equal(existsSync(f.input.runtimeDirectory), false);
1459
+ }
1460
+ finally {
1461
+ controller.abort();
1462
+ await settled;
1463
+ f.cleanup();
1464
+ }
1465
+ });
1466
+ test('native cancellation fixture settles a real installer before assertion-failure cleanup', async () => {
1467
+ const api = await producer();
1468
+ const f = await fixture(true);
1469
+ const controller = new AbortController();
1470
+ writeFileSync(join(f.base, 'wait'), 'go');
1471
+ writeFileSync(join(f.base, 'unrelated'), 'keep');
1472
+ const running = api.stageRuntime({ ...f.input, signal: controller.signal });
1473
+ let finished = false;
1474
+ const settled = running.then(() => {
1475
+ finished = true;
1476
+ }, () => {
1477
+ finished = true;
1478
+ });
1479
+ const fault = new Error('Synthetic assertion failed with a pending native installer');
1480
+ try {
1481
+ // Establish readiness independently so this regression isolates teardown ordering.
1482
+ while (!existsSync(join(f.input.runtimeDirectory, 'node_modules/.bin/ai-delivery'))) {
1483
+ if (finished)
1484
+ await running;
1485
+ assert.equal(finished, false, 'Stage settled before the pending installer became ready');
1486
+ await new Promise((resolve) => setTimeout(resolve, 20));
1487
+ }
1488
+ await assert.rejects(cancelNativeStageWhenReady(running, f.input, controller, () => {
1489
+ throw fault;
1490
+ }), (error) => error === fault);
1491
+ assert.equal(finished, true, 'Fixture cleanup must wait for actual staging settlement');
1492
+ assert.equal(existsSync(f.input.runtimeDirectory), false);
1493
+ assert.equal(readFileSync(f.counter, 'utf8'), 'x');
1494
+ assert.equal(readFileSync(join(f.base, 'unrelated'), 'utf8'), 'keep');
1495
+ assert.equal(readFileSync(join(f.input.nativePluginRoot, 'README.md'), 'utf8'), 'Synthetic copied native plugin.\n');
1496
+ }
1497
+ finally {
1498
+ controller.abort();
1499
+ await settled;
1500
+ f.cleanup();
1501
+ }
1502
+ });
1503
+ async function assertRetirementErrorBoundaries(error, repoRoot, forbidden) {
1504
+ const { printCommandError } = await import('./cliResult.js');
1505
+ const stderr = vi.spyOn(process.stderr, 'write').mockReturnValue(true);
1506
+ const exitCode = process.exitCode;
1507
+ let cliOutput;
1508
+ try {
1509
+ printCommandError(error);
1510
+ cliOutput = stderr.mock.calls.map(([chunk]) => String(chunk)).join('');
1511
+ assert.equal(process.exitCode, 1);
1512
+ }
1513
+ finally {
1514
+ stderr.mockRestore();
1515
+ process.exitCode = exitCode;
1516
+ }
1517
+ const dispatch = await import('./dispatch.js');
1518
+ const invoke = vi.spyOn(dispatch, 'executeTool').mockRejectedValueOnce(error);
1519
+ const { Client } = await import('@modelcontextprotocol/sdk/client/index.js');
1520
+ const { InMemoryTransport } = await import('@modelcontextprotocol/sdk/inMemory.js');
1521
+ const { createAiDeliveryMcpServer } = await import('./mcp/index.js');
1522
+ const server = createAiDeliveryMcpServer({ repoRoot });
1523
+ const client = new Client({ name: 'retirement-cause-privacy', version: '1.0.0' });
1524
+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
1525
+ try {
1526
+ await server.connect(serverTransport);
1527
+ await client.connect(clientTransport);
1528
+ const result = await client.callTool({
1529
+ name: 'issue_info',
1530
+ arguments: { repo: 'example/widget', issueNumber: 17 },
1531
+ });
1532
+ assert.equal(invoke.mock.calls.length, 1);
1533
+ assert.equal(result.isError, true);
1534
+ assert.deepEqual(result.content, [{ type: 'text', text: error.message }]);
1535
+ const output = cliOutput + JSON.stringify(result);
1536
+ assert.ok(output.length < 2048);
1537
+ for (const value of forbidden)
1538
+ assert.equal(output.includes(value), false);
1539
+ }
1540
+ finally {
1541
+ await client.close();
1542
+ await server.close();
1543
+ invoke.mockRestore();
1544
+ }
1545
+ }
1546
+ for (const fault of ['installer', 'accessors', 'cycle', 'proxy']) {
1547
+ test(`output retirement retains a bounded operation cause without exposing ${fault} failure data`, async () => {
1548
+ const api = await producer();
1549
+ const f = await fixture();
1550
+ const secret = 'fictional_operation_credential';
1551
+ const priorSecret = 'fictional_existing_cause_credential';
1552
+ const prior = new Error(priorSecret);
1553
+ Object.defineProperty(prior, 'cause', { value: prior });
1554
+ const primary = new Error('Synthetic retirement refusal', { cause: prior });
1555
+ let reads = 0;
1556
+ let operation = new Error(secret.repeat(2048));
1557
+ if (fault === 'accessors') {
1558
+ operation = Object.defineProperties(new Error(), {
1559
+ message: {
1560
+ get: () => {
1561
+ reads++;
1562
+ throw new Error(secret);
1563
+ },
1564
+ },
1565
+ name: {
1566
+ get: () => {
1567
+ reads++;
1568
+ throw new Error(secret);
1569
+ },
1570
+ },
1571
+ stack: {
1572
+ get: () => {
1573
+ reads++;
1574
+ throw new Error(secret);
1575
+ },
1576
+ },
1577
+ cause: {
1578
+ get: () => {
1579
+ reads++;
1580
+ throw new Error(secret);
1581
+ },
1582
+ },
1583
+ });
1584
+ }
1585
+ else if (fault === 'cycle') {
1586
+ Object.defineProperty(operation, 'cause', { value: operation });
1587
+ Object.freeze(operation);
1588
+ }
1589
+ else if (fault === 'proxy') {
1590
+ const trap = () => {
1591
+ reads++;
1592
+ throw new Error(secret);
1593
+ };
1594
+ operation = new Error(secret, {
1595
+ // The spy checks the thrown root with instanceof; the diagnostic must never inspect its hostile cause.
1596
+ cause: new Proxy({}, { get: trap, getPrototypeOf: trap, ownKeys: trap, getOwnPropertyDescriptor: trap }),
1597
+ });
1598
+ }
1599
+ const write = atomicJson.writePrivateJsonFileAtomically;
1600
+ const injected = vi.spyOn(atomicJson, 'writePrivateJsonFileAtomically').mockImplementation((path, value) => {
1601
+ if (fault !== 'installer' && path === join(f.input.runtimeDirectory, 'runtime-stage.json'))
1602
+ throw operation;
1603
+ write(path, value);
1604
+ });
1605
+ try {
1606
+ if (fault === 'installer')
1607
+ writeFileSync(join(f.base, 'fail'), '');
1608
+ retirementFailure.directory = join(f.root, '.git/ai-delivery/output-observation');
1609
+ retirementFailure.error = primary;
1610
+ retirementFailure.hits = 0;
1611
+ let received;
1612
+ try {
1613
+ await api.stageRuntime(f.input);
1614
+ }
1615
+ catch (error) {
1616
+ received = error;
1617
+ }
1618
+ assert.equal(retirementFailure.hits, 1, 'the actual gate must retire before the injected refusal');
1619
+ assert.equal(received, primary, 'retirement failure keeps its original instance and precedence');
1620
+ assert.equal(primary.message, 'Synthetic retirement refusal');
1621
+ const cause = Object.getOwnPropertyDescriptor(primary, 'cause')?.value;
1622
+ assert.notEqual(cause, prior, 'the masked operation must have its own bounded diagnostic cause');
1623
+ assert.ok(cause instanceof Error);
1624
+ assert.match(cause.message, /^Wrapped operation failed/u);
1625
+ if (fault === 'installer')
1626
+ assert.match(cause.message, /exit=7/u);
1627
+ assert.ok(cause.message.length < 1024);
1628
+ assert.equal(cause.message.includes(secret), false);
1629
+ assert.equal(Object.getOwnPropertyDescriptor(cause, 'cause')?.value, prior, 'existing retirement cause is retained');
1630
+ assert.equal(reads, 0, 'operation getters, proxy traps and cause graphs are never evaluated');
1631
+ await assertRetirementErrorBoundaries(primary, f.root, [secret, priorSecret]);
1632
+ assert.equal(reads, 0);
1633
+ assert.equal(existsSync(f.input.runtimeDirectory), false);
1634
+ if (fault === 'installer')
1635
+ assert.equal(readFileSync(f.counter, 'utf8'), 'x');
1636
+ else
1637
+ assert.equal(existsSync(f.counter), false);
1638
+ }
1639
+ finally {
1640
+ retirementFailure.directory = '';
1641
+ retirementFailure.error = undefined;
1642
+ injected.mockRestore();
1643
+ f.cleanup();
1644
+ }
1645
+ });
1646
+ }
1647
+ test('output retirement preserves an operation failure when native retirement succeeds', async () => {
1648
+ const api = await producer();
1649
+ const f = await fixture();
1650
+ try {
1651
+ writeFileSync(join(f.base, 'fail'), '');
1652
+ await assert.rejects(api.stageRuntime(f.input), /exit 7/u);
1653
+ assert.equal(readFileSync(f.counter, 'utf8'), 'x');
1654
+ assert.equal(existsSync(f.input.runtimeDirectory), false);
1655
+ }
1656
+ finally {
1657
+ f.cleanup();
1658
+ }
1659
+ });
1660
+ test('output retirement preserves its existing cause after a successful real stage', async () => {
1661
+ const api = await producer();
1662
+ const f = await fixture();
1663
+ const prior = new Error('Existing retirement cause');
1664
+ const primary = new Error('Synthetic retirement refusal', { cause: prior });
1665
+ try {
1666
+ retirementFailure.directory = join(f.root, '.git/ai-delivery/output-observation');
1667
+ retirementFailure.error = primary;
1668
+ retirementFailure.hits = 0;
1669
+ await assert.rejects(api.stageRuntime(f.input), (error) => error === primary);
1670
+ assert.equal(retirementFailure.hits, 1);
1671
+ assert.equal(primary.cause, prior, 'successful operation does not add a failure cause');
1672
+ assert.equal(JSON.parse(readFileSync(join(f.input.runtimeDirectory, 'runtime-stage.json'), 'utf8'))
1673
+ .status, 'complete');
1674
+ assert.equal((await api.stageRuntime(f.input)).reused, true);
1675
+ assert.equal(readFileSync(f.counter, 'utf8'), 'x');
1676
+ }
1677
+ finally {
1678
+ retirementFailure.directory = '';
1679
+ retirementFailure.error = undefined;
1680
+ f.cleanup();
1681
+ }
1682
+ });
1159
1683
  test('admission reports unknown durability with exact same-stage reconciliation and preserves desired bytes', async () => {
1160
1684
  const api = await producer();
1161
1685
  const f = await fixture();
@@ -1236,6 +1760,10 @@ for (const denied of [
1236
1760
  });
1237
1761
  }
1238
1762
  test('setup interruption child', { skip: !process.env.AI_DELIVERY_SETUP_INTERRUPT_INPUT }, async () => {
1763
+ if (process.env.AI_DELIVERY_CLI_PREPARE) {
1764
+ await prepareOwnedCliStage();
1765
+ return;
1766
+ }
1239
1767
  const api = await producer();
1240
1768
  const phase = process.env.AI_DELIVERY_SETUP_LOG_INTERRUPT_PHASE;
1241
1769
  if (phase) {
@@ -1428,6 +1956,165 @@ for (const native of [false, true]) {
1428
1956
  });
1429
1957
  }
1430
1958
  const stageAdmitCase = 'CLI stage and admit execute the same public producer with explicit authority and prior absence';
1959
+ const preparedCliSchema = z.strictObject({
1960
+ ownerRoot: z.string(),
1961
+ base: z.string(),
1962
+ stageId: z.string().regex(/^sha256:[a-f0-9]{64}$/u),
1963
+ configPath: z.string(),
1964
+ npmBin: z.string(),
1965
+ author: z.literal('host-user'),
1966
+ reviewer: z.literal('reviewer[bot]'),
1967
+ input: z.strictObject({
1968
+ authority: z.literal('runtime:stage'),
1969
+ identity: z.literal('host-author'),
1970
+ repoRoot: z.string(),
1971
+ archivePath: z.string(),
1972
+ expectedArchiveSha256: z.string(),
1973
+ packageVersion: z.literal('0.3.5'),
1974
+ expectedSourceCommit: z.string(),
1975
+ expectedConfigDigest: z.string(),
1976
+ runtimeDirectory: z.string(),
1977
+ }),
1978
+ files: z.array(z.strictObject({ path: z.string(), digest: z.string() })).length(6),
1979
+ });
1980
+ function preparedCliClosure(input) {
1981
+ const npmRoot = join(dirname(process.execPath), '../lib/node_modules/npm');
1982
+ assert.equal(JSON.parse(readFileSync(join(npmRoot, 'package.json'), 'utf8')).version, '11.19.0');
1983
+ const result = spawnSync(process.execPath, [
1984
+ join(npmRoot, 'bin/npm-cli.js'),
1985
+ 'ls',
1986
+ '--prefix',
1987
+ input.runtimeDirectory,
1988
+ '--omit=dev',
1989
+ '--all',
1990
+ '--json',
1991
+ '--logs-max',
1992
+ '0',
1993
+ ], {
1994
+ cwd: input.repoRoot,
1995
+ encoding: 'utf8',
1996
+ maxBuffer: 1024 ** 2,
1997
+ });
1998
+ assert.equal(result.error, undefined);
1999
+ assert.equal(result.status, 0, result.stderr + result.stdout);
2000
+ const graph = JSON.parse(result.stdout);
2001
+ assert.equal(graph.problems, undefined);
2002
+ const dependency = graph.dependencies['@aviaratech/ai-delivery'];
2003
+ assert.equal(dependency.version, input.packageVersion);
2004
+ assert.equal(dependency.resolved, `file:${join(input.runtimeDirectory, 'reviewed-archive.tgz')}`);
2005
+ assert.equal(dependency.invalid, undefined);
2006
+ assert.equal(dependency.missing, undefined);
2007
+ }
2008
+ function readPreparedCli(ownerRoot) {
2009
+ assert.equal(realpathSync(ownerRoot), ownerRoot);
2010
+ const prepared = preparedCliSchema.parse(JSON.parse(privateFiles.assertPrivateFile(join(ownerRoot, 'prepared.json'), { maxBytes: 16 * 1024 }).toString('utf8')));
2011
+ assert.equal(prepared.ownerRoot, ownerRoot);
2012
+ const below = (path) => {
2013
+ const name = relative(ownerRoot, path);
2014
+ assert.ok(name !== '' && name !== '..' && !name.startsWith('..' + sep) && !isAbsolute(name));
2015
+ assert.equal(realpathSync(path), path);
2016
+ };
2017
+ for (const path of [
2018
+ prepared.base,
2019
+ prepared.configPath,
2020
+ prepared.npmBin,
2021
+ prepared.input.repoRoot,
2022
+ prepared.input.archivePath,
2023
+ prepared.input.runtimeDirectory,
2024
+ ...prepared.files.map((f) => f.path),
2025
+ ])
2026
+ below(path);
2027
+ assert.equal(dirname(prepared.base), ownerRoot);
2028
+ assert.ok(prepared.base.split(sep).at(-1).startsWith('ai-delivery-setup-'));
2029
+ assert.equal(prepared.input.repoRoot, join(prepared.base, 'consumer'));
2030
+ assert.equal(prepared.input.runtimeDirectory, join(prepared.base, 'staged'));
2031
+ assert.equal(prepared.input.archivePath, join(prepared.base, 'reviewed archive; inert.tgz'));
2032
+ assert.equal(prepared.configPath, join(prepared.base, 'user.json'));
2033
+ assert.equal(prepared.npmBin, join(prepared.base, 'prepared-npm'));
2034
+ assert.equal(digestBytes(readFileSync(prepared.input.archivePath)), prepared.input.expectedArchiveSha256);
2035
+ assert.equal(git(prepared.input.repoRoot, 'rev-parse', 'HEAD'), prepared.input.expectedSourceCommit);
2036
+ assert.equal(git(prepared.input.repoRoot, 'status', '--porcelain'), '');
2037
+ const recordPath = join(prepared.input.runtimeDirectory, 'runtime-stage.json');
2038
+ const record = JSON.parse(privateFiles.assertPrivateFile(recordPath).toString('utf8'));
2039
+ const { recordId, ...content } = record;
2040
+ assert.equal(digestValue(content), recordId);
2041
+ assert.equal(record.status, 'complete');
2042
+ assert.equal(record.stageId, prepared.stageId, 'Prepared CLI stage identity mismatch');
2043
+ assert.equal(digestValue(record.intent), prepared.stageId);
2044
+ for (const [field, value] of Object.entries({
2045
+ repoRoot: prepared.input.repoRoot,
2046
+ runtimeDirectory: prepared.input.runtimeDirectory,
2047
+ sourceCommit: prepared.input.expectedSourceCommit,
2048
+ configDigest: prepared.input.expectedConfigDigest,
2049
+ archivePath: prepared.input.archivePath,
2050
+ archiveSha256: prepared.input.expectedArchiveSha256,
2051
+ packageVersion: prepared.input.packageVersion,
2052
+ }))
2053
+ assert.equal(record.intent[field], value);
2054
+ assert.deepEqual(record.intent.resourceBounds, {
2055
+ maxAggregateRssBytes: 1024 ** 3,
2056
+ minFreeDiskBytes: 256 * 1024 ** 2,
2057
+ maxNewOutputBytes: 512 * 1024 ** 2,
2058
+ maxCapturedOutputBytes: 1024 ** 2,
2059
+ });
2060
+ const expectedPaths = [
2061
+ recordPath,
2062
+ join(prepared.input.runtimeDirectory, 'package.json'),
2063
+ join(prepared.input.runtimeDirectory, 'package-lock.json'),
2064
+ join(prepared.input.runtimeDirectory, 'reviewed-archive.tgz'),
2065
+ join(prepared.input.runtimeDirectory, 'node_modules/@aviaratech/ai-delivery/dist/cli.js'),
2066
+ prepared.configPath,
2067
+ ];
2068
+ assert.deepEqual(prepared.files.map((f) => f.path), expectedPaths);
2069
+ for (const file of prepared.files)
2070
+ assert.equal(digestBytes(readFileSync(file.path)), file.digest);
2071
+ assert.equal(readFileSync(join(prepared.base, 'installs'), 'utf8'), 'x');
2072
+ return prepared;
2073
+ }
2074
+ async function prepareOwnedCliStage() {
2075
+ const ownerRoot = process.env.AI_DELIVERY_CLI_PREPARE;
2076
+ const f = await fixture(false, ownerRoot);
2077
+ const previousPath = process.env.PATH;
2078
+ const scenario = process.env.AI_DELIVERY_STAGE_ADMIT_SCENARIO;
2079
+ try {
2080
+ writeFileSync(join(f.base, 'unrelated-preparation'), 'unrelated');
2081
+ const npmRoot = join(dirname(process.execPath), '../lib/node_modules/npm');
2082
+ assert.equal(JSON.parse(readFileSync(join(npmRoot, 'package.json'), 'utf8')).version, '11.19.0');
2083
+ const npmBin = join(f.base, 'prepared-npm');
2084
+ mkdirSync(npmBin);
2085
+ writeFileSync(join(npmBin, 'npm'), `#!${process.execPath}\nconst fs=require('node:fs'),assert=require('node:assert/strict');if(process.argv[2]==='install'){assert.ok(process.argv.includes('--ignore-scripts'));fs.appendFileSync(${JSON.stringify(f.counter)},'x');fs.writeFileSync(${JSON.stringify(f.marker)},String(process.pid));}${scenario === 'preparation-failure' ? "process.argv[2]='synthetic-unknown-command';" : ''}${scenario === 'preparation-cancel' ? 'setInterval(()=>{},1000);' : ''}require(${JSON.stringify(join(npmRoot, 'bin/npm-cli.js'))});\n`);
2086
+ chmodSync(join(npmBin, 'npm'), 0o755);
2087
+ process.env.PATH = `${npmBin}:${previousPath ?? ''}`;
2088
+ const stage = await (await producer()).stageRuntime(f.input);
2089
+ preparedCliClosure(f.input);
2090
+ assert.equal(stage.reused, false);
2091
+ assert.equal(existsSync(join(f.root, '.git/ai-delivery/runtime-admission.json')), false);
2092
+ const files = [
2093
+ join(f.input.runtimeDirectory, 'runtime-stage.json'),
2094
+ join(f.input.runtimeDirectory, 'package.json'),
2095
+ join(f.input.runtimeDirectory, 'package-lock.json'),
2096
+ join(f.input.runtimeDirectory, 'reviewed-archive.tgz'),
2097
+ stage.admission.cliPath,
2098
+ join(f.base, 'user.json'),
2099
+ ].map((path) => ({ path, digest: digestBytes(readFileSync(path)) }));
2100
+ atomicJson.writePrivateJsonFileAtomically(join(ownerRoot, 'prepared.json'), {
2101
+ ownerRoot,
2102
+ base: f.base,
2103
+ stageId: stage.stageId,
2104
+ configPath: join(f.base, 'user.json'),
2105
+ npmBin,
2106
+ author: actors.author,
2107
+ reviewer: actors.reviewer,
2108
+ input: f.input,
2109
+ files,
2110
+ });
2111
+ readPreparedCli(ownerRoot);
2112
+ }
2113
+ finally {
2114
+ // The outer supervisor owns fixture disposal, including a killed preparation process.
2115
+ process.env.PATH = previousPath;
2116
+ }
2117
+ }
1431
2118
  // Re-enter this same case so cancellation can contain synchronous CLI work as well as promises.
1432
2119
  // The existing producer supervisor owns the native process; these callbacks only retain its observations.
1433
2120
  async function observeStageAdmitCase(scenario = 'normal', traceFault) {
@@ -1439,7 +2126,7 @@ async function observeStageAdmitCase(scenario = 'normal', traceFault) {
1439
2126
  let cleanupFailure;
1440
2127
  let receiptFailure;
1441
2128
  let lastPhase = [];
1442
- let deadline = performance.now() + 15_000;
2129
+ let deadline = 0;
1443
2130
  const active = new Map();
1444
2131
  let seen = 0;
1445
2132
  let cancelledPhase;
@@ -1451,6 +2138,17 @@ async function observeStageAdmitCase(scenario = 'normal', traceFault) {
1451
2138
  let cleanupState;
1452
2139
  let traceFaultInjected = false;
1453
2140
  let unreadableSince;
2141
+ let prepared;
2142
+ let preparationStartedAt;
2143
+ let preparationElapsedMs;
2144
+ let preparationCompleted = false;
2145
+ const needsPreparation = [
2146
+ 'budget',
2147
+ 'admission-stall',
2148
+ 'handoff-mismatch',
2149
+ 'preparation-failure',
2150
+ 'preparation-cancel',
2151
+ ].includes(scenario);
1454
2152
  const readPhases = () => {
1455
2153
  const value = JSON.parse(privateFiles.assertPrivateFile(tracePath, { maxBytes: 64 * 1024 }).toString('utf8'));
1456
2154
  assert.ok(Array.isArray(value) && value.length <= 64, 'CLI phase count exceeded its bound');
@@ -1486,7 +2184,8 @@ async function observeStageAdmitCase(scenario = 'normal', traceFault) {
1486
2184
  cancellation.abort();
1487
2185
  }
1488
2186
  };
1489
- const watch = setInterval(() => {
2187
+ let watch;
2188
+ const watchPhases = () => {
1490
2189
  try {
1491
2190
  if (existsSync(tracePath)) {
1492
2191
  const phases = readPhases();
@@ -1538,15 +2237,17 @@ async function observeStageAdmitCase(scenario = 'normal', traceFault) {
1538
2237
  cancelledPhase ??= overdue?.[0] ?? (seen === 0 ? 'bootstrap' : 'native-drain');
1539
2238
  cancellation.abort();
1540
2239
  }
1541
- }, 50);
1542
- try {
2240
+ };
2241
+ const executeChild = async (preparing) => {
2242
+ idle = false;
2243
+ failedBytes = undefined;
1543
2244
  const output = await runStageCommand(process.cwd(), [
1544
2245
  process.execPath,
1545
2246
  join(process.cwd(), 'node_modules/vitest/vitest.mjs'),
1546
2247
  'run',
1547
2248
  'dist/setup.test.js',
1548
2249
  '-t',
1549
- `^${stageAdmitCase}$`,
2250
+ preparing ? '^setup interruption child$' : `^${stageAdmitCase}$`,
1550
2251
  ], cancellation.signal, undefined,
1551
2252
  // This bounded synthetic case uses the fixture floor, not a local host's 100 GiB reserve.
1552
2253
  { maxAggregateRssBytes: 3 * 1024 ** 3, minFreeDiskBytes: 256 * 1024 ** 2 }, undefined, undefined, {
@@ -1590,6 +2291,9 @@ async function observeStageAdmitCase(scenario = 'normal', traceFault) {
1590
2291
  AI_DELIVERY_STAGE_ADMIT_CHILD: tracePath,
1591
2292
  AI_DELIVERY_STAGE_ADMIT_SCENARIO: scenario,
1592
2293
  AI_DELIVERY_STAGE_ADMIT_TRACE_FAULT: traceFault ?? '',
2294
+ AI_DELIVERY_CLI_PREPARE: preparing ? root : '',
2295
+ ...(preparing ? { AI_DELIVERY_SETUP_INTERRUPT_INPUT: 'owned-cli-preparation' } : {}),
2296
+ AI_DELIVERY_CLI_PREPARED_ROOT: !preparing && prepared !== undefined ? root : '',
1593
2297
  },
1594
2298
  maxCapturedOutputBytes: 32 * 1024 ** 2,
1595
2299
  includeControllerTree: true,
@@ -1609,6 +2313,38 @@ async function observeStageAdmitCase(scenario = 'normal', traceFault) {
1609
2313
  if (output.includes(Buffer.from('SETUP_CLI_TRACE_FAILURE')))
1610
2314
  receiptFailure ??= 'Child CLI phase write failed';
1611
2315
  process.stdout.write(output);
2316
+ };
2317
+ try {
2318
+ if (needsPreparation) {
2319
+ preparationStartedAt = performance.now();
2320
+ const cancelPreparation = scenario === 'preparation-cancel'
2321
+ ? setInterval(() => {
2322
+ const base = readdirSync(root).find((name) => name.startsWith('ai-delivery-setup-'));
2323
+ if (base !== undefined && existsSync(join(root, base, 'installer-running')))
2324
+ cancellation.abort();
2325
+ }, 50)
2326
+ : undefined;
2327
+ try {
2328
+ await executeChild(true);
2329
+ assert.ok(idle && cleanupFailure === undefined, 'preparation must settle with native quiescence');
2330
+ prepared = readPreparedCli(root);
2331
+ preparedCliClosure(prepared.input);
2332
+ preparationCompleted = true;
2333
+ if (scenario === 'handoff-mismatch')
2334
+ atomicJson.writePrivateJsonFileAtomically(join(root, 'prepared.json'), {
2335
+ ...prepared,
2336
+ stageId: 'sha256:' + '0'.repeat(64),
2337
+ });
2338
+ }
2339
+ finally {
2340
+ if (cancelPreparation !== undefined)
2341
+ clearInterval(cancelPreparation);
2342
+ preparationElapsedMs = performance.now() - preparationStartedAt;
2343
+ }
2344
+ }
2345
+ deadline = performance.now() + 15_000;
2346
+ watch = setInterval(watchPhases, 50);
2347
+ await executeChild(false);
1612
2348
  }
1613
2349
  catch (error) {
1614
2350
  failure = error instanceof Error ? error.message : String(error);
@@ -1616,12 +2352,17 @@ async function observeStageAdmitCase(scenario = 'normal', traceFault) {
1616
2352
  process.stdout.write(failedBytes);
1617
2353
  }
1618
2354
  finally {
1619
- clearInterval(watch);
1620
- try {
1621
- lastPhase = readPhases();
1622
- }
1623
- catch (error) {
1624
- receiptFailure ??= error instanceof Error ? error.message : String(error);
2355
+ if (watch !== undefined)
2356
+ clearInterval(watch);
2357
+ if (needsPreparation && !preparationCompleted)
2358
+ receiptFailure ??= 'CLI preparation failed before completed handoff';
2359
+ else {
2360
+ try {
2361
+ lastPhase = readPhases();
2362
+ }
2363
+ catch (error) {
2364
+ receiptFailure ??= error instanceof Error ? error.message : String(error);
2365
+ }
1625
2366
  }
1626
2367
  if (idle && cleanupFailure === undefined) {
1627
2368
  try {
@@ -1655,6 +2396,8 @@ async function observeStageAdmitCase(scenario = 'normal', traceFault) {
1655
2396
  owned,
1656
2397
  root,
1657
2398
  residualInstaller,
2399
+ preparationElapsedMs,
2400
+ preparationCompleted,
1658
2401
  }) +
1659
2402
  '\n');
1660
2403
  }
@@ -1669,6 +2412,15 @@ async function observeStageAdmitCase(scenario = 'normal', traceFault) {
1669
2412
  traceFaultInjected,
1670
2413
  restoredGlobalsWithPending: failedBytes?.includes(Buffer.from('SETUP_CLI_ENV_RESTORED_WITH_PENDING')) ?? false,
1671
2414
  });
2415
+ if (prepared !== undefined) {
2416
+ // Parent retains original validated bindings even when the child receives the mismatch fault.
2417
+ for (const file of prepared.files)
2418
+ assert.equal(digestBytes(readFileSync(file.path)), file.digest);
2419
+ assert.equal(readFileSync(join(prepared.base, 'installs'), 'utf8'), 'x');
2420
+ preparedCliClosure(prepared.input);
2421
+ if (scenario !== 'budget' || failure !== undefined)
2422
+ assert.equal(existsSync(join(prepared.input.repoRoot, '.git/ai-delivery/runtime-admission.json')), false);
2423
+ }
1672
2424
  rmSync(root, { recursive: true, force: true });
1673
2425
  assert.equal(existsSync(root), false, 'Owned CLI case root was not removed');
1674
2426
  return {
@@ -1680,6 +2432,7 @@ async function observeStageAdmitCase(scenario = 'normal', traceFault) {
1680
2432
  residualInstaller,
1681
2433
  identities: [...identities.values()],
1682
2434
  installerFailureReported: failedBytes?.includes(Buffer.from('exit 7')) ?? false,
2435
+ handoffMismatchReported: failedBytes?.includes(Buffer.from('Prepared CLI stage identity mismatch')) ?? false,
1683
2436
  };
1684
2437
  }
1685
2438
  test(stageAdmitCase, async () => {
@@ -1721,7 +2474,26 @@ test(stageAdmitCase, async () => {
1721
2474
  phase('preparation', 'start');
1722
2475
  if (scenario === 'budget')
1723
2476
  await new Promise((resolve) => setTimeout(resolve, 12_000));
1724
- const f = await fixture();
2477
+ const preparedRoot = process.env.AI_DELIVERY_CLI_PREPARED_ROOT;
2478
+ const prepared = preparedRoot ? readPreparedCli(preparedRoot) : undefined;
2479
+ const ownedFixture = prepared === undefined ? await fixture() : undefined;
2480
+ const f = ownedFixture ?? {
2481
+ base: prepared.base,
2482
+ root: prepared.input.repoRoot,
2483
+ input: prepared.input,
2484
+ counter: join(prepared.base, 'installs'),
2485
+ marker: join(prepared.base, 'installer-running'),
2486
+ };
2487
+ const previousPath = process.env.PATH;
2488
+ if (prepared !== undefined) {
2489
+ vi.stubEnv('AI_DELIVERY_CONFIG', prepared.configPath);
2490
+ process.env.PATH = `${prepared.npmBin}:${previousPath ?? ''}`;
2491
+ assert.equal((await loadDeliveryConfig(f.root)).configDigest, f.input.expectedConfigDigest);
2492
+ assert.equal(actors.author, prepared.author);
2493
+ assert.equal(actors.reviewer, prepared.reviewer);
2494
+ assert.equal(existsSync(join(f.root, '.git/ai-delivery/runtime-admission.json')), false);
2495
+ preparedCliClosure(f.input);
2496
+ }
1725
2497
  if (scenario === 'unfinished')
1726
2498
  writeFileSync(join(f.base, 'wait'), '');
1727
2499
  if (scenario === 'installer-failure')
@@ -1864,6 +2636,13 @@ test(stageAdmitCase, async () => {
1864
2636
  ]);
1865
2637
  phase('assertions:stageId', 'start');
1866
2638
  assert.equal(typeof staged.stageId, 'string');
2639
+ if (prepared !== undefined) {
2640
+ assert.equal(staged.reused, true, 'the actual CLI must reuse the completed prepared stage');
2641
+ assert.equal(staged.stageId, prepared.stageId);
2642
+ assert.equal(readFileSync(f.counter, 'utf8'), 'x');
2643
+ for (const file of prepared.files)
2644
+ assert.equal(digestBytes(readFileSync(file.path)), file.digest);
2645
+ }
1867
2646
  phase('assertions:stageId', 'end');
1868
2647
  const authorCallsBeforeAdmission = actors.authorCalls;
1869
2648
  if (scenario === 'budget')
@@ -1894,7 +2673,10 @@ test(stageAdmitCase, async () => {
1894
2673
  stdout.mockRestore();
1895
2674
  process.argv = argv;
1896
2675
  process.exitCode = exitCode;
1897
- f.cleanup();
2676
+ if (ownedFixture !== undefined)
2677
+ ownedFixture.cleanup();
2678
+ else
2679
+ process.env.PATH = previousPath;
1898
2680
  phase('cleanup', 'end');
1899
2681
  }
1900
2682
  if (traceFailure !== undefined)
@@ -1915,6 +2697,58 @@ test('CLI stage/admit preparation and commands retain separate finite budgets',
1915
2697
  assert.ok(end !== undefined && end.atMs - entry.atMs < 15_000, `${entry.phase} did not complete within its own bound`);
1916
2698
  }
1917
2699
  });
2700
+ test('CLI prepared handoff rejects a mismatched stage identity without reinstall or admission', async () => {
2701
+ const result = await observeStageAdmitCase('handoff-mismatch');
2702
+ assert.equal(result.handoffMismatchReported, true, 'the actual child must refuse its mismatched prepared stage');
2703
+ assert.ok(result.failure !== undefined && result.nativeIdle && result.rootRemoved);
2704
+ assert.equal(result.phases.some((entry) => entry.phase === 'runtime:admit'), false);
2705
+ });
2706
+ for (const fault of ['failure', 'cancel']) {
2707
+ test(`CLI preparation ${fault} retains owned evidence through native drain`, async () => {
2708
+ const previousPath = process.env.PATH;
2709
+ let received;
2710
+ try {
2711
+ await observeStageAdmitCase(`preparation-${fault}`);
2712
+ }
2713
+ catch (error) {
2714
+ received = error;
2715
+ }
2716
+ assert.ok(received instanceof Error, 'failed preparation must retain its owned root for recovery');
2717
+ const error = received;
2718
+ assert.equal(error.nativeIdle, true);
2719
+ assert.ok(error.cleanupState !== undefined);
2720
+ assert.equal(error.restoredGlobalsWithPending, false);
2721
+ assert.equal(realpathSync(error.root), error.root);
2722
+ assert.equal(dirname(error.root), realpathSync(tmpdir()));
2723
+ assert.match(error.root, /ai-delivery-cli-case-/u);
2724
+ const ownership = JSON.parse(privateFiles.assertPrivateFile(join(error.root, 'ownership.json')).toString('utf8'));
2725
+ assert.equal(ownership.idle, true);
2726
+ assert.equal(ownership.owned.rootPid, error.cleanupState.rootPid);
2727
+ assert.equal(ownership.owned.rootIdentity, error.cleanupState.rootIdentity);
2728
+ const { confirmOwnedCleanup } = await import('./verification.js');
2729
+ await confirmOwnedCleanup(error.cleanupState);
2730
+ try {
2731
+ const bases = readdirSync(error.root).filter((name) => name.startsWith('ai-delivery-setup-'));
2732
+ assert.equal(bases.length, 1);
2733
+ const base = join(error.root, bases[0]);
2734
+ assert.equal(readFileSync(join(base, 'unrelated-preparation'), 'utf8'), 'unrelated');
2735
+ assert.equal(readFileSync(join(base, 'installs'), 'utf8'), 'x');
2736
+ assert.equal(existsSync(join(base, 'consumer/.git/ai-delivery/runtime-admission.json')), false);
2737
+ if (fault === 'cancel') {
2738
+ assert.equal(error.residualInstaller?.counter, 'x');
2739
+ assert.ok(error.cleanupState.tracked.has(error.residualInstaller.pid));
2740
+ }
2741
+ assert.equal(process.env.PATH, previousPath);
2742
+ }
2743
+ finally {
2744
+ rmSync(error.root, { recursive: true, force: true });
2745
+ }
2746
+ assert.equal(existsSync(error.root), false);
2747
+ process.stdout.write('SETUP_CLI_PREPARATION_RECOVERY ' +
2748
+ JSON.stringify({ fault, root: error.root, quiescenceRechecked: true, removed: true }) +
2749
+ '\n');
2750
+ });
2751
+ }
1918
2752
  test('CLI stage/admit keeps an unfinished real installer owned until native quiescence', async () => {
1919
2753
  const result = await observeStageAdmitCase('unfinished');
1920
2754
  assert.ok(result.failure !== undefined && result.nativeIdle && result.rootRemoved);