@aviaratech/ai-delivery 0.3.30 → 0.3.31

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 (45) hide show
  1. package/dist/cli.js +2 -5
  2. package/dist/cli.js.map +1 -1
  3. package/dist/cliResult.d.ts +1 -0
  4. package/dist/cliResult.js +8 -0
  5. package/dist/cliResult.js.map +1 -1
  6. package/dist/cliResult.test.js +176 -0
  7. package/dist/cliResult.test.js.map +1 -1
  8. package/dist/errors.d.ts +19 -0
  9. package/dist/errors.js +52 -0
  10. package/dist/errors.js.map +1 -1
  11. package/dist/github/client.d.ts +5 -0
  12. package/dist/github/client.js +142 -6
  13. package/dist/github/client.js.map +1 -1
  14. package/dist/github/machineAuth.test.js +284 -1
  15. package/dist/github/machineAuth.test.js.map +1 -1
  16. package/dist/lifecycle.test.js +72 -6
  17. package/dist/lifecycle.test.js.map +1 -1
  18. package/dist/pluginAuthProbe.test.js +25 -0
  19. package/dist/pluginAuthProbe.test.js.map +1 -1
  20. package/dist/pluginDoctor.test.js +1 -1
  21. package/dist/pluginDoctor.test.js.map +1 -1
  22. package/dist/pluginInstaller.js +169 -49
  23. package/dist/pluginInstaller.js.map +1 -1
  24. package/dist/pluginInstaller.test.js +526 -25
  25. package/dist/pluginInstaller.test.js.map +1 -1
  26. package/dist/pr.d.ts +1 -1
  27. package/dist/pr.js +85 -27
  28. package/dist/pr.js.map +1 -1
  29. package/dist/pr.test.js +223 -5
  30. package/dist/pr.test.js.map +1 -1
  31. package/dist/prAssociation.test.js +509 -2
  32. package/dist/prAssociation.test.js.map +1 -1
  33. package/dist/review.js +11 -0
  34. package/dist/review.js.map +1 -1
  35. package/dist/review.test.js +38 -0
  36. package/dist/review.test.js.map +1 -1
  37. package/dist/setup.test.js +489 -4
  38. package/dist/setup.test.js.map +1 -1
  39. package/dist/targetPolicyLocal.test.js +574 -167
  40. package/dist/targetPolicyLocal.test.js.map +1 -1
  41. package/package.json +1 -1
  42. package/plugins/ai-delivery/.claude-plugin/plugin.json +2 -2
  43. package/plugins/ai-delivery/plugin.json +1 -1
  44. package/plugins/ai-delivery/runtime/dist/cli.js +57 -57
  45. package/plugins/ai-delivery/runtime/package.json +1 -1
@@ -1427,14 +1427,323 @@ for (const native of [false, true]) {
1427
1427
  }
1428
1428
  });
1429
1429
  }
