@aviaratech/ai-delivery 0.3.30 → 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.
- package/dist/cli.js +2 -5
- package/dist/cli.js.map +1 -1
- package/dist/cliResult.d.ts +1 -0
- package/dist/cliResult.js +8 -0
- package/dist/cliResult.js.map +1 -1
- package/dist/cliResult.test.js +176 -0
- package/dist/cliResult.test.js.map +1 -1
- package/dist/errors.d.ts +19 -0
- package/dist/errors.js +52 -0
- package/dist/errors.js.map +1 -1
- package/dist/github/client.d.ts +5 -0
- package/dist/github/client.js +142 -6
- package/dist/github/client.js.map +1 -1
- package/dist/github/machineAuth.test.js +284 -1
- package/dist/github/machineAuth.test.js.map +1 -1
- package/dist/lifecycle.test.js +72 -6
- package/dist/lifecycle.test.js.map +1 -1
- package/dist/pluginAuthProbe.test.js +25 -0
- package/dist/pluginAuthProbe.test.js.map +1 -1
- package/dist/pluginDoctor.test.js +1 -1
- package/dist/pluginDoctor.test.js.map +1 -1
- package/dist/pluginInstaller.js +169 -49
- package/dist/pluginInstaller.js.map +1 -1
- package/dist/pluginInstaller.test.js +526 -25
- package/dist/pluginInstaller.test.js.map +1 -1
- package/dist/pr.d.ts +1 -1
- package/dist/pr.js +85 -27
- package/dist/pr.js.map +1 -1
- package/dist/pr.test.js +223 -5
- package/dist/pr.test.js.map +1 -1
- package/dist/prAssociation.test.js +509 -2
- package/dist/prAssociation.test.js.map +1 -1
- package/dist/review.js +11 -0
- package/dist/review.js.map +1 -1
- package/dist/review.test.js +38 -0
- package/dist/review.test.js.map +1 -1
- package/dist/setup.js +65 -2
- package/dist/setup.js.map +1 -1
- package/dist/setup.test.js +1335 -16
- package/dist/setup.test.js.map +1 -1
- package/dist/targetPolicyLocal.test.js +574 -167
- package/dist/targetPolicyLocal.test.js.map +1 -1
- package/dist/verification.js +42 -3
- package/dist/verification.js.map +1 -1
- package/package.json +1 -1
- package/plugins/ai-delivery/.claude-plugin/plugin.json +2 -2
- package/plugins/ai-delivery/plugin.json +1 -1
- package/plugins/ai-delivery/runtime/dist/cli.js +57 -57
- package/plugins/ai-delivery/runtime/package.json +1 -1
package/dist/setup.test.js
CHANGED
|
@@ -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(
|
|
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
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
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) {
|
|
@@ -1427,14 +1955,567 @@ for (const native of [false, true]) {
|
|
|
1427
1955
|
}
|
|
1428
1956
|
});
|
|
1429
1957
|
}
|
|
1430
|
-
|
|
1431
|
-
|
|
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
|
+
}
|
|
2118
|
+
// Re-enter this same case so cancellation can contain synchronous CLI work as well as promises.
|
|
2119
|
+
// The existing producer supervisor owns the native process; these callbacks only retain its observations.
|
|
2120
|
+
async function observeStageAdmitCase(scenario = 'normal', traceFault) {
|
|
2121
|
+
const { runStageCommand } = await import('./verification.js');
|
|
2122
|
+
const root = realpathSync(mkdtempSync(join(tmpdir(), 'ai-delivery-cli-case-')));
|
|
2123
|
+
const tracePath = join(root, 'phases.json');
|
|
2124
|
+
const cancellation = new AbortController();
|
|
2125
|
+
let idle = false;
|
|
2126
|
+
let cleanupFailure;
|
|
2127
|
+
let receiptFailure;
|
|
2128
|
+
let lastPhase = [];
|
|
2129
|
+
let deadline = 0;
|
|
2130
|
+
const active = new Map();
|
|
2131
|
+
let seen = 0;
|
|
2132
|
+
let cancelledPhase;
|
|
2133
|
+
let failure;
|
|
2134
|
+
let failedBytes;
|
|
2135
|
+
let owned;
|
|
2136
|
+
const identities = new Map();
|
|
2137
|
+
let residualInstaller;
|
|
2138
|
+
let cleanupState;
|
|
2139
|
+
let traceFaultInjected = false;
|
|
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);
|
|
2152
|
+
const readPhases = () => {
|
|
2153
|
+
const value = JSON.parse(privateFiles.assertPrivateFile(tracePath, { maxBytes: 64 * 1024 }).toString('utf8'));
|
|
2154
|
+
assert.ok(Array.isArray(value) && value.length <= 64, 'CLI phase count exceeded its bound');
|
|
2155
|
+
let previous = -1;
|
|
2156
|
+
for (const item of value) {
|
|
2157
|
+
assert.ok(item !== null && typeof item === 'object' && Object.keys(item).length === 3, 'CLI phase entry is invalid');
|
|
2158
|
+
const entry = item;
|
|
2159
|
+
assert.ok(typeof entry.phase === 'string' &&
|
|
2160
|
+
entry.phase.length <= 64 &&
|
|
2161
|
+
['start', 'end', 'settled', 'pending'].includes(entry.event ?? '') &&
|
|
2162
|
+
typeof entry.atMs === 'number' &&
|
|
2163
|
+
Number.isFinite(entry.atMs) &&
|
|
2164
|
+
entry.atMs >= 0 &&
|
|
2165
|
+
entry.atMs >= previous, 'CLI phase entry is invalid');
|
|
2166
|
+
previous = entry.atMs;
|
|
2167
|
+
}
|
|
2168
|
+
const phases = value;
|
|
2169
|
+
assert.ok(phases.length >= lastPhase.length &&
|
|
2170
|
+
lastPhase.every((entry, index) => {
|
|
2171
|
+
const current = phases[index];
|
|
2172
|
+
return current.phase === entry.phase && current.event === entry.event && current.atMs === entry.atMs;
|
|
2173
|
+
}), 'CLI phase history changed after observation');
|
|
2174
|
+
return phases;
|
|
2175
|
+
};
|
|
2176
|
+
const save = () => {
|
|
2177
|
+
try {
|
|
2178
|
+
writeFileSync(join(root, 'ownership.json'), JSON.stringify({ idle, owned, cleanupFailure, receiptFailure }), {
|
|
2179
|
+
mode: 0o600,
|
|
2180
|
+
});
|
|
2181
|
+
}
|
|
2182
|
+
catch (error) {
|
|
2183
|
+
receiptFailure = error instanceof Error ? error.message : String(error);
|
|
2184
|
+
cancellation.abort();
|
|
2185
|
+
}
|
|
2186
|
+
};
|
|
2187
|
+
let watch;
|
|
2188
|
+
const watchPhases = () => {
|
|
2189
|
+
try {
|
|
2190
|
+
if (existsSync(tracePath)) {
|
|
2191
|
+
const phases = readPhases();
|
|
2192
|
+
unreadableSince = undefined;
|
|
2193
|
+
lastPhase = phases;
|
|
2194
|
+
for (const entry of phases.slice(seen)) {
|
|
2195
|
+
if (entry.event === 'start')
|
|
2196
|
+
active.set(entry.phase, performance.now() + (scenario === 'unfinished' && entry.phase === 'runtime:stage' ? 30_000 : 15_000));
|
|
2197
|
+
else if (entry.event === 'end' || entry.event === 'settled')
|
|
2198
|
+
active.delete(entry.phase);
|
|
2199
|
+
}
|
|
2200
|
+
if (phases.length > seen)
|
|
2201
|
+
deadline = performance.now() + 15_000;
|
|
2202
|
+
seen = phases.length;
|
|
2203
|
+
if (traceFault !== undefined && traceFault !== 'write' && !traceFaultInjected) {
|
|
2204
|
+
const fixtureRoot = readdirSync(root).find((name) => name.startsWith('ai-delivery-setup-'));
|
|
2205
|
+
const marker = fixtureRoot === undefined ? undefined : join(root, fixtureRoot, 'installer-running');
|
|
2206
|
+
if (marker !== undefined && existsSync(marker)) {
|
|
2207
|
+
assert.equal(readFileSync(join(dirname(marker), 'installs'), 'utf8'), 'x');
|
|
2208
|
+
traceFaultInjected = true;
|
|
2209
|
+
if (traceFault === 'missing')
|
|
2210
|
+
rmSync(tracePath);
|
|
2211
|
+
else if (traceFault === 'oversized') {
|
|
2212
|
+
writeFileSync(tracePath, Buffer.alloc(64 * 1024 + 1, 32));
|
|
2213
|
+
sharedOutputRead.path = tracePath;
|
|
2214
|
+
}
|
|
2215
|
+
else
|
|
2216
|
+
writeFileSync(tracePath, JSON.stringify(Array.from({ length: 65 }, () => phases[0])));
|
|
2217
|
+
}
|
|
2218
|
+
}
|
|
2219
|
+
}
|
|
2220
|
+
else if (seen > 0)
|
|
2221
|
+
throw new Error('CLI phase evidence disappeared after observation');
|
|
2222
|
+
}
|
|
2223
|
+
catch (error) {
|
|
2224
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
2225
|
+
// Atomic replacement can race an identity-bound read. Retry only that bounded observation,
|
|
2226
|
+
// while operation deadlines continue to run; missing, oversized or invalid history fails immediately.
|
|
2227
|
+
const changing = /identity changed before its bounded read|truncated during its bounded read|bytes are missing, corrupt or changed during its bounded read/u.test(message);
|
|
2228
|
+
if (changing)
|
|
2229
|
+
unreadableSince ??= performance.now();
|
|
2230
|
+
if (!changing || performance.now() - unreadableSince >= 1_000) {
|
|
2231
|
+
receiptFailure ??= message;
|
|
2232
|
+
cancellation.abort();
|
|
2233
|
+
}
|
|
2234
|
+
}
|
|
2235
|
+
const overdue = [...active].find(([, limit]) => performance.now() >= limit);
|
|
2236
|
+
if (overdue !== undefined || (active.size === 0 && performance.now() >= deadline)) {
|
|
2237
|
+
cancelledPhase ??= overdue?.[0] ?? (seen === 0 ? 'bootstrap' : 'native-drain');
|
|
2238
|
+
cancellation.abort();
|
|
2239
|
+
}
|
|
2240
|
+
};
|
|
2241
|
+
const executeChild = async (preparing) => {
|
|
2242
|
+
idle = false;
|
|
2243
|
+
failedBytes = undefined;
|
|
2244
|
+
const output = await runStageCommand(process.cwd(), [
|
|
2245
|
+
process.execPath,
|
|
2246
|
+
join(process.cwd(), 'node_modules/vitest/vitest.mjs'),
|
|
2247
|
+
'run',
|
|
2248
|
+
'dist/setup.test.js',
|
|
2249
|
+
'-t',
|
|
2250
|
+
preparing ? '^setup interruption child$' : `^${stageAdmitCase}$`,
|
|
2251
|
+
], cancellation.signal, undefined,
|
|
2252
|
+
// This bounded synthetic case uses the fixture floor, not a local host's 100 GiB reserve.
|
|
2253
|
+
{ maxAggregateRssBytes: 3 * 1024 ** 3, minFreeDiskBytes: 256 * 1024 ** 2 }, undefined, undefined, {
|
|
2254
|
+
starting: () => {
|
|
2255
|
+
idle = false;
|
|
2256
|
+
save();
|
|
2257
|
+
},
|
|
2258
|
+
observed: (state) => {
|
|
2259
|
+
cleanupState = { ...state, tracked: new Map(state.tracked) };
|
|
2260
|
+
for (const member of state.tracked.values()) {
|
|
2261
|
+
if (identities.size >= 512 && !identities.has(`${member.pid}:${member.identity}`)) {
|
|
2262
|
+
receiptFailure ??= 'CLI ownership observation count exceeded its bound';
|
|
2263
|
+
cancellation.abort();
|
|
2264
|
+
break;
|
|
2265
|
+
}
|
|
2266
|
+
identities.set(`${member.pid}:${member.identity}`, {
|
|
2267
|
+
pid: member.pid,
|
|
2268
|
+
identity: member.identity,
|
|
2269
|
+
pgid: member.pgid,
|
|
2270
|
+
});
|
|
2271
|
+
}
|
|
2272
|
+
owned = {
|
|
2273
|
+
rootPid: state.rootPid,
|
|
2274
|
+
rootIdentity: state.rootIdentity,
|
|
2275
|
+
sampled: state.sampled,
|
|
2276
|
+
tracked: [...identities.values()],
|
|
2277
|
+
};
|
|
2278
|
+
save();
|
|
2279
|
+
},
|
|
2280
|
+
idle: () => {
|
|
2281
|
+
idle = true;
|
|
2282
|
+
save();
|
|
2283
|
+
},
|
|
2284
|
+
assertQuiescent: () => assert.ok(idle && cleanupFailure === undefined),
|
|
2285
|
+
}, {
|
|
2286
|
+
environment: {
|
|
2287
|
+
...process.env,
|
|
2288
|
+
TMPDIR: root,
|
|
2289
|
+
TMP: root,
|
|
2290
|
+
TEMP: root,
|
|
2291
|
+
AI_DELIVERY_STAGE_ADMIT_CHILD: tracePath,
|
|
2292
|
+
AI_DELIVERY_STAGE_ADMIT_SCENARIO: scenario,
|
|
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 : '',
|
|
2297
|
+
},
|
|
2298
|
+
maxCapturedOutputBytes: 32 * 1024 ** 2,
|
|
2299
|
+
includeControllerTree: true,
|
|
2300
|
+
failedOutput: (bytes) => {
|
|
2301
|
+
failedBytes = bytes;
|
|
2302
|
+
if (bytes.includes(Buffer.from('SETUP_CLI_TRACE_WRITE_FAULT_WITH_PENDING')))
|
|
2303
|
+
traceFaultInjected = true;
|
|
2304
|
+
if (bytes.includes(Buffer.from('SETUP_CLI_TRACE_FAILURE')))
|
|
2305
|
+
receiptFailure ??= 'Child CLI phase write failed';
|
|
2306
|
+
return ` CLI case output ${digestBytes(bytes)} (${bytes.length} bytes).`;
|
|
2307
|
+
},
|
|
2308
|
+
onCleanupFailure: (reason) => {
|
|
2309
|
+
cleanupFailure = reason;
|
|
2310
|
+
save();
|
|
2311
|
+
},
|
|
2312
|
+
});
|
|
2313
|
+
if (output.includes(Buffer.from('SETUP_CLI_TRACE_FAILURE')))
|
|
2314
|
+
receiptFailure ??= 'Child CLI phase write failed';
|
|
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);
|
|
2348
|
+
}
|
|
2349
|
+
catch (error) {
|
|
2350
|
+
failure = error instanceof Error ? error.message : String(error);
|
|
2351
|
+
if (failedBytes !== undefined)
|
|
2352
|
+
process.stdout.write(failedBytes);
|
|
2353
|
+
}
|
|
2354
|
+
finally {
|
|
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
|
+
}
|
|
2366
|
+
}
|
|
2367
|
+
if (idle && cleanupFailure === undefined) {
|
|
2368
|
+
try {
|
|
2369
|
+
for (const name of readdirSync(root).filter((name) => name.startsWith('ai-delivery-setup-'))) {
|
|
2370
|
+
const base = join(root, name);
|
|
2371
|
+
const marker = join(base, 'installer-running');
|
|
2372
|
+
if (existsSync(marker)) {
|
|
2373
|
+
assert.ok(lstatSync(marker).size <= 64 && lstatSync(join(base, 'installs')).size <= 64);
|
|
2374
|
+
residualInstaller = {
|
|
2375
|
+
pid: Number(readFileSync(marker, 'utf8')),
|
|
2376
|
+
counter: readFileSync(join(base, 'installs'), 'utf8'),
|
|
2377
|
+
};
|
|
2378
|
+
}
|
|
2379
|
+
}
|
|
2380
|
+
}
|
|
2381
|
+
catch (error) {
|
|
2382
|
+
receiptFailure ??= error instanceof Error ? error.message : String(error);
|
|
2383
|
+
}
|
|
2384
|
+
}
|
|
2385
|
+
process.stdout.write('SETUP_CLI_PHASE_RECEIPT ' +
|
|
2386
|
+
JSON.stringify({
|
|
2387
|
+
scenario,
|
|
2388
|
+
traceFault,
|
|
2389
|
+
traceFaultInjected,
|
|
2390
|
+
phases: lastPhase,
|
|
2391
|
+
nativeIdle: idle,
|
|
2392
|
+
cancelledPhase,
|
|
2393
|
+
failure,
|
|
2394
|
+
cleanupFailure,
|
|
2395
|
+
receiptFailure,
|
|
2396
|
+
owned,
|
|
2397
|
+
root,
|
|
2398
|
+
residualInstaller,
|
|
2399
|
+
preparationElapsedMs,
|
|
2400
|
+
preparationCompleted,
|
|
2401
|
+
}) +
|
|
2402
|
+
'\n');
|
|
2403
|
+
}
|
|
2404
|
+
if (!idle || cleanupFailure !== undefined || receiptFailure !== undefined)
|
|
2405
|
+
throw Object.assign(new Error(`CLI case ownership unresolved; preserve ${root}`), {
|
|
2406
|
+
root,
|
|
2407
|
+
nativeIdle: idle,
|
|
2408
|
+
cleanupState,
|
|
2409
|
+
receiptFailure,
|
|
2410
|
+
residualInstaller,
|
|
2411
|
+
retainedPhaseCount: lastPhase.length,
|
|
2412
|
+
traceFaultInjected,
|
|
2413
|
+
restoredGlobalsWithPending: failedBytes?.includes(Buffer.from('SETUP_CLI_ENV_RESTORED_WITH_PENDING')) ?? false,
|
|
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
|
+
}
|
|
2424
|
+
rmSync(root, { recursive: true, force: true });
|
|
2425
|
+
assert.equal(existsSync(root), false, 'Owned CLI case root was not removed');
|
|
2426
|
+
return {
|
|
2427
|
+
phases: lastPhase,
|
|
2428
|
+
nativeIdle: idle,
|
|
2429
|
+
cancelledPhase,
|
|
2430
|
+
failure,
|
|
2431
|
+
rootRemoved: true,
|
|
2432
|
+
residualInstaller,
|
|
2433
|
+
identities: [...identities.values()],
|
|
2434
|
+
installerFailureReported: failedBytes?.includes(Buffer.from('exit 7')) ?? false,
|
|
2435
|
+
handoffMismatchReported: failedBytes?.includes(Buffer.from('Prepared CLI stage identity mismatch')) ?? false,
|
|
2436
|
+
};
|
|
2437
|
+
}
|
|
2438
|
+
test(stageAdmitCase, async () => {
|
|
2439
|
+
const tracePath = process.env.AI_DELIVERY_STAGE_ADMIT_CHILD;
|
|
2440
|
+
if (tracePath === undefined) {
|
|
2441
|
+
const result = await observeStageAdmitCase();
|
|
2442
|
+
assert.equal(result.failure, undefined);
|
|
2443
|
+
return;
|
|
2444
|
+
}
|
|
2445
|
+
const scenario = process.env.AI_DELIVERY_STAGE_ADMIT_SCENARIO;
|
|
2446
|
+
const traceFault = process.env.AI_DELIVERY_STAGE_ADMIT_TRACE_FAULT;
|
|
2447
|
+
const phases = [];
|
|
2448
|
+
let activeCommands = 0;
|
|
2449
|
+
let traceFailure;
|
|
2450
|
+
const phase = (name, event) => {
|
|
2451
|
+
if (traceFailure !== undefined)
|
|
2452
|
+
return;
|
|
2453
|
+
try {
|
|
2454
|
+
assert.ok(phases.length < 64, 'CLI phase count exceeded its bound');
|
|
2455
|
+
phases.push({ phase: name, event, atMs: performance.now() });
|
|
2456
|
+
if (traceFault === 'write' && name === 'import:runtime:stage' && event === 'end') {
|
|
2457
|
+
assert.ok(activeCommands > 0, 'Trace write fault requires an actually pending CLI command');
|
|
2458
|
+
process.stderr.write('SETUP_CLI_TRACE_WRITE_FAULT_WITH_PENDING\n');
|
|
2459
|
+
rmSync(tracePath);
|
|
2460
|
+
mkdirSync(tracePath);
|
|
2461
|
+
}
|
|
2462
|
+
atomicJson.writePrivateJsonFileAtomically(tracePath, phases);
|
|
2463
|
+
}
|
|
2464
|
+
catch (error) {
|
|
2465
|
+
traceFailure = error instanceof Error ? error : new Error(String(error));
|
|
2466
|
+
try {
|
|
2467
|
+
process.stderr.write('SETUP_CLI_TRACE_FAILURE\n');
|
|
2468
|
+
}
|
|
2469
|
+
catch {
|
|
2470
|
+
/* The parent also validates the retained trace. */
|
|
2471
|
+
}
|
|
2472
|
+
}
|
|
2473
|
+
};
|
|
2474
|
+
phase('preparation', 'start');
|
|
2475
|
+
if (scenario === 'budget')
|
|
2476
|
+
await new Promise((resolve) => setTimeout(resolve, 12_000));
|
|
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
|
+
}
|
|
2497
|
+
if (scenario === 'unfinished')
|
|
2498
|
+
writeFileSync(join(f.base, 'wait'), '');
|
|
2499
|
+
if (scenario === 'installer-failure')
|
|
2500
|
+
writeFileSync(join(f.base, 'fail'), '');
|
|
2501
|
+
phase('preparation', 'end');
|
|
1432
2502
|
const argv = process.argv;
|
|
1433
2503
|
const exitCode = process.exitCode;
|
|
1434
2504
|
const stdout = vi.spyOn(process.stdout, 'write');
|
|
2505
|
+
const pending = [];
|
|
2506
|
+
const restoreAuthorObservations = [];
|
|
2507
|
+
const restoreEnvs = vi.unstubAllEnvs.bind(vi);
|
|
2508
|
+
const environmentProbe = traceFault === 'write'
|
|
2509
|
+
? vi.spyOn(vi, 'unstubAllEnvs').mockImplementation(() => {
|
|
2510
|
+
if (activeCommands > 0)
|
|
2511
|
+
process.stderr.write('SETUP_CLI_ENV_RESTORED_WITH_PENDING\n');
|
|
2512
|
+
return restoreEnvs();
|
|
2513
|
+
})
|
|
2514
|
+
: undefined;
|
|
1435
2515
|
try {
|
|
1436
2516
|
const runCli = async (args) => {
|
|
1437
2517
|
const begin = stdout.mock.calls.length;
|
|
2518
|
+
let settled = false;
|
|
1438
2519
|
process.argv = [
|
|
1439
2520
|
process.execPath,
|
|
1440
2521
|
join(process.cwd(), 'dist/cli.js'),
|
|
@@ -1445,16 +2526,93 @@ test('CLI stage and admit execute the same public producer with explicit authori
|
|
|
1445
2526
|
...args,
|
|
1446
2527
|
];
|
|
1447
2528
|
vi.resetModules();
|
|
1448
|
-
|
|
2529
|
+
if (args[0] === 'runtime:admit') {
|
|
2530
|
+
const clientsModule = await import('./github/client.js');
|
|
2531
|
+
const create = clientsModule.createDeliveryGitHubClients;
|
|
2532
|
+
let authorChecks = 0;
|
|
2533
|
+
const clients = vi
|
|
2534
|
+
.spyOn(clientsModule, 'createDeliveryGitHubClients')
|
|
2535
|
+
.mockImplementation(async (...input) => {
|
|
2536
|
+
const client = await create(...input);
|
|
2537
|
+
const authenticatedAuthor = client.authenticatedAuthor;
|
|
2538
|
+
if (authenticatedAuthor !== undefined) {
|
|
2539
|
+
client.authenticatedAuthor = async (...request) => {
|
|
2540
|
+
const name = `admit:author:${++authorChecks}${actors.pauseAuthor ? ':delayed' : ''}`;
|
|
2541
|
+
phase(name, 'start');
|
|
2542
|
+
try {
|
|
2543
|
+
assert.ok(scenario !== 'budget' || authorChecks === 1 || !actors.pauseAuthor, 'Budget fixture repeated its deliberate HTTP delay at another required authority check');
|
|
2544
|
+
const response = await authenticatedAuthor(...request);
|
|
2545
|
+
// This fictional HTTP port can withhold its response; the actual CLI parse remains pending.
|
|
2546
|
+
if (scenario === 'admission-stall')
|
|
2547
|
+
await new Promise(() => { });
|
|
2548
|
+
return response;
|
|
2549
|
+
}
|
|
2550
|
+
finally {
|
|
2551
|
+
// The budget regression needs one four-second response, not one per required recheck.
|
|
2552
|
+
if (scenario === 'budget')
|
|
2553
|
+
actors.pauseAuthor = false;
|
|
2554
|
+
phase(name, 'end');
|
|
2555
|
+
}
|
|
2556
|
+
};
|
|
2557
|
+
}
|
|
2558
|
+
return client;
|
|
2559
|
+
});
|
|
2560
|
+
restoreAuthorObservations.push(() => clients.mockRestore());
|
|
2561
|
+
}
|
|
2562
|
+
const { Command } = await import('commander');
|
|
2563
|
+
const descriptor = Object.getOwnPropertyDescriptor(Command.prototype, 'parseAsync');
|
|
2564
|
+
assert.equal(typeof descriptor?.value, 'function', 'Commander parse operation is unavailable');
|
|
2565
|
+
const parse = descriptor.value;
|
|
2566
|
+
let command;
|
|
2567
|
+
let observation;
|
|
2568
|
+
const observe = vi.spyOn(Command.prototype, 'parseAsync').mockImplementation(function (...input) {
|
|
2569
|
+
phase(args[0], 'start');
|
|
2570
|
+
if (traceFailure !== undefined)
|
|
2571
|
+
throw traceFailure;
|
|
2572
|
+
const operation = parse.apply(this, input);
|
|
2573
|
+
activeCommands++;
|
|
2574
|
+
command = operation;
|
|
2575
|
+
observation = operation.then(() => {
|
|
2576
|
+
activeCommands--;
|
|
2577
|
+
settled = true;
|
|
2578
|
+
phase(args[0], 'settled');
|
|
2579
|
+
}, () => {
|
|
2580
|
+
activeCommands--;
|
|
2581
|
+
settled = true;
|
|
2582
|
+
phase(args[0], 'settled');
|
|
2583
|
+
});
|
|
2584
|
+
pending.push(operation, observation);
|
|
2585
|
+
// Retain observer failures for the explicit join without an interim unhandled rejection.
|
|
2586
|
+
void observation.catch(() => { });
|
|
2587
|
+
return operation;
|
|
2588
|
+
});
|
|
2589
|
+
try {
|
|
2590
|
+
phase(`import:${args[0]}`, 'start');
|
|
2591
|
+
if (traceFailure !== undefined)
|
|
2592
|
+
throw traceFailure;
|
|
2593
|
+
await import('./cli.js');
|
|
2594
|
+
phase(`import:${args[0]}`, 'end');
|
|
2595
|
+
}
|
|
2596
|
+
finally {
|
|
2597
|
+
observe.mockRestore();
|
|
2598
|
+
}
|
|
2599
|
+
assert.ok(command, 'CLI import did not start its actual parse operation');
|
|
2600
|
+
await command;
|
|
2601
|
+
await observation;
|
|
2602
|
+
if (traceFailure !== undefined)
|
|
2603
|
+
throw traceFailure;
|
|
1449
2604
|
for (let i = 0; i < 300; i++) {
|
|
1450
2605
|
const output = stdout.mock.calls
|
|
1451
2606
|
.slice(begin)
|
|
1452
2607
|
.map(([bytes]) => String(bytes))
|
|
1453
2608
|
.find((bytes) => bytes.startsWith('{'));
|
|
1454
|
-
if (output)
|
|
2609
|
+
if (output) {
|
|
2610
|
+
phase(`return:${args[0]}`, settled ? 'end' : 'pending');
|
|
1455
2611
|
return JSON.parse(output);
|
|
2612
|
+
}
|
|
1456
2613
|
await new Promise((resolve) => setTimeout(resolve, 20));
|
|
1457
2614
|
}
|
|
2615
|
+
phase(`return:${args[0]}`, settled ? 'end' : 'pending');
|
|
1458
2616
|
throw new Error('CLI completion output unavailable');
|
|
1459
2617
|
};
|
|
1460
2618
|
const common = [
|
|
@@ -1476,7 +2634,19 @@ test('CLI stage and admit execute the same public producer with explicit authori
|
|
|
1476
2634
|
f.input.packageVersion,
|
|
1477
2635
|
...common,
|
|
1478
2636
|
]);
|
|
2637
|
+
phase('assertions:stageId', 'start');
|
|
1479
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
|
+
}
|
|
2646
|
+
phase('assertions:stageId', 'end');
|
|
2647
|
+
const authorCallsBeforeAdmission = actors.authorCalls;
|
|
2648
|
+
if (scenario === 'budget')
|
|
2649
|
+
actors.pauseAuthor = true;
|
|
1480
2650
|
const admitted = await runCli([
|
|
1481
2651
|
'runtime:admit',
|
|
1482
2652
|
'--authorize-admit',
|
|
@@ -1485,17 +2655,166 @@ test('CLI stage and admit execute the same public producer with explicit authori
|
|
|
1485
2655
|
'--expected-absent',
|
|
1486
2656
|
...common,
|
|
1487
2657
|
]);
|
|
2658
|
+
phase('assertions', 'start');
|
|
2659
|
+
assert.equal(actors.authorCalls - authorCallsBeforeAdmission, 3, 'Admission must authenticate at its initial, locked and final controller checks');
|
|
1488
2660
|
assert.equal(admitted.admission.sourceCommit, f.input.expectedSourceCommit);
|
|
1489
2661
|
assert.equal(readFileSync(f.counter, 'utf8'), 'x');
|
|
1490
2662
|
assert.equal(process.exitCode, exitCode);
|
|
2663
|
+
phase('assertions', 'end');
|
|
1491
2664
|
}
|
|
1492
2665
|
finally {
|
|
2666
|
+
phase('drain', 'start');
|
|
2667
|
+
await Promise.allSettled(pending);
|
|
2668
|
+
for (const restore of restoreAuthorObservations)
|
|
2669
|
+
restore();
|
|
2670
|
+
environmentProbe?.mockRestore();
|
|
2671
|
+
phase('drain', 'end');
|
|
2672
|
+
phase('cleanup', 'start');
|
|
1493
2673
|
stdout.mockRestore();
|
|
1494
2674
|
process.argv = argv;
|
|
1495
2675
|
process.exitCode = exitCode;
|
|
1496
|
-
|
|
2676
|
+
if (ownedFixture !== undefined)
|
|
2677
|
+
ownedFixture.cleanup();
|
|
2678
|
+
else
|
|
2679
|
+
process.env.PATH = previousPath;
|
|
2680
|
+
phase('cleanup', 'end');
|
|
2681
|
+
}
|
|
2682
|
+
if (traceFailure !== undefined)
|
|
2683
|
+
throw traceFailure;
|
|
2684
|
+
},
|
|
2685
|
+
// The parent supervises bootstrap, each overlapping phase, and native drain independently.
|
|
2686
|
+
// Cancellation may terminate this isolated process; it never proves JavaScript settlement.
|
|
2687
|
+
0);
|
|
2688
|
+
test('CLI stage/admit preparation and commands retain separate finite budgets', async () => {
|
|
2689
|
+
const result = await observeStageAdmitCase('budget');
|
|
2690
|
+
const authorChecks = result.phases.filter((entry) => entry.phase.startsWith('admit:author:') && entry.event === 'start');
|
|
2691
|
+
assert.equal(authorChecks.length, 3, 'All three admission authority checks must execute');
|
|
2692
|
+
assert.equal(authorChecks.filter((entry) => entry.phase.endsWith(':delayed')).length, 1, 'The aggregate-budget regression must inject one delayed HTTP response, not repeat it for every authority check');
|
|
2693
|
+
assert.equal(result.failure, undefined, 'A CLI operation failed; inspect the retained phase and ownership evidence');
|
|
2694
|
+
assert.ok(result.phases.at(-1).atMs - result.phases[0].atMs > 15_000);
|
|
2695
|
+
for (const entry of result.phases.filter((entry) => entry.event === 'start')) {
|
|
2696
|
+
const end = result.phases.find((candidate) => candidate.phase === entry.phase && ['end', 'settled'].includes(candidate.event));
|
|
2697
|
+
assert.ok(end !== undefined && end.atMs - entry.atMs < 15_000, `${entry.phase} did not complete within its own bound`);
|
|
2698
|
+
}
|
|
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
|
+
}
|
|
2752
|
+
test('CLI stage/admit keeps an unfinished real installer owned until native quiescence', async () => {
|
|
2753
|
+
const result = await observeStageAdmitCase('unfinished');
|
|
2754
|
+
assert.ok(result.failure !== undefined && result.nativeIdle && result.rootRemoved);
|
|
2755
|
+
assert.equal(result.residualInstaller?.counter, 'x', 'A real installer must execute exactly once');
|
|
2756
|
+
assert.ok(result.identities.some((member) => member.pid === result.residualInstaller?.pid), 'Installer birth identity was not observed by the native supervisor');
|
|
2757
|
+
assert.equal(result.phases.some((entry) => entry.event === 'pending'), false, 'CLI caller relinquished an unfinished command');
|
|
2758
|
+
assert.equal(result.cancelledPhase, 'runtime:stage');
|
|
2759
|
+
assert.equal(result.phases.some((entry) => entry.phase === 'cleanup'), false, 'Child cleaned a fixture with active work');
|
|
2760
|
+
});
|
|
2761
|
+
test('CLI stage/admit joins a failed real installer before restoring its fixture', async () => {
|
|
2762
|
+
const result = await observeStageAdmitCase('installer-failure');
|
|
2763
|
+
assert.ok(result.failure !== undefined && result.nativeIdle && result.rootRemoved);
|
|
2764
|
+
assert.equal(result.installerFailureReported, true, 'The real installer failure was not reported');
|
|
2765
|
+
const settled = result.phases.findIndex((entry) => entry.phase === 'runtime:stage' && entry.event === 'settled');
|
|
2766
|
+
const cleanup = result.phases.findIndex((entry) => entry.phase === 'cleanup' && entry.event === 'start');
|
|
2767
|
+
assert.ok(settled >= 0 && cleanup > settled, 'Failure cleanup preceded actual command settlement');
|
|
2768
|
+
assert.equal(result.phases.some((entry) => entry.phase === 'runtime:admit'), false);
|
|
2769
|
+
});
|
|
2770
|
+
test('CLI stage/admit keeps a stalled admission response owned until native quiescence', async () => {
|
|
2771
|
+
const result = await observeStageAdmitCase('admission-stall');
|
|
2772
|
+
assert.ok(result.failure !== undefined && result.nativeIdle && result.rootRemoved);
|
|
2773
|
+
assert.equal(result.cancelledPhase, 'runtime:admit');
|
|
2774
|
+
assert.ok(result.phases.some((entry) => entry.phase === 'runtime:stage' && entry.event === 'settled'));
|
|
2775
|
+
assert.ok(result.phases.some((entry) => entry.phase === 'admit:author:1' && entry.event === 'start'));
|
|
2776
|
+
assert.equal(result.phases.some((entry) => entry.phase === 'cleanup' ||
|
|
2777
|
+
entry.phase === 'return:runtime:admit' ||
|
|
2778
|
+
(entry.phase === 'admit:author:1' && entry.event === 'end')), false, 'The stalled HTTP response must keep the original command pending until native cancellation');
|
|
2779
|
+
});
|
|
2780
|
+
test.each(['missing', 'oversized', 'records', 'write'])('CLI stage/admit preserves owned recovery evidence when its trace fails: %s', async (fault) => {
|
|
2781
|
+
let failure;
|
|
2782
|
+
sharedOutputRead.unboundedReads = 0;
|
|
2783
|
+
try {
|
|
2784
|
+
try {
|
|
2785
|
+
await observeStageAdmitCase('unfinished', fault);
|
|
2786
|
+
}
|
|
2787
|
+
catch (error) {
|
|
2788
|
+
assert.ok(error instanceof Error);
|
|
2789
|
+
failure = error;
|
|
2790
|
+
}
|
|
2791
|
+
assert.ok(failure?.receiptFailure, 'Unavailable phase evidence was accepted');
|
|
2792
|
+
assert.equal(failure.nativeIdle, true);
|
|
2793
|
+
assert.equal(failure.traceFaultInjected, true, 'The real pending CLI trace fault did not execute');
|
|
2794
|
+
assert.equal(existsSync(failure.root), true, 'Untrusted phase evidence was discarded before recovery');
|
|
2795
|
+
assert.ok(failure.retainedPhaseCount <= 64, 'Invalid final trace replaced validated bounded evidence');
|
|
2796
|
+
assert.equal(sharedOutputRead.unboundedReads, 0, 'Failure handling attempted an unbounded final trace read');
|
|
2797
|
+
assert.equal(failure.restoredGlobalsWithPending, false, 'Trace failure bypassed the actual command join');
|
|
2798
|
+
if (fault !== 'write')
|
|
2799
|
+
assert.equal(failure.residualInstaller?.counter, 'x');
|
|
1497
2800
|
}
|
|
1498
|
-
|
|
2801
|
+
finally {
|
|
2802
|
+
sharedOutputRead.path = '';
|
|
2803
|
+
if (failure?.nativeIdle && failure.cleanupState !== undefined) {
|
|
2804
|
+
const recorded = JSON.parse(privateFiles
|
|
2805
|
+
.assertPrivateFile(join(failure.root, 'ownership.json'), { maxBytes: 256 * 1024 })
|
|
2806
|
+
.toString('utf8'));
|
|
2807
|
+
assert.equal(recorded.idle, true);
|
|
2808
|
+
assert.equal(recorded.owned.rootPid, failure.cleanupState.rootPid);
|
|
2809
|
+
const { confirmOwnedCleanup } = await import('./verification.js');
|
|
2810
|
+
await confirmOwnedCleanup(failure.cleanupState);
|
|
2811
|
+
rmSync(failure.root, { recursive: true, force: true });
|
|
2812
|
+
assert.equal(existsSync(failure.root), false);
|
|
2813
|
+
process.stdout.write(`SETUP_CLI_TRACE_RECOVERY ${JSON.stringify({ fault, root: failure.root, quiescenceRechecked: true, removed: true })}\n`);
|
|
2814
|
+
}
|
|
2815
|
+
sharedOutputRead.unboundedReads = 0;
|
|
2816
|
+
}
|
|
2817
|
+
});
|
|
1499
2818
|
test('actual reviewed 0.3.4 archive qualifies with real npm production installation in a temporary synthetic consumer', { skip: !process.env.AI_DELIVERY_REAL_PACKAGE_ARCHIVE, timeout: 0 }, async () => {
|
|
1500
2819
|
const realPath = process.env.PATH;
|
|
1501
2820
|
const api = await producer();
|