@aviaratech/ai-delivery 0.3.34 → 0.3.35

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.
Files changed (75) hide show
  1. package/README.md +48 -0
  2. package/dist/boardReconcile.test.d.ts +1 -0
  3. package/dist/boardReconcile.test.js +1685 -0
  4. package/dist/boardReconcile.test.js.map +1 -0
  5. package/dist/cli.js +35 -1
  6. package/dist/cli.js.map +1 -1
  7. package/dist/cliResult.js +21 -1
  8. package/dist/cliResult.js.map +1 -1
  9. package/dist/cliResult.test.js +82 -0
  10. package/dist/cliResult.test.js.map +1 -1
  11. package/dist/config/deliveryConfig.d.ts +32 -0
  12. package/dist/config/deliveryConfig.js +5 -0
  13. package/dist/config/deliveryConfig.js.map +1 -1
  14. package/dist/config/deliveryConfig.test.js +67 -0
  15. package/dist/config/deliveryConfig.test.js.map +1 -1
  16. package/dist/currentTrackingScenario.test.js +6 -4
  17. package/dist/currentTrackingScenario.test.js.map +1 -1
  18. package/dist/directoryIndependent.test.js +2 -2
  19. package/dist/directoryIndependent.test.js.map +1 -1
  20. package/dist/dispatch.d.ts +1 -1
  21. package/dist/dispatch.js +33 -1
  22. package/dist/dispatch.js.map +1 -1
  23. package/dist/errors.d.ts +13 -0
  24. package/dist/errors.js +15 -0
  25. package/dist/errors.js.map +1 -1
  26. package/dist/github/commandIdentityPolicy.js +1 -0
  27. package/dist/github/commandIdentityPolicy.js.map +1 -1
  28. package/dist/github/discovery.d.ts +2 -0
  29. package/dist/github/discovery.js +17 -3
  30. package/dist/github/discovery.js.map +1 -1
  31. package/dist/github/projectDelivery.d.ts +36 -0
  32. package/dist/github/projectDelivery.js +136 -31
  33. package/dist/github/projectDelivery.js.map +1 -1
  34. package/dist/github/relationships.d.ts +5 -2
  35. package/dist/github/relationships.js +59 -2
  36. package/dist/github/relationships.js.map +1 -1
  37. package/dist/issue.d.ts +66 -1
  38. package/dist/issue.js +259 -62
  39. package/dist/issue.js.map +1 -1
  40. package/dist/issueBatchUpdate.test.js +229 -12
  41. package/dist/issueBatchUpdate.test.js.map +1 -1
  42. package/dist/issueTracking.test.js +436 -11
  43. package/dist/issueTracking.test.js.map +1 -1
  44. package/dist/mcp/index.js +4 -0
  45. package/dist/mcp/index.js.map +1 -1
  46. package/dist/mcp/tools.d.ts +592 -0
  47. package/dist/mcp/tools.js +7 -0
  48. package/dist/mcp/tools.js.map +1 -1
  49. package/dist/pluginInstaller.js +21 -23
  50. package/dist/pluginInstaller.js.map +1 -1
  51. package/dist/pluginInstaller.test.js +121 -1
  52. package/dist/pluginInstaller.test.js.map +1 -1
  53. package/dist/pluginPackaging.test.js +135 -6
  54. package/dist/pluginPackaging.test.js.map +1 -1
  55. package/dist/services/boardReconcileService.d.ts +1204 -0
  56. package/dist/services/boardReconcileService.js +1571 -0
  57. package/dist/services/boardReconcileService.js.map +1 -0
  58. package/dist/services/deliveryAdmission.d.ts +2 -0
  59. package/dist/services/deliveryAdmission.js +2 -2
  60. package/dist/services/deliveryAdmission.js.map +1 -1
  61. package/dist/setup.test.js +299 -28
  62. package/dist/setup.test.js.map +1 -1
  63. package/dist/stdoutRegression.test.js +5 -2
  64. package/dist/stdoutRegression.test.js.map +1 -1
  65. package/dist/verification.js +12 -2
  66. package/dist/verification.js.map +1 -1
  67. package/dist/version.d.ts +6 -0
  68. package/dist/version.js +16 -1
  69. package/dist/version.js.map +1 -1
  70. package/package.json +2 -1
  71. package/plugins/ai-delivery/.claude-plugin/plugin.json +2 -2
  72. package/plugins/ai-delivery/plugin.json +1 -1
  73. package/plugins/ai-delivery/runtime/dist/THIRD-PARTY-NOTICES.md +24 -0
  74. package/plugins/ai-delivery/runtime/dist/cli.js +72 -71
  75. package/plugins/ai-delivery/runtime/package.json +1 -1
@@ -109,6 +109,7 @@ const actors = vi.hoisted(() => ({
109
109
  authorStarted: false,
110
110
  authorAborted: false,
111
111
  pauseAuthor: false,
112
+ authorDelayMs: 4_000,
112
113
  }));
113
114
  // Only GitHub HTTP/authentication is synthetic. Resolver, process ownership and file operations are real.