1430
- test('CLI stage and admit execute the same public producer with explicit authority and prior absence', async () => {
1430
+ const stageAdmitCase = 'CLI stage and admit execute the same public producer with explicit authority and prior absence';
1431
+ // Re-enter this same case so cancellation can contain synchronous CLI work as well as promises.
1432
+ // The existing producer supervisor owns the native process; these callbacks only retain its observations.
1433
+ async function observeStageAdmitCase(scenario = 'normal', traceFault) {
1434
+ const { runStageCommand } = await import('./verification.js');
1435
+ const root = realpathSync(mkdtempSync(join(tmpdir(), 'ai-delivery-cli-case-')));
1436
+ const tracePath = join(root, 'phases.json');
1437
+ const cancellation = new AbortController();
1438
+ let idle = false;
1439
+ let cleanupFailure;
1440
+ let receiptFailure;
1441
+ let lastPhase = [];
1442
+ let deadline = performance.now() + 15_000;
1443
+ const active = new Map();
1444
+ let seen = 0;
1445
+ let cancelledPhase;
1446
+ let failure;
1447
+ let failedBytes;
1448
+ let owned;
1449
+ const identities = new Map();
1450
+ let residualInstaller;
1451
+ let cleanupState;
1452
+ let traceFaultInjected = false;
1453
+ let unreadableSince;
1454
+ const readPhases = () => {
1455
+ const value = JSON.parse(privateFiles.assertPrivateFile(tracePath, { maxBytes: 64 * 1024 }).toString('utf8'));
1456
+ assert.ok(Array.isArray(value) && value.length <= 64, 'CLI phase count exceeded its bound');
1457
+ let previous = -1;
1458
+ for (const item of value) {
1459
+ assert.ok(item !== null && typeof item === 'object' && Object.keys(item).length === 3, 'CLI phase entry is invalid');
1460
+ const entry = item;
1461
+ assert.ok(typeof entry.phase === 'string' &&
1462
+ entry.phase.length <= 64 &&
1463
+ ['start', 'end', 'settled', 'pending'].includes(entry.event ?? '') &&
1464
+ typeof entry.atMs === 'number' &&
1465
+ Number.isFinite(entry.atMs) &&
1466
+ entry.atMs >= 0 &&
1467
+ entry.atMs >= previous, 'CLI phase entry is invalid');
1468
+ previous = entry.atMs;
1469
+ }
1470
+ const phases = value;
1471
+ assert.ok(phases.length >= lastPhase.length &&
1472
+ lastPhase.every((entry, index) => {
1473
+ const current = phases[index];
1474
+ return current.phase === entry.phase && current.event === entry.event && current.atMs === entry.atMs;
1475
+ }), 'CLI phase history changed after observation');
1476
+ return phases;
1477
+ };
1478
+ const save = () => {
1479
+ try {
1480
+ writeFileSync(join(root, 'ownership.json'), JSON.stringify({ idle, owned, cleanupFailure, receiptFailure }), {
1481
+ mode: 0o600,
1482
+ });
1483
+ }
1484
+ catch (error) {
1485
+ receiptFailure = error instanceof Error ? error.message : String(error);
1486
+ cancellation.abort();
1487
+ }
1488
+ };
1489
+ const watch = setInterval(() => {
1490
+ try {
1491
+ if (existsSync(tracePath)) {
1492
+ const phases = readPhases();
1493
+ unreadableSince = undefined;
1494
+ lastPhase = phases;
1495
+ for (const entry of phases.slice(seen)) {
1496
+ if (entry.event === 'start')
1497
+ active.set(entry.phase, performance.now() + (scenario === 'unfinished' && entry.phase === 'runtime:stage' ? 30_000 : 15_000));
1498
+ else if (entry.event === 'end' || entry.event === 'settled')
1499
+ active.delete(entry.phase);
1500
+ }
1501
+ if (phases.length > seen)
1502
+ deadline = performance.now() + 15_000;
1503
+ seen = phases.length;
1504
+ if (traceFault !== undefined && traceFault !== 'write' && !traceFaultInjected) {
1505
+ const fixtureRoot = readdirSync(root).find((name) => name.startsWith('ai-delivery-setup-'));
1506
+ const marker = fixtureRoot === undefined ? undefined : join(root, fixtureRoot, 'installer-running');
1507
+ if (marker !== undefined && existsSync(marker)) {
1508
+ assert.equal(readFileSync(join(dirname(marker), 'installs'), 'utf8'), 'x');
1509
+ traceFaultInjected = true;
1510
+ if (traceFault === 'missing')
1511
+ rmSync(tracePath);
1512
+ else if (traceFault === 'oversized') {
1513
+ writeFileSync(tracePath, Buffer.alloc(64 * 1024 + 1, 32));
1514
+ sharedOutputRead.path = tracePath;
1515
+ }
1516
+ else
1517
+ writeFileSync(tracePath, JSON.stringify(Array.from({ length: 65 }, () => phases[0])));
1518
+ }
1519
+ }
1520
+ }
1521
+ else if (seen > 0)
1522
+ throw new Error('CLI phase evidence disappeared after observation');
1523
+ }
1524
+ catch (error) {
1525
+ const message = error instanceof Error ? error.message : String(error);
1526
+ // Atomic replacement can race an identity-bound read. Retry only that bounded observation,
1527
+ // while operation deadlines continue to run; missing, oversized or invalid history fails immediately.
1528
+ 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);
1529
+ if (changing)
1530
+ unreadableSince ??= performance.now();
1531
+ if (!changing || performance.now() - unreadableSince >= 1_000) {
1532
+ receiptFailure ??= message;
1533
+ cancellation.abort();
1534
+ }
1535
+ }
1536
+ const overdue = [...active].find(([, limit]) => performance.now() >= limit);
1537
+ if (overdue !== undefined || (active.size === 0 && performance.now() >= deadline)) {
1538
+ cancelledPhase ??= overdue?.[0] ?? (seen === 0 ? 'bootstrap' : 'native-drain');
1539
+ cancellation.abort();
1540
+ }
1541
+ }, 50);
1542
+ try {
1543
+ const output = await runStageCommand(process.cwd(), [
1544
+ process.execPath,
1545
+ join(process.cwd(), 'node_modules/vitest/vitest.mjs'),
1546
+ 'run',
1547
+ 'dist/setup.test.js',
1548
+ '-t',
1549
+ `^${stageAdmitCase}$`,
1550
+ ], cancellation.signal, undefined,
1551
+ // This bounded synthetic case uses the fixture floor, not a local host's 100 GiB reserve.
1552
+ { maxAggregateRssBytes: 3 * 1024 ** 3, minFreeDiskBytes: 256 * 1024 ** 2 }, undefined, undefined, {
1553
+ starting: () => {
1554
+ idle = false;
1555
+ save();
1556
+ },
1557
+ observed: (state) => {
1558
+ cleanupState = { ...state, tracked: new Map(state.tracked) };
1559
+ for (const member of state.tracked.values()) {
1560
+ if (identities.size >= 512 && !identities.has(`${member.pid}:${member.identity}`)) {
1561
+ receiptFailure ??= 'CLI ownership observation count exceeded its bound';
1562
+ cancellation.abort();
1563
+ break;
1564
+ }
1565
+ identities.set(`${member.pid}:${member.identity}`, {
1566
+ pid: member.pid,
1567
+ identity: member.identity,
1568
+ pgid: member.pgid,
1569
+ });
1570
+ }
1571
+ owned = {
1572
+ rootPid: state.rootPid,
1573
+ rootIdentity: state.rootIdentity,
1574
+ sampled: state.sampled,
1575
+ tracked: [...identities.values()],
1576
+ };
1577
+ save();
1578
+ },
1579
+ idle: () => {
1580
+ idle = true;
1581
+ save();
1582
+ },
1583
+ assertQuiescent: () => assert.ok(idle && cleanupFailure === undefined),
1584
+ }, {
1585
+ environment: {
1586
+ ...process.env,
1587
+ TMPDIR: root,
1588
+ TMP: root,
1589
+ TEMP: root,
1590
+ AI_DELIVERY_STAGE_ADMIT_CHILD: tracePath,
1591
+ AI_DELIVERY_STAGE_ADMIT_SCENARIO: scenario,
1592
+ AI_DELIVERY_STAGE_ADMIT_TRACE_FAULT: traceFault ?? '',
1593
+ },
1594
+ maxCapturedOutputBytes: 32 * 1024 ** 2,
1595
+ includeControllerTree: true,
1596
+ failedOutput: (bytes) => {
1597
+ failedBytes = bytes;
1598
+ if (bytes.includes(Buffer.from('SETUP_CLI_TRACE_WRITE_FAULT_WITH_PENDING')))
1599
+ traceFaultInjected = true;
1600
+ if (bytes.includes(Buffer.from('SETUP_CLI_TRACE_FAILURE')))
1601
+ receiptFailure ??= 'Child CLI phase write failed';
1602
+ return ` CLI case output ${digestBytes(bytes)} (${bytes.length} bytes).`;
1603
+ },
1604
+ onCleanupFailure: (reason) => {
1605
+ cleanupFailure = reason;
1606
+ save();
1607
+ },
1608
+ });
1609
+ if (output.includes(Buffer.from('SETUP_CLI_TRACE_FAILURE')))
1610
+ receiptFailure ??= 'Child CLI phase write failed';
1611
+ process.stdout.write(output);
1612
+ }
1613
+ catch (error) {
1614
+ failure = error instanceof Error ? error.message : String(error);
1615
+ if (failedBytes !== undefined)
1616
+ process.stdout.write(failedBytes);
1617
+ }
1618
+ finally {
1619
+ clearInterval(watch);
1620
+ try {
1621
+ lastPhase = readPhases();
1622
+ }
1623
+ catch (error) {
1624
+ receiptFailure ??= error instanceof Error ? error.message : String(error);
1625
+ }
1626
+ if (idle && cleanupFailure === undefined) {
1627
+ try {
1628
+ for (const name of readdirSync(root).filter((name) => name.startsWith('ai-delivery-setup-'))) {
1629
+ const base = join(root, name);
1630
+ const marker = join(base, 'installer-running');
1631
+ if (existsSync(marker)) {
1632
+ assert.ok(lstatSync(marker).size <= 64 && lstatSync(join(base, 'installs')).size <= 64);
1633
+ residualInstaller = {
1634
+ pid: Number(readFileSync(marker, 'utf8')),
1635
+ counter: readFileSync(join(base, 'installs'), 'utf8'),
1636
+ };
1637
+ }
1638
+ }
1639
+ }
1640
+ catch (error) {
1641
+ receiptFailure ??= error instanceof Error ? error.message : String(error);
1642
+ }
1643
+ }
1644
+ process.stdout.write('SETUP_CLI_PHASE_RECEIPT ' +
1645
+ JSON.stringify({
1646
+ scenario,
1647
+ traceFault,
1648
+ traceFaultInjected,
1649
+ phases: lastPhase,
1650
+ nativeIdle: idle,
1651
+ cancelledPhase,
1652
+ failure,
1653
+ cleanupFailure,
1654
+ receiptFailure,
1655
+ owned,
1656
+ root,
1657
+ residualInstaller,
1658
+ }) +
1659
+ '\n');
1660
+ }
1661
+ if (!idle || cleanupFailure !== undefined || receiptFailure !== undefined)
1662
+ throw Object.assign(new Error(`CLI case ownership unresolved; preserve ${root}`), {
1663
+ root,
1664
+ nativeIdle: idle,
1665
+ cleanupState,
1666
+ receiptFailure,
1667
+ residualInstaller,
1668
+ retainedPhaseCount: lastPhase.length,
1669
+ traceFaultInjected,
1670
+ restoredGlobalsWithPending: failedBytes?.includes(Buffer.from('SETUP_CLI_ENV_RESTORED_WITH_PENDING')) ?? false,
1671
+ });
1672
+ rmSync(root, { recursive: true, force: true });
1673
+ assert.equal(existsSync(root), false, 'Owned CLI case root was not removed');
1674
+ return {
1675
+ phases: lastPhase,
1676
+ nativeIdle: idle,
1677
+ cancelledPhase,
1678
+ failure,
1679
+ rootRemoved: true,
1680
+ residualInstaller,
1681
+ identities: [...identities.values()],
1682
+ installerFailureReported: failedBytes?.includes(Buffer.from('exit 7')) ?? false,
1683
+ };
1684
+ }
1685
+ test(stageAdmitCase, async () => {
1686
+ const tracePath = process.env.AI_DELIVERY_STAGE_ADMIT_CHILD;
1687
+ if (tracePath === undefined) {
1688
+ const result = await observeStageAdmitCase();
1689
+ assert.equal(result.failure, undefined);
1690
+ return;
1691
+ }
1692
+ const scenario = process.env.AI_DELIVERY_STAGE_ADMIT_SCENARIO;
1693
+ const traceFault = process.env.AI_DELIVERY_STAGE_ADMIT_TRACE_FAULT;
1694
+ const phases = [];
1695
+ let activeCommands = 0;
1696
+ let traceFailure;
1697
+ const phase = (name, event) => {
1698
+ if (traceFailure !== undefined)
1699
+ return;
1700
+ try {
1701
+ assert.ok(phases.length < 64, 'CLI phase count exceeded its bound');
1702
+ phases.push({ phase: name, event, atMs: performance.now() });
1703
+ if (traceFault === 'write' && name === 'import:runtime:stage' && event === 'end') {
1704
+ assert.ok(activeCommands > 0, 'Trace write fault requires an actually pending CLI command');
1705
+ process.stderr.write('SETUP_CLI_TRACE_WRITE_FAULT_WITH_PENDING\n');
1706
+ rmSync(tracePath);
1707
+ mkdirSync(tracePath);
1708
+ }
1709
+ atomicJson.writePrivateJsonFileAtomically(tracePath, phases);
1710
+ }
1711
+ catch (error) {
1712
+ traceFailure = error instanceof Error ? error : new Error(String(error));
1713
+ try {
1714
+ process.stderr.write('SETUP_CLI_TRACE_FAILURE\n');
1715
+ }
1716
+ catch {
1717
+ /* The parent also validates the retained trace. */
1718
+ }
1719
+ }
1720
+ };
1721
+ phase('preparation', 'start');
1722
+ if (scenario === 'budget')
1723
+ await new Promise((resolve) => setTimeout(resolve, 12_000));
1431
1724
  const f = await fixture();
1725
+ if (scenario === 'unfinished')
1726
+ writeFileSync(join(f.base, 'wait'), '');
1727
+ if (scenario === 'installer-failure')
1728
+ writeFileSync(join(f.base, 'fail'), '');
1729
+ phase('preparation', 'end');
1432
1730
  const argv = process.argv;
1433
1731
  const exitCode = process.exitCode;
1434
1732
  const stdout = vi.spyOn(process.stdout, 'write');
1733
+ const pending = [];
1734
+ const restoreAuthorObservations = [];
1735
+ const restoreEnvs = vi.unstubAllEnvs.bind(vi);
1736
+ const environmentProbe = traceFault === 'write'
1737
+ ? vi.spyOn(vi, 'unstubAllEnvs').mockImplementation(() => {
1738
+ if (activeCommands > 0)
1739
+ process.stderr.write('SETUP_CLI_ENV_RESTORED_WITH_PENDING\n');
1740
+ return restoreEnvs();
1741
+ })
1742
+ : undefined;
1435
1743
  try {
1436
1744
  const runCli = async (args) => {
1437
1745
  const begin = stdout.mock.calls.length;
1746
+ let settled = false;
1438
1747
  process.argv = [
1439
1748
  process.execPath,
1440
1749
  join(process.cwd(), 'dist/cli.js'),
@@ -1445,16 +1754,93 @@ test('CLI stage and admit execute the same public producer with explicit authori
1445
1754
  ...args,
1446
1755
  ];
1447
1756
  vi.resetModules();
1448
- await import('./cli.js');
1757
+ if (args[0] === 'runtime:admit') {
1758
+ const clientsModule = await import('./github/client.js');
1759
+ const create = clientsModule.createDeliveryGitHubClients;
1760
+ let authorChecks = 0;
1761
+ const clients = vi
1762
+ .spyOn(clientsModule, 'createDeliveryGitHubClients')
1763
+ .mockImplementation(async (...input) => {
1764
+ const client = await create(...input);
1765
+ const authenticatedAuthor = client.authenticatedAuthor;
1766
+ if (authenticatedAuthor !== undefined) {
1767
+ client.authenticatedAuthor = async (...request) => {
1768
+ const name = `admit:author:${++authorChecks}${actors.pauseAuthor ? ':delayed' : ''}`;
1769
+ phase(name, 'start');
1770
+ try {
1771
+ assert.ok(scenario !== 'budget' || authorChecks === 1 || !actors.pauseAuthor, 'Budget fixture repeated its deliberate HTTP delay at another required authority check');
1772
+ const response = await authenticatedAuthor(...request);
1773
+ // This fictional HTTP port can withhold its response; the actual CLI parse remains pending.
1774
+ if (scenario === 'admission-stall')
1775
+ await new Promise(() => { });
1776
+ return response;
1777
+ }
1778
+ finally {
1779
+ // The budget regression needs one four-second response, not one per required recheck.
1780
+ if (scenario === 'budget')
1781
+ actors.pauseAuthor = false;
1782
+ phase(name, 'end');
1783
+ }
1784
+ };
1785
+ }
1786
+ return client;
1787
+ });
1788
+ restoreAuthorObservations.push(() => clients.mockRestore());
1789
+ }
1790
+ const { Command } = await import('commander');
1791
+ const descriptor = Object.getOwnPropertyDescriptor(Command.prototype, 'parseAsync');
1792
+ assert.equal(typeof descriptor?.value, 'function', 'Commander parse operation is unavailable');
1793
+ const parse = descriptor.value;
1794
+ let command;
1795
+ let observation;
1796
+ const observe = vi.spyOn(Command.prototype, 'parseAsync').mockImplementation(function (...input) {
1797
+ phase(args[0], 'start');
1798
+ if (traceFailure !== undefined)
1799
+ throw traceFailure;
1800
+ const operation = parse.apply(this, input);
1801
+ activeCommands++;
1802
+ command = operation;
1803
+ observation = operation.then(() => {
1804
+ activeCommands--;
1805
+ settled = true;
1806
+ phase(args[0], 'settled');
1807
+ }, () => {
1808
+ activeCommands--;
1809
+ settled = true;
1810
+ phase(args[0], 'settled');
1811
+ });
1812
+ pending.push(operation, observation);
1813
+ // Retain observer failures for the explicit join without an interim unhandled rejection.
1814
+ void observation.catch(() => { });
1815
+ return operation;
1816
+ });
1817
+ try {
1818
+ phase(`import:${args[0]}`, 'start');
1819
+ if (traceFailure !== undefined)
1820
+ throw traceFailure;
1821
+ await import('./cli.js');
1822
+ phase(`import:${args[0]}`, 'end');
1823
+ }
1824
+ finally {
1825
+ observe.mockRestore();
1826
+ }
1827
+ assert.ok(command, 'CLI import did not start its actual parse operation');
1828
+ await command;
1829
+ await observation;
1830
+ if (traceFailure !== undefined)
1831
+ throw traceFailure;
1449
1832
  for (let i = 0; i < 300; i++) {
1450
1833
  const output = stdout.mock.calls
1451
1834
  .slice(begin)
1452
1835
  .map(([bytes]) => String(bytes))
1453
1836
  .find((bytes) => bytes.startsWith('{'));
1454
- if (output)
1837
+ if (output) {
1838
+ phase(`return:${args[0]}`, settled ? 'end' : 'pending');
1455
1839
  return JSON.parse(output);
1840
+ }
1456
1841
  await new Promise((resolve) => setTimeout(resolve, 20));
1457
1842
  }
1843
+ phase(`return:${args[0]}`, settled ? 'end' : 'pending');
1458
1844
  throw new Error('CLI completion output unavailable');
1459
1845
  };
1460
1846
  const common = [
@@ -1476,7 +1862,12 @@ test('CLI stage and admit execute the same public producer with explicit authori
1476
1862
  f.input.packageVersion,
1477
1863
  ...common,
1478
1864
  ]);
1865
+ phase('assertions:stageId', 'start');
1479
1866
  assert.equal(typeof staged.stageId, 'string');
1867
+ phase('assertions:stageId', 'end');
1868
+ const authorCallsBeforeAdmission = actors.authorCalls;
1869
+ if (scenario === 'budget')
1870
+ actors.pauseAuthor = true;
1480
1871
  const admitted = await runCli([
1481
1872
  'runtime:admit',
1482
1873
  '--authorize-admit',
@@ -1485,17 +1876,111 @@ test('CLI stage and admit execute the same public producer with explicit authori
1485
1876
  '--expected-absent',
1486
1877
  ...common,
1487
1878
  ]);
1879
+ phase('assertions', 'start');
1880
+ assert.equal(actors.authorCalls - authorCallsBeforeAdmission, 3, 'Admission must authenticate at its initial, locked and final controller checks');
1488
1881
  assert.equal(admitted.admission.sourceCommit, f.input.expectedSourceCommit);
1489
1882
  assert.equal(readFileSync(f.counter, 'utf8'), 'x');
1490
1883
  assert.equal(process.exitCode, exitCode);
1884
+ phase('assertions', 'end');
1491
1885
  }
1492
1886
  finally {
1887
+ phase('drain', 'start');
1888
+ await Promise.allSettled(pending);
1889
+ for (const restore of restoreAuthorObservations)
1890
+ restore();
1891
+ environmentProbe?.mockRestore();
1892
+ phase('drain', 'end');
1893
+ phase('cleanup', 'start');
1493
1894
  stdout.mockRestore();
1494
1895
  process.argv = argv;
1495
1896
  process.exitCode = exitCode;
1496
1897
  f.cleanup();
1898
+ phase('cleanup', 'end');
1899
+ }
1900
+ if (traceFailure !== undefined)
1901
+ throw traceFailure;
1902
+ },
1903
+ // The parent supervises bootstrap, each overlapping phase, and native drain independently.
1904
+ // Cancellation may terminate this isolated process; it never proves JavaScript settlement.
1905
+ 0);
1906
+ test('CLI stage/admit preparation and commands retain separate finite budgets', async () => {
1907
+ const result = await observeStageAdmitCase('budget');
1908
+ const authorChecks = result.phases.filter((entry) => entry.phase.startsWith('admit:author:') && entry.event === 'start');
1909
+ assert.equal(authorChecks.length, 3, 'All three admission authority checks must execute');
1910
+ 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');
1911
+ assert.equal(result.failure, undefined, 'A CLI operation failed; inspect the retained phase and ownership evidence');
1912
+ assert.ok(result.phases.at(-1).atMs - result.phases[0].atMs > 15_000);
1913
+ for (const entry of result.phases.filter((entry) => entry.event === 'start')) {
1914
+ const end = result.phases.find((candidate) => candidate.phase === entry.phase && ['end', 'settled'].includes(candidate.event));
1915
+ assert.ok(end !== undefined && end.atMs - entry.atMs < 15_000, `${entry.phase} did not complete within its own bound`);
1916
+ }
1917
+ });
1918
+ test('CLI stage/admit keeps an unfinished real installer owned until native quiescence', async () => {
1919
+ const result = await observeStageAdmitCase('unfinished');
1920
+ assert.ok(result.failure !== undefined && result.nativeIdle && result.rootRemoved);
1921
+ assert.equal(result.residualInstaller?.counter, 'x', 'A real installer must execute exactly once');
1922
+ assert.ok(result.identities.some((member) => member.pid === result.residualInstaller?.pid), 'Installer birth identity was not observed by the native supervisor');
1923
+ assert.equal(result.phases.some((entry) => entry.event === 'pending'), false, 'CLI caller relinquished an unfinished command');
1924
+ assert.equal(result.cancelledPhase, 'runtime:stage');
1925
+ assert.equal(result.phases.some((entry) => entry.phase === 'cleanup'), false, 'Child cleaned a fixture with active work');
1926
+ });
1927
+ test('CLI stage/admit joins a failed real installer before restoring its fixture', async () => {
1928
+ const result = await observeStageAdmitCase('installer-failure');
1929
+ assert.ok(result.failure !== undefined && result.nativeIdle && result.rootRemoved);
1930
+ assert.equal(result.installerFailureReported, true, 'The real installer failure was not reported');
1931
+ const settled = result.phases.findIndex((entry) => entry.phase === 'runtime:stage' && entry.event === 'settled');
1932
+ const cleanup = result.phases.findIndex((entry) => entry.phase === 'cleanup' && entry.event === 'start');
1933
+ assert.ok(settled >= 0 && cleanup > settled, 'Failure cleanup preceded actual command settlement');
1934
+ assert.equal(result.phases.some((entry) => entry.phase === 'runtime:admit'), false);
1935
+ });
1936
+ test('CLI stage/admit keeps a stalled admission response owned until native quiescence', async () => {
1937
+ const result = await observeStageAdmitCase('admission-stall');
1938
+ assert.ok(result.failure !== undefined && result.nativeIdle && result.rootRemoved);
1939
+ assert.equal(result.cancelledPhase, 'runtime:admit');
1940
+ assert.ok(result.phases.some((entry) => entry.phase === 'runtime:stage' && entry.event === 'settled'));
1941
+ assert.ok(result.phases.some((entry) => entry.phase === 'admit:author:1' && entry.event === 'start'));
1942
+ assert.equal(result.phases.some((entry) => entry.phase === 'cleanup' ||
1943
+ entry.phase === 'return:runtime:admit' ||
1944
+ (entry.phase === 'admit:author:1' && entry.event === 'end')), false, 'The stalled HTTP response must keep the original command pending until native cancellation');
1945
+ });
1946
+ test.each(['missing', 'oversized', 'records', 'write'])('CLI stage/admit preserves owned recovery evidence when its trace fails: %s', async (fault) => {
1947
+ let failure;
1948
+ sharedOutputRead.unboundedReads = 0;
1949
+ try {
1950
+ try {
1951
+ await observeStageAdmitCase('unfinished', fault);
1952
+ }
1953
+ catch (error) {
1954
+ assert.ok(error instanceof Error);
1955
+ failure = error;
1956
+ }
1957
+ assert.ok(failure?.receiptFailure, 'Unavailable phase evidence was accepted');
1958
+ assert.equal(failure.nativeIdle, true);
1959
+ assert.equal(failure.traceFaultInjected, true, 'The real pending CLI trace fault did not execute');
1960
+ assert.equal(existsSync(failure.root), true, 'Untrusted phase evidence was discarded before recovery');
1961
+ assert.ok(failure.retainedPhaseCount <= 64, 'Invalid final trace replaced validated bounded evidence');
1962
+ assert.equal(sharedOutputRead.unboundedReads, 0, 'Failure handling attempted an unbounded final trace read');
1963
+ assert.equal(failure.restoredGlobalsWithPending, false, 'Trace failure bypassed the actual command join');
1964
+ if (fault !== 'write')
1965
+ assert.equal(failure.residualInstaller?.counter, 'x');
1497
1966
  }
1498
- }, 15_000);
1967
+ finally {
1968
+ sharedOutputRead.path = '';
1969
+ if (failure?.nativeIdle && failure.cleanupState !== undefined) {
1970
+ const recorded = JSON.parse(privateFiles
1971
+ .assertPrivateFile(join(failure.root, 'ownership.json'), { maxBytes: 256 * 1024 })
1972
+ .toString('utf8'));
1973
+ assert.equal(recorded.idle, true);
1974
+ assert.equal(recorded.owned.rootPid, failure.cleanupState.rootPid);
1975
+ const { confirmOwnedCleanup } = await import('./verification.js');
1976
+ await confirmOwnedCleanup(failure.cleanupState);
1977
+ rmSync(failure.root, { recursive: true, force: true });
1978
+ assert.equal(existsSync(failure.root), false);
1979
+ process.stdout.write(`SETUP_CLI_TRACE_RECOVERY ${JSON.stringify({ fault, root: failure.root, quiescenceRechecked: true, removed: true })}\n`);
1980
+ }
1981
+ sharedOutputRead.unboundedReads = 0;
1982
+ }
1983
+ });
1499
1984
  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
1985
  const realPath = process.env.PATH;
1501
1986
  const api = await producer();