114
115
  vi.mock('./github/client.js', async (original) => ({
@@ -130,7 +131,7 @@ vi.mock('./github/client.js', async (original) => ({
130
131
  if (actors.pauseAuthor) {
131
132
  await new Promise((resolve, reject) => {
132
133
  // A delayed HTTP response bounds this fixture's request, not the stage's elapsed duration.
133
- const response = setTimeout(resolve, 4_000);
134
+ const response = setTimeout(resolve, actors.authorDelayMs);
134
135
  const abort = () => {
135
136
  clearTimeout(response);
136
137
  actors.authorAborted = true;
@@ -183,6 +184,7 @@ async function fixture(native = false, parent = tmpdir()) {
183
184
  actors.authorStarted = false;
184
185
  actors.authorAborted = false;
185
186
  actors.pauseAuthor = false;
187
+ actors.authorDelayMs = 4_000;
186
188
  const base = realpathSync(mkdtempSync(join(parent, 'ai-delivery-setup-')));
187
189
  const root = join(base, 'consumer');
188
190
  mkdirSync(root);
@@ -247,7 +249,7 @@ async function fixture(native = false, parent = tmpdir()) {
247
249
  const counter = join(base, 'installs');
248
250
  const marker = join(base, 'installer-running');
249
251
  // Synthetic installer boundary: the real owned command copies fixture bytes; no process manager is mocked.
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`);
252
+ 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(()=>{if(fs.existsSync(${JSON.stringify(join(base, 'wait-noise'))})){fs.appendFileSync(${JSON.stringify(join(base, 'noise-writes'))},'x');process.stdout.write('pending installer heartbeat\\n');}},1000);\n`);
251
253
  chmodSync(join(bin, 'npm'), 0o755);
252
254
  const previousPath = process.env.PATH;
253
255
  process.env.PATH = `${bin}:${previousPath ?? ''}`;
@@ -269,9 +271,10 @@ async function fixture(native = false, parent = tmpdir()) {
269
271
  input,
270
272
  counter,
271
273
  marker,
272
- cleanup: () => {
274
+ cleanup: (retainFiles = false) => {
273
275
  process.env.PATH = previousPath;
274
- rmSync(base, { recursive: true, force: true });
276
+ if (!retainFiles)
277
+ rmSync(base, { recursive: true, force: true });
275
278
  },
276
279
  };
277
280
  }
@@ -2286,6 +2289,31 @@ async function prepareOwnedCliStage() {
2286
2289
  process.env.PATH = previousPath;
2287
2290
  }
2288
2291
  }
2292
+ const cliBindingSchema = z.strictObject({
2293
+ ownerRoot: z.string(),
2294
+ scenario: z.string(),
2295
+ repoRoot: z.string(),
2296
+ sourceCommit: z.string().regex(/^[a-f0-9]{40}$/u),
2297
+ configDigest: z.string().regex(/^sha256:[a-f0-9]{64}$/u),
2298
+ userConfigDigest: z.string().regex(/^sha256:[a-f0-9]{64}$/u),
2299
+ archivePath: z.string(),
2300
+ archiveSha256: z.string().regex(/^sha256:[a-f0-9]{64}$/u),
2301
+ runtimeDirectory: z.string(),
2302
+ });
2303
+ const cliUnitSchema = z.strictObject({
2304
+ command: z.enum(['runtime:stage', 'runtime:admit']),
2305
+ kind: z.enum(['context', 'preflight', 'installer', 'authority']),
2306
+ call: z.number().int().min(1).max(3),
2307
+ binding: z.string().regex(/^sha256:[a-f0-9]{64}$/u),
2308
+ result: z
2309
+ .string()
2310
+ .regex(/^sha256:[a-f0-9]{64}$/u)
2311
+ .optional(),
2312
+ });
2313
+ function cliUnitResult(unit) {
2314
+ const { result: _result, ...operation } = unit;
2315
+ return digestValue({ ...operation, result: 'validated-success' });
2316
+ }
2289
2317
  // Re-enter this same case so cancellation can contain synchronous CLI work as well as promises.
2290
2318
  // The existing producer supervisor owns the native process; these callbacks only retain its observations.
2291
2319
  async function observeStageAdmitCase(scenario = 'normal', traceFault) {
@@ -2299,6 +2327,10 @@ async function observeStageAdmitCase(scenario = 'normal', traceFault) {
2299
2327
  let lastPhase = [];
2300
2328
  let deadline = 0;
2301
2329
  const active = new Map();
2330
+ const pendingUnits = new Map();
2331
+ const startedUnits = new Set();
2332
+ const completedUnits = [];
2333
+ let fixtureBinding;
2302
2334
  let seen = 0;
2303
2335
  let cancelledPhase;
2304
2336
  let failure;
@@ -2325,7 +2357,10 @@ async function observeStageAdmitCase(scenario = 'normal', traceFault) {
2325
2357
  assert.ok(Array.isArray(value) && value.length <= 64, 'CLI phase count exceeded its bound');
2326
2358
  let previous = -1;
2327
2359
  for (const item of value) {
2328
- assert.ok(item !== null && typeof item === 'object' && Object.keys(item).length === 3, 'CLI phase entry is invalid');
2360
+ assert.ok(item !== null &&
2361
+ typeof item === 'object' &&
2362
+ Object.keys(item).length === ('unit' in item ? 4 : 3) &&
2363
+ Object.keys(item).every((key) => ['phase', 'event', 'atMs', 'unit'].includes(key)), 'CLI phase entry is invalid');
2329
2364
  const entry = item;
2330
2365
  assert.ok(typeof entry.phase === 'string' &&
2331
2366
  entry.phase.length <= 64 &&
@@ -2335,12 +2370,17 @@ async function observeStageAdmitCase(scenario = 'normal', traceFault) {
2335
2370
  entry.atMs >= 0 &&
2336
2371
  entry.atMs >= previous, 'CLI phase entry is invalid');
2337
2372
  previous = entry.atMs;
2373
+ if (entry.unit !== undefined)
2374
+ cliUnitSchema.parse(entry.unit);
2338
2375
  }
2339
2376
  const phases = value;
2340
2377
  assert.ok(phases.length >= lastPhase.length &&
2341
2378
  lastPhase.every((entry, index) => {
2342
2379
  const current = phases[index];
2343
- return current.phase === entry.phase && current.event === entry.event && current.atMs === entry.atMs;
2380
+ return (current.phase === entry.phase &&
2381
+ current.event === entry.event &&
2382
+ current.atMs === entry.atMs &&
2383
+ JSON.stringify(current.unit) === JSON.stringify(entry.unit));
2344
2384
  }), 'CLI phase history changed after observation');
2345
2385
  return phases;
2346
2386
  };
@@ -2356,22 +2396,82 @@ async function observeStageAdmitCase(scenario = 'normal', traceFault) {
2356
2396
  }
2357
2397
  };
2358
2398
  let watch;
2359
- const watchPhases = () => {
2399
+ const readBinding = () => {
2400
+ const binding = cliBindingSchema.parse(JSON.parse(privateFiles.assertPrivateFile(join(root, 'producer-binding.json'), { maxBytes: 8 * 1024 }).toString('utf8')));
2401
+ assert.equal(binding.ownerRoot, root);
2402
+ assert.equal(binding.scenario, scenario);
2403
+ assert.equal(realpathSync(binding.repoRoot), binding.repoRoot);
2404
+ assert.equal(dirname(dirname(binding.repoRoot)), root);
2405
+ assert.equal(binding.runtimeDirectory, join(dirname(binding.repoRoot), 'staged'));
2406
+ assert.equal(binding.archivePath, join(dirname(binding.repoRoot), 'reviewed archive; inert.tgz'));
2407
+ assert.equal(digestBytes(privateFiles.assertPrivateFile(join(dirname(binding.repoRoot), 'user.json'))), binding.userConfigDigest);
2408
+ if (fixtureBinding === undefined) {
2409
+ assert.equal(git(binding.repoRoot, 'rev-parse', 'HEAD'), binding.sourceCommit);
2410
+ assert.equal(digestBytes(readFileSync(binding.archivePath)), binding.archiveSha256);
2411
+ fixtureBinding = binding;
2412
+ }
2413
+ else
2414
+ assert.deepEqual(binding, fixtureBinding, 'CLI producer binding changed');
2415
+ return binding;
2416
+ };
2417
+ const watchPhases = (injectFault = true) => {
2360
2418
  try {
2361
2419
  if (existsSync(tracePath)) {
2362
2420
  const phases = readPhases();
2363
2421
  unreadableSince = undefined;
2364
- lastPhase = phases;
2365
2422
  for (const entry of phases.slice(seen)) {
2423
+ if (entry.unit !== undefined) {
2424
+ const unit = cliUnitSchema.parse(entry.unit);
2425
+ assert.equal(entry.phase, `unit:${unit.command}:${unit.kind}:${unit.call}`);
2426
+ assert.equal(unit.binding, digestValue(readBinding()));
2427
+ assert.ok(active.has(unit.command), 'Completion record is outside its actual CLI invocation');
2428
+ assert.ok(unit.kind !== 'installer' || (unit.command === 'runtime:stage' && unit.call === 1));
2429
+ assert.ok(unit.kind !== 'authority' || unit.command === 'runtime:admit');
2430
+ if (entry.event === 'start') {
2431
+ assert.equal(unit.result, undefined);
2432
+ assert.ok(!startedUnits.has(entry.phase), 'Duplicate CLI unit start');
2433
+ assert.equal(unit.call, 1 + [...startedUnits].filter((name) => name.startsWith(`unit:${unit.command}:${unit.kind}:`)).length);
2434
+ if (unit.kind === 'preflight')
2435
+ assert.ok(completedUnits.includes(`unit:${unit.command}:context:${unit.call}`), 'Preflight preceded its validated context');
2436
+ if (unit.kind === 'context' && unit.call > 1)
2437
+ assert.ok(completedUnits.includes(`unit:${unit.command}:preflight:${unit.call - 1}`), 'Context recheck preceded its prior preflight');
2438
+ if (unit.kind === 'installer')
2439
+ assert.ok(completedUnits.includes('unit:runtime:stage:preflight:1'), 'Installer preceded real preflight');
2440
+ if (unit.kind === 'authority')
2441
+ assert.ok(pendingUnits.has(`unit:runtime:admit:preflight:${unit.call}`), 'Authority check is outside its real preflight');
2442
+ startedUnits.add(entry.phase);
2443
+ pendingUnits.set(entry.phase, unit);
2444
+ }
2445
+ else {
2446
+ assert.equal(entry.event, 'end', 'Only successful delegated units may report completion');
2447
+ const started = pendingUnits.get(entry.phase);
2448
+ assert.ok(started, 'Unmatched or duplicate CLI unit completion');
2449
+ assert.deepEqual({ ...unit, result: undefined }, { ...started, result: undefined });
2450
+ assert.equal(unit.result, cliUnitResult(started), 'CLI unit result binding is invalid');
2451
+ if (unit.command === 'runtime:admit' && unit.kind === 'preflight')
2452
+ assert.ok(completedUnits.includes(`unit:runtime:admit:authority:${unit.call}`), 'Admission preflight lacks successful authority readback');
2453
+ pendingUnits.delete(entry.phase);
2454
+ completedUnits.push(entry.phase);
2455
+ // This measures inactivity between verified substantive units, never total command duration.
2456
+ active.set(unit.command, performance.now() + (scenario === 'unfinished' && unit.command === 'runtime:stage' ? 30_000 : 15_000));
2457
+ }
2458
+ continue;
2459
+ }
2460
+ if (entry.phase.startsWith('unit:')) {
2461
+ assert.equal(entry.event, 'settled', 'CLI unit completion lacks a validated result');
2462
+ assert.ok(pendingUnits.delete(entry.phase), 'Unmatched rejected CLI unit');
2463
+ continue; // A rejected operation is settled, but cannot refresh the stall clock.
2464
+ }
2366
2465
  if (entry.event === 'start')
2367
2466
  active.set(entry.phase, performance.now() + (scenario === 'unfinished' && entry.phase === 'runtime:stage' ? 30_000 : 15_000));
2368
2467
  else if (entry.event === 'end' || entry.event === 'settled')
2369
2468
  active.delete(entry.phase);
2370
2469
  }
2470
+ lastPhase = phases;
2371
2471
  if (phases.length > seen)
2372
2472
  deadline = performance.now() + 15_000;
2373
2473
  seen = phases.length;
2374
- if (traceFault !== undefined && traceFault !== 'write' && !traceFaultInjected) {
2474
+ if (injectFault && !idle && traceFault !== undefined && traceFault !== 'write' && !traceFaultInjected) {
2375
2475
  const fixtureRoot = readdirSync(root).find((name) => name.startsWith('ai-delivery-setup-'));
2376
2476
  const marker = fixtureRoot === undefined ? undefined : join(root, fixtureRoot, 'installer-running');
2377
2477
  if (marker !== undefined && existsSync(marker)) {
@@ -2383,6 +2483,27 @@ async function observeStageAdmitCase(scenario = 'normal', traceFault) {
2383
2483
  writeFileSync(tracePath, Buffer.alloc(64 * 1024 + 1, 32));
2384
2484
  sharedOutputRead.path = tracePath;
2385
2485
  }
2486
+ else if (traceFault.startsWith('completion-')) {
2487
+ const source = phases.find((entry) => traceFault === 'completion-malformed'
2488
+ ? entry.unit?.kind === 'installer' && entry.event === 'start' && pendingUnits.has(entry.phase)
2489
+ : entry.unit !== undefined && entry.event === 'end');
2490
+ assert.ok(source?.unit, 'A completion fault needs its matching real delegated unit first');
2491
+ const injected = {
2492
+ ...source,
2493
+ event: 'end',
2494
+ atMs: phases.at(-1).atMs + 0.001,
2495
+ unit: { ...source.unit },
2496
+ };
2497
+ if (traceFault === 'completion-unmatched') {
2498
+ injected.unit.call++;
2499
+ injected.phase = `unit:${injected.unit.command}:${injected.unit.kind}:${injected.unit.call}`;
2500
+ }
2501
+ else if (traceFault === 'completion-rejected')
2502
+ injected.event = 'settled';
2503
+ else if (traceFault === 'completion-malformed')
2504
+ injected.unit.result = 'sha256:' + '0'.repeat(64);
2505
+ writeFileSync(tracePath, JSON.stringify([...phases, injected]));
2506
+ }
2386
2507
  else
2387
2508
  writeFileSync(tracePath, JSON.stringify(Array.from({ length: 65 }, () => phases[0])));
2388
2509
  }
@@ -2529,7 +2650,7 @@ async function observeStageAdmitCase(scenario = 'normal', traceFault) {
2529
2650
  receiptFailure ??= 'CLI preparation failed before completed handoff';
2530
2651
  else {
2531
2652
  try {
2532
- lastPhase = readPhases();
2653
+ watchPhases(false);
2533
2654
  }
2534
2655
  catch (error) {
2535
2656
  receiptFailure ??= error instanceof Error ? error.message : String(error);
@@ -2545,6 +2666,7 @@ async function observeStageAdmitCase(scenario = 'normal', traceFault) {
2545
2666
  residualInstaller = {
2546
2667
  pid: Number(readFileSync(marker, 'utf8')),
2547
2668
  counter: readFileSync(join(base, 'installs'), 'utf8'),
2669
+ noiseWrites: existsSync(join(base, 'noise-writes')) ? lstatSync(join(base, 'noise-writes')).size : 0,
2548
2670
  };
2549
2671
  }
2550
2672
  }
@@ -2569,6 +2691,7 @@ async function observeStageAdmitCase(scenario = 'normal', traceFault) {
2569
2691
  residualInstaller,
2570
2692
  preparationElapsedMs,
2571
2693
  preparationCompleted,
2694
+ completedUnits,
2572
2695
  }) +
2573
2696
  '\n');
2574
2697
  }
@@ -2583,6 +2706,33 @@ async function observeStageAdmitCase(scenario = 'normal', traceFault) {
2583
2706
  traceFaultInjected,
2584
2707
  restoredGlobalsWithPending: failedBytes?.includes(Buffer.from('SETUP_CLI_ENV_RESTORED_WITH_PENDING')) ?? false,
2585
2708
  });
2709
+ if (fixtureBinding !== undefined) {
2710
+ const savedConfig = process.env.AI_DELIVERY_CONFIG;
2711
+ try {
2712
+ process.env.AI_DELIVERY_CONFIG = join(dirname(fixtureBinding.repoRoot), 'user.json');
2713
+ assert.equal((await loadDeliveryConfig(fixtureBinding.repoRoot)).configDigest, fixtureBinding.configDigest);
2714
+ }
2715
+ finally {
2716
+ if (savedConfig === undefined)
2717
+ delete process.env.AI_DELIVERY_CONFIG;
2718
+ else
2719
+ process.env.AI_DELIVERY_CONFIG = savedConfig;
2720
+ }
2721
+ if (failure === undefined) {
2722
+ assert.equal(pendingUnits.size, 0, 'A successful CLI retained an unfinished semantic unit');
2723
+ const stage = JSON.parse(privateFiles.assertPrivateFile(join(fixtureBinding.runtimeDirectory, 'runtime-stage.json')).toString('utf8'));
2724
+ const { recordId, ...content } = stage;
2725
+ assert.equal(recordId, digestValue(content));
2726
+ assert.equal(stage.status, 'complete');
2727
+ assert.equal(stage.intent.sourceCommit, fixtureBinding.sourceCommit);
2728
+ assert.equal(stage.intent.configDigest, fixtureBinding.configDigest);
2729
+ assert.equal(stage.intent.archiveSha256, fixtureBinding.archiveSha256);
2730
+ assert.deepEqual(JSON.parse(privateFiles
2731
+ .assertPrivateFile(join(fixtureBinding.repoRoot, '.git/ai-delivery/runtime-admission.json'))
2732
+ .toString('utf8')), stage.admission);
2733
+ assert.ok(completedUnits.includes('unit:runtime:stage:installer:1') || prepared !== undefined);
2734
+ }
2735
+ }
2586
2736
  if (prepared !== undefined) {
2587
2737
  // Parent retains original validated bindings even when the child receives the mismatch fault.
2588
2738
  for (const file of prepared.files)
@@ -2596,6 +2746,7 @@ async function observeStageAdmitCase(scenario = 'normal', traceFault) {
2596
2746
  assert.equal(existsSync(root), false, 'Owned CLI case root was not removed');
2597
2747
  return {
2598
2748
  phases: lastPhase,
2749
+ completedUnits,
2599
2750
  nativeIdle: idle,
2600
2751
  cancelledPhase,
2601
2752
  failure,
@@ -2618,12 +2769,12 @@ test(stageAdmitCase, async () => {
2618
2769
  const phases = [];
2619
2770
  let activeCommands = 0;
2620
2771
  let traceFailure;
2621
- const phase = (name, event) => {
2772
+ const phase = (name, event, unit) => {
2622
2773
  if (traceFailure !== undefined)
2623
2774
  return;
2624
2775
  try {
2625
2776
  assert.ok(phases.length < 64, 'CLI phase count exceeded its bound');
2626
- phases.push({ phase: name, event, atMs: performance.now() });
2777
+ phases.push({ phase: name, event, atMs: performance.now(), ...(unit === undefined ? {} : { unit }) });
2627
2778
  if (traceFault === 'write' && name === 'import:runtime:stage' && event === 'end') {
2628
2779
  assert.ok(activeCommands > 0, 'Trace write fault requires an actually pending CLI command');
2629
2780
  process.stderr.write('SETUP_CLI_TRACE_WRITE_FAULT_WITH_PENDING\n');
@@ -2665,16 +2816,31 @@ test(stageAdmitCase, async () => {
2665
2816
  assert.equal(existsSync(join(f.root, '.git/ai-delivery/runtime-admission.json')), false);
2666
2817
  preparedCliClosure(f.input);
2667
2818
  }
2668
- if (scenario === 'unfinished')
2819
+ if (scenario === 'unfinished') {
2669
2820
  writeFileSync(join(f.base, 'wait'), '');
2821
+ writeFileSync(join(f.base, 'wait-noise'), '');
2822
+ }
2670
2823
  if (scenario === 'installer-failure')
2671
2824
  writeFileSync(join(f.base, 'fail'), '');
2825
+ chmodSync(join(f.base, 'user.json'), 0o600);
2826
+ const binding = {
2827
+ ownerRoot: dirname(tracePath),
2828
+ scenario,
2829
+ repoRoot: f.root,
2830
+ sourceCommit: f.input.expectedSourceCommit,
2831
+ configDigest: f.input.expectedConfigDigest,
2832
+ userConfigDigest: digestBytes(readFileSync(join(f.base, 'user.json'))),
2833
+ archivePath: f.input.archivePath,
2834
+ archiveSha256: f.input.expectedArchiveSha256,
2835
+ runtimeDirectory: f.input.runtimeDirectory,
2836
+ };
2837
+ atomicJson.writePrivateJsonFileAtomically(join(dirname(tracePath), 'producer-binding.json'), binding);
2672
2838
  phase('preparation', 'end');
2673
2839
  const argv = process.argv;
2674
2840
  const exitCode = process.exitCode;
2675
2841
  const stdout = vi.spyOn(process.stdout, 'write');
2676
2842
  const pending = [];
2677
- const restoreAuthorObservations = [];
2843
+ const restoreObservations = [];
2678
2844
  const restoreEnvs = vi.unstubAllEnvs.bind(vi);
2679
2845
  const environmentProbe = traceFault === 'write'
2680
2846
  ? vi.spyOn(vi, 'unstubAllEnvs').mockImplementation(() => {
@@ -2697,6 +2863,78 @@ test(stageAdmitCase, async () => {
2697
2863
  ...args,
2698
2864
  ];
2699
2865
  vi.resetModules();
2866
+ const calls = { context: 0, preflight: 0, installer: 0, authority: 0 };
2867
+ const observeUnit = async (kind, operation, validate) => {
2868
+ const unit = {
2869
+ command: args[0],
2870
+ kind,
2871
+ call: ++calls[kind],
2872
+ binding: digestValue(binding),
2873
+ };
2874
+ const name = `unit:${unit.command}:${unit.kind}:${unit.call}`;
2875
+ phase(name, 'start', unit);
2876
+ try {
2877
+ const value = await operation();
2878
+ validate(value);
2879
+ phase(name, 'end', { ...unit, result: cliUnitResult(unit) });
2880
+ return value;
2881
+ }
2882
+ catch (error) {
2883
+ phase(name, 'settled'); // Failure is evidence of settlement, never successful progress.
2884
+ throw error;
2885
+ }
2886
+ };
2887
+ const contextModule = await import('./issue.js');
2888
+ const context = contextModule.loadDeliveryContext;
2889
+ const contextObserver = vi.spyOn(contextModule, 'loadDeliveryContext').mockImplementation((...input) => observeUnit('context', () => context(...input), (value) => {
2890
+ assert.equal(input[0].repoRoot, f.root);
2891
+ assert.equal(input[0].identity, 'host-author');
2892
+ assert.equal(input[0].role, 'author');
2893
+ assert.equal(value.config.repository, 'example/widget');
2894
+ assert.equal(value.configuration?.configDigest, f.input.expectedConfigDigest);
2895
+ assert.equal(value.clients.role, 'author');
2896
+ assert.equal(value.clients.authSource, 'personal');
2897
+ assert.equal(value.clients.credentialSource, 'env:AUTHOR_TOKEN');
2898
+ }));
2899
+ restoreObservations.push(() => contextObserver.mockRestore());
2900
+ const preflightModule = await import('./pr.js');
2901
+ const preflight = preflightModule.preflightReviewRoute;
2902
+ const preflightObserver = vi.spyOn(preflightModule, 'preflightReviewRoute').mockImplementation((...input) => observeUnit('preflight', () => preflight(...input), (value) => {
2903
+ assert.equal(value.author.actorLogin, 'host-user');
2904
+ assert.equal(value.author.identity, 'host-author');
2905
+ assert.equal(value.author.authSource, 'personal');
2906
+ assert.equal(value.reviewer.actorLogin, 'reviewer[bot]');
2907
+ assert.equal(value.reviewer.identity, 'synthetic-reviewer');
2908
+ assert.equal(value.reviewer.repositoryAccess, 'readable');
2909
+ assert.equal(value.rules.visibility, 'unknown');
2910
+ assert.equal(value.rules.observedRequiredApprovals, null);
2911
+ assert.equal(value.approvalEligibility, 'unknown');
2912
+ }));
2913
+ restoreObservations.push(() => preflightObserver.mockRestore());
2914
+ const verificationModule = await import('./verification.js');
2915
+ const writer = verificationModule.withRuntimeSetupWriter;
2916
+ const observedWriter = (root, operation, scope) => writer(root, (runner) => operation({
2917
+ ...runner,
2918
+ run: (...input) => observeUnit('installer', () => runner.run(...input), () => {
2919
+ assert.equal(root, f.root);
2920
+ assert.equal(input[0][0], 'npm');
2921
+ assert.equal(input[0][1], 'install');
2922
+ assert.equal(input[0][input[0].indexOf('--prefix') + 1], f.input.runtimeDirectory);
2923
+ assert.equal(input[0].at(-1), join(f.input.runtimeDirectory, 'reviewed-archive.tgz'));
2924
+ assert.equal(input[4], f.input.runtimeDirectory);
2925
+ runner.assertQuiescent();
2926
+ assert.equal(readFileSync(f.counter, 'utf8'), 'x');
2927
+ const installed = JSON.parse(readFileSync(join(f.input.runtimeDirectory, 'node_modules/@aviaratech/ai-delivery/package.json'), 'utf8'));
2928
+ assert.equal(installed.name, '@aviaratech/ai-delivery');
2929
+ assert.equal(installed.version, f.input.packageVersion);
2930
+ const lock = JSON.parse(readFileSync(join(f.input.runtimeDirectory, 'package-lock.json'), 'utf8'));
2931
+ assert.equal(lock.packages['node_modules/@aviaratech/ai-delivery']?.version, f.input.packageVersion);
2932
+ }),
2933
+ }), scope);
2934
+ const writerObserver = vi
2935
+ .spyOn(verificationModule, 'withRuntimeSetupWriter')
2936
+ .mockImplementation(observedWriter);
2937
+ restoreObservations.push(() => writerObserver.mockRestore());
2700
2938
  if (args[0] === 'runtime:admit') {
2701
2939
  const clientsModule = await import('./github/client.js');
2702
2940
  const create = clientsModule.createDeliveryGitHubClients;
@@ -2712,11 +2950,16 @@ test(stageAdmitCase, async () => {
2712
2950
  phase(name, 'start');
2713
2951
  try {
2714
2952
  assert.ok(scenario !== 'budget' || authorChecks === 1 || !actors.pauseAuthor, 'Budget fixture repeated its deliberate HTTP delay at another required authority check');
2715
- const response = await authenticatedAuthor(...request);
2716
- // This fictional HTTP port can withhold its response; the actual CLI parse remains pending.
2717
- if (scenario === 'admission-stall')
2718
- await new Promise(() => { });
2719
- return response;
2953
+ return await observeUnit('authority', async () => {
2954
+ const response = await authenticatedAuthor(...request);
2955
+ // This fictional HTTP port can withhold its response; the actual CLI parse remains pending.
2956
+ if (scenario === 'admission-stall')
2957
+ await new Promise(() => { });
2958
+ return response;
2959
+ }, (response) => {
2960
+ assert.equal(response.actorLogin, 'host-user');
2961
+ assert.equal(response.credentialIdentity, 'user:37');
2962
+ });
2720
2963
  }
2721
2964
  finally {
2722
2965
  // The budget regression needs one four-second response, not one per required recheck.
@@ -2728,7 +2971,7 @@ test(stageAdmitCase, async () => {
2728
2971
  }
2729
2972
  return client;
2730
2973
  });
2731
- restoreAuthorObservations.push(() => clients.mockRestore());
2974
+ restoreObservations.push(() => clients.mockRestore());
2732
2975
  }
2733
2976
  const { Command } = await import('commander');
2734
2977
  const descriptor = Object.getOwnPropertyDescriptor(Command.prototype, 'parseAsync');
@@ -2794,6 +3037,11 @@ test(stageAdmitCase, async () => {
2794
3037
  '--runtime-directory',
2795
3038
  f.input.runtimeDirectory,
2796
3039
  ];
3040
+ if (scenario === 'progress') {
3041
+ // Two actual authority responses alone exceed the old aggregate command limit.
3042
+ actors.pauseAuthor = true;
3043
+ actors.authorDelayMs = 8_000;
3044
+ }
2797
3045
  const staged = await runCli([
2798
3046
  'runtime:stage',
2799
3047
  '--authorize-stage',
@@ -2815,6 +3063,8 @@ test(stageAdmitCase, async () => {
2815
3063
  assert.equal(digestBytes(readFileSync(file.path)), file.digest);
2816
3064
  }
2817
3065
  phase('assertions:stageId', 'end');
3066
+ if (scenario === 'progress')
3067
+ actors.pauseAuthor = false;
2818
3068
  const authorCallsBeforeAdmission = actors.authorCalls;
2819
3069
  if (scenario === 'budget')
2820
3070
  actors.pauseAuthor = true;
@@ -2836,7 +3086,7 @@ test(stageAdmitCase, async () => {
2836
3086
  finally {
2837
3087
  phase('drain', 'start');
2838
3088
  await Promise.allSettled(pending);
2839
- for (const restore of restoreAuthorObservations)
3089
+ for (const restore of restoreObservations)
2840
3090
  restore();
2841
3091
  environmentProbe?.mockRestore();
2842
3092
  phase('drain', 'end');
@@ -2844,8 +3094,9 @@ test(stageAdmitCase, async () => {
2844
3094
  stdout.mockRestore();
2845
3095
  process.argv = argv;
2846
3096
  process.exitCode = exitCode;
3097
+ // The existing parent owns final artifact corroboration and disposal after native quiescence.
2847
3098
  if (ownedFixture !== undefined)
2848
- ownedFixture.cleanup();
3099
+ ownedFixture.cleanup(true);
2849
3100
  else
2850
3101
  process.env.PATH = previousPath;
2851
3102
  phase('cleanup', 'end');
@@ -2856,7 +3107,16 @@ test(stageAdmitCase, async () => {
2856
3107
  // The parent supervises bootstrap, each overlapping phase, and native drain independently.
2857
3108
  // Cancellation may terminate this isolated process; it never proves JavaScript settlement.
2858
3109
  0);
2859
- test('CLI stage/admit preparation and commands retain separate finite budgets', async () => {
3110
+ test('CLI stage/admit completes substantive work beyond the former aggregate command limit', async () => {
3111
+ const result = await observeStageAdmitCase('progress');
3112
+ assert.equal(result.failure, undefined, 'The actual CLI must complete while real producer units keep completing');
3113
+ const start = result.phases.find((entry) => entry.phase === 'runtime:stage' && entry.event === 'start');
3114
+ const end = result.phases.find((entry) => entry.phase === 'runtime:stage' && entry.event === 'settled');
3115
+ assert.ok(start && end && end.atMs - start.atMs > 15_000);
3116
+ assert.ok(result.nativeIdle && result.rootRemoved);
3117
+ assert.ok(result.phases.some((entry) => entry.phase === 'runtime:admit' && entry.event === 'settled'));
3118
+ });
3119
+ test('CLI stage/admit separates preparation from substantive command progress', async () => {
2860
3120
  const result = await observeStageAdmitCase('budget');
2861
3121
  const authorChecks = result.phases.filter((entry) => entry.phase.startsWith('admit:author:') && entry.event === 'start');
2862
3122
  assert.equal(authorChecks.length, 3, 'All three admission authority checks must execute');
@@ -2865,7 +3125,7 @@ test('CLI stage/admit preparation and commands retain separate finite budgets',
2865
3125
  assert.ok(result.phases.at(-1).atMs - result.phases[0].atMs > 15_000);
2866
3126
  for (const entry of result.phases.filter((entry) => entry.event === 'start')) {
2867
3127
  const end = result.phases.find((candidate) => candidate.phase === entry.phase && ['end', 'settled'].includes(candidate.event));
2868
- assert.ok(end !== undefined && end.atMs - entry.atMs < 15_000, `${entry.phase} did not complete within its own bound`);
3128
+ assert.ok(end !== undefined, `${entry.phase} did not settle`);
2869
3129
  }
2870
3130
  });
2871
3131
  test('CLI prepared handoff rejects a mismatched stage identity without reinstall or admission', async () => {
@@ -2927,6 +3187,8 @@ test('CLI stage/admit keeps an unfinished real installer owned until native quie
2927
3187
  assert.ok(result.identities.some((member) => member.pid === result.residualInstaller?.pid), 'Installer birth identity was not observed by the native supervisor');
2928
3188
  assert.equal(result.phases.some((entry) => entry.event === 'pending'), false, 'CLI caller relinquished an unfinished command');
2929
3189
  assert.equal(result.cancelledPhase, 'runtime:stage');
3190
+ assert.ok((result.residualInstaller?.noiseWrites ?? 0) >= 2, 'The actually stalled installer must emit repeated noise');
3191
+ assert.equal(result.completedUnits.includes('unit:runtime:stage:installer:1'), false);
2930
3192
  assert.equal(result.phases.some((entry) => entry.phase === 'cleanup'), false, 'Child cleaned a fixture with active work');
2931
3193
  });
2932
3194
  test('CLI stage/admit joins a failed real installer before restoring its fixture', async () => {
@@ -2948,7 +3210,16 @@ test('CLI stage/admit keeps a stalled admission response owned until native quie
2948
3210
  entry.phase === 'return:runtime:admit' ||
2949
3211
  (entry.phase === 'admit:author:1' && entry.event === 'end')), false, 'The stalled HTTP response must keep the original command pending until native cancellation');
2950
3212
  });
2951
- test.each(['missing', 'oversized', 'records', 'write'])('CLI stage/admit preserves owned recovery evidence when its trace fails: %s', async (fault) => {
3213
+ test.each([
3214
+ 'missing',
3215
+ 'oversized',
3216
+ 'records',
3217
+ 'write',
3218
+ 'completion-duplicate',
3219
+ 'completion-unmatched',
3220
+ 'completion-rejected',
3221
+ 'completion-malformed',
3222
+ ])('CLI stage/admit preserves owned recovery evidence when its trace fails: %s', async (fault) => {
2952
3223
  let failure;
2953
3224
  sharedOutputRead.unboundedReads = 0;
2954
3225
  try {
@@ -2960,6 +3231,8 @@ test.each(['missing', 'oversized', 'records', 'write'])('CLI stage/admit preserv
2960
3231
  failure = error;
2961
3232
  }
2962
3233
  assert.ok(failure?.receiptFailure, 'Unavailable phase evidence was accepted');
3234
+ if (fault === 'completion-malformed')
3235
+ assert.match(failure.receiptFailure, /CLI unit result binding is invalid/u);
2963
3236
  assert.equal(failure.nativeIdle, true);
2964
3237
  assert.equal(failure.traceFaultInjected, true, 'The real pending CLI trace fault did not execute');
2965
3238
  assert.equal(existsSync(failure.root), true, 'Untrusted phase evidence was discarded before recovery');
@@ -2972,9 +3245,7 @@ test.each(['missing', 'oversized', 'records', 'write'])('CLI stage/admit preserv
2972
3245
  finally {
2973
3246
  sharedOutputRead.path = '';
2974
3247
  if (failure?.nativeIdle && failure.cleanupState !== undefined) {
2975
- const recorded = JSON.parse(privateFiles
2976
- .assertPrivateFile(join(failure.root, 'ownership.json'), { maxBytes: 256 * 1024 })
2977
- .toString('utf8'));
3248
+ const recorded = JSON.parse(privateFiles.assertPrivateFile(join(failure.root, 'ownership.json'), { maxBytes: 256 * 1024 }).toString('utf8'));
2978
3249
  assert.equal(recorded.idle, true);
2979
3250
  assert.equal(recorded.owned.rootPid, failure.cleanupState.rootPid);
2980
3251
  const { confirmOwnedCleanup } = await import('./verification.js');