@aviaratech/ai-delivery 0.3.35 → 0.3.37

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 (301) hide show
  1. package/CONTRIBUTING.md +12 -206
  2. package/README.md +56 -554
  3. package/dist/agent.d.ts +1 -3
  4. package/dist/agent.js +74 -16
  5. package/dist/agent.js.map +7 -1
  6. package/dist/agentReadiness.test.js +73 -67
  7. package/dist/agentReadiness.test.js.map +7 -1
  8. package/dist/boardReconcile.test.js +1651 -1590
  9. package/dist/boardReconcile.test.js.map +7 -1
  10. package/dist/build.test.js +130 -0
  11. package/dist/build.test.js.map +7 -0
  12. package/dist/callerErrors.test.js +91 -0
  13. package/dist/callerErrors.test.js.map +7 -0
  14. package/dist/cli.js +389 -517
  15. package/dist/cli.js.map +7 -1
  16. package/dist/cliResult.d.ts +2 -2
  17. package/dist/cliResult.js +42 -45
  18. package/dist/cliResult.js.map +7 -1
  19. package/dist/cliResult.test.js +424 -369
  20. package/dist/cliResult.test.js.map +7 -1
  21. package/dist/config/deliveryConfig.d.ts +288 -14
  22. package/dist/config/deliveryConfig.js +472 -390
  23. package/dist/config/deliveryConfig.js.map +7 -1
  24. package/dist/config/deliveryConfig.test.js +773 -649
  25. package/dist/config/deliveryConfig.test.js.map +7 -1
  26. package/dist/contributorChecks.test.js +1694 -916
  27. package/dist/contributorChecks.test.js.map +7 -1
  28. package/dist/currentConsumer.test.js +819 -737
  29. package/dist/currentConsumer.test.js.map +7 -1
  30. package/dist/currentTrackingScenario.test.js +499 -479
  31. package/dist/currentTrackingScenario.test.js.map +7 -1
  32. package/dist/delivery/common.js +160 -172
  33. package/dist/delivery/common.js.map +7 -1
  34. package/dist/delivery/delivery.test.js +509 -431
  35. package/dist/delivery/delivery.test.js.map +7 -1
  36. package/dist/delivery/evidence.d.ts +2 -2
  37. package/dist/delivery/evidence.js +133 -120
  38. package/dist/delivery/evidence.js.map +7 -1
  39. package/dist/delivery/index.js +7 -2
  40. package/dist/delivery/index.js.map +7 -1
  41. package/dist/delivery/legacy.js +65 -5
  42. package/dist/delivery/legacy.js.map +7 -1
  43. package/dist/delivery/policy.d.ts +10 -10
  44. package/dist/delivery/policy.js +211 -238
  45. package/dist/delivery/policy.js.map +7 -1
  46. package/dist/delivery/stage.d.ts +18 -18
  47. package/dist/delivery/stage.js +220 -235
  48. package/dist/delivery/stage.js.map +7 -1
  49. package/dist/deliveryBoard.d.ts +74 -0
  50. package/dist/deliveryBoard.js +644 -0
  51. package/dist/deliveryBoard.js.map +7 -0
  52. package/dist/deliveryBoard.test.js +649 -0
  53. package/dist/deliveryBoard.test.js.map +7 -0
  54. package/dist/deliveryHealth.test.js +179 -155
  55. package/dist/deliveryHealth.test.js.map +7 -1
  56. package/dist/dependencyCompatibility.test.js +154 -140
  57. package/dist/dependencyCompatibility.test.js.map +7 -1
  58. package/dist/directoryIndependent.test.js +417 -383
  59. package/dist/directoryIndependent.test.js.map +7 -1
  60. package/dist/dispatch.d.ts +16 -11
  61. package/dist/dispatch.js +316 -354
  62. package/dist/dispatch.js.map +7 -1
  63. package/dist/errors.d.ts +3 -3
  64. package/dist/errors.js +103 -96
  65. package/dist/errors.js.map +7 -1
  66. package/dist/fixtures/deliveryBoardReplay.d.ts +56 -0
  67. package/dist/fixtures/deliveryBoardReplay.js +617 -0
  68. package/dist/fixtures/deliveryBoardReplay.js.map +7 -0
  69. package/dist/fixtures/discovery.d.ts +63 -23
  70. package/dist/fixtures/discovery.js +96 -90
  71. package/dist/fixtures/discovery.js.map +7 -1
  72. package/dist/fixtures/inertEntrypointChild.js +57 -56
  73. package/dist/fixtures/inertEntrypointChild.js.map +7 -1
  74. package/dist/fixtures/inertEntrypoints.d.ts +1 -1
  75. package/dist/fixtures/inertEntrypoints.js +321 -276
  76. package/dist/fixtures/inertEntrypoints.js.map +7 -1
  77. package/dist/fixtures/inertTarget.d.ts +78 -7
  78. package/dist/fixtures/inertTarget.js +769 -691
  79. package/dist/fixtures/inertTarget.js.map +7 -1
  80. package/dist/fixtures/issue63.d.ts +4 -3
  81. package/dist/fixtures/issue63.js +260 -274
  82. package/dist/fixtures/issue63.js.map +7 -1
  83. package/dist/fixtures/issueProjectItems.d.ts +20 -0
  84. package/dist/fixtures/issueProjectItems.js +15 -0
  85. package/dist/fixtures/issueProjectItems.js.map +7 -0
  86. package/dist/fixtures/readView.d.ts +120 -0
  87. package/dist/fixtures/readView.js +172 -0
  88. package/dist/fixtures/readView.js.map +7 -0
  89. package/dist/fixtures/recordedGitHubFlows.d.ts +120 -0
  90. package/dist/fixtures/recordedGitHubFlows.js +109 -0
  91. package/dist/fixtures/recordedGitHubFlows.js.map +7 -0
  92. package/dist/genericCompatibility.test.js +64 -55
  93. package/dist/genericCompatibility.test.js.map +7 -1
  94. package/dist/git.d.ts +0 -3
  95. package/dist/git.js +59 -76
  96. package/dist/git.js.map +7 -1
  97. package/dist/gitProcess.d.ts +1 -1
  98. package/dist/gitProcess.js +58 -53
  99. package/dist/gitProcess.js.map +7 -1
  100. package/dist/github/client.d.ts +2 -2
  101. package/dist/github/client.js +484 -379
  102. package/dist/github/client.js.map +7 -1
  103. package/dist/github/commandIdentityPolicy.js +42 -52
  104. package/dist/github/commandIdentityPolicy.js.map +7 -1
  105. package/dist/github/discovery.d.ts +1 -0
  106. package/dist/github/discovery.js +197 -215
  107. package/dist/github/discovery.js.map +7 -1
  108. package/dist/github/discovery.test.js +223 -177
  109. package/dist/github/discovery.test.js.map +7 -1
  110. package/dist/github/issueHistory.d.ts +2 -2
  111. package/dist/github/issueHistory.js +117 -125
  112. package/dist/github/issueHistory.js.map +7 -1
  113. package/dist/github/machineAuth.d.ts +1 -1
  114. package/dist/github/machineAuth.js +126 -117
  115. package/dist/github/machineAuth.js.map +7 -1
  116. package/dist/github/machineAuth.test.js +755 -639
  117. package/dist/github/machineAuth.test.js.map +7 -1
  118. package/dist/github/nativeIssueMetadata.js +286 -273
  119. package/dist/github/nativeIssueMetadata.js.map +7 -1
  120. package/dist/github/projectDelivery.d.ts +18 -2
  121. package/dist/github/projectDelivery.js +615 -557
  122. package/dist/github/projectDelivery.js.map +7 -1
  123. package/dist/github/relationships.js +433 -389
  124. package/dist/github/relationships.js.map +7 -1
  125. package/dist/github/repo.d.ts +1 -0
  126. package/dist/github/repo.js +123 -96
  127. package/dist/github/repo.js.map +7 -1
  128. package/dist/index.js +3 -3
  129. package/dist/index.js.map +7 -1
  130. package/dist/issue.d.ts +40 -9
  131. package/dist/issue.js +2102 -1742
  132. package/dist/issue.js.map +7 -1
  133. package/dist/issue63History.test.js +40 -42
  134. package/dist/issue63History.test.js.map +7 -1
  135. package/dist/issue63Routes.test.js +154 -143
  136. package/dist/issue63Routes.test.js.map +7 -1
  137. package/dist/issueBatchUpdate.test.js +989 -885
  138. package/dist/issueBatchUpdate.test.js.map +7 -1
  139. package/dist/issueBlockerGuard.test.js +262 -226
  140. package/dist/issueBlockerGuard.test.js.map +7 -1
  141. package/dist/issueContract.d.ts +23 -4
  142. package/dist/issueContract.js +416 -395
  143. package/dist/issueContract.js.map +7 -1
  144. package/dist/issueContract.test.d.ts +4 -3
  145. package/dist/issueContract.test.js +358 -321
  146. package/dist/issueContract.test.js.map +7 -1
  147. package/dist/issueDates.test.js +235 -233
  148. package/dist/issueDates.test.js.map +7 -1
  149. package/dist/issueInfoReadback.test.js +304 -190
  150. package/dist/issueInfoReadback.test.js.map +7 -1
  151. package/dist/issueIntake.test.js +1938 -1732
  152. package/dist/issueIntake.test.js.map +7 -1
  153. package/dist/issueJournal.d.ts +40 -19
  154. package/dist/issueJournal.js +229 -138
  155. package/dist/issueJournal.js.map +7 -1
  156. package/dist/issueJournal.test.js +605 -422
  157. package/dist/issueJournal.test.js.map +7 -1
  158. package/dist/issueRollup.test.d.ts +1 -0
  159. package/dist/issueRollup.test.js +476 -0
  160. package/dist/issueRollup.test.js.map +7 -0
  161. package/dist/issueTracking.test.js +1059 -989
  162. package/dist/issueTracking.test.js.map +7 -1
  163. package/dist/issueWriteRecovery.test.d.ts +1 -0
  164. package/dist/issueWriteRecovery.test.js +260 -0
  165. package/dist/issueWriteRecovery.test.js.map +7 -0
  166. package/dist/lifecycle.test.js +112 -441
  167. package/dist/lifecycle.test.js.map +7 -1
  168. package/dist/logger.js +80 -74
  169. package/dist/logger.js.map +7 -1
  170. package/dist/mcp/index.js +116 -94
  171. package/dist/mcp/index.js.map +7 -1
  172. package/dist/mcp/tools.d.ts +252 -310
  173. package/dist/mcp/tools.js +235 -342
  174. package/dist/mcp/tools.js.map +7 -1
  175. package/dist/pluginAuthProbe.js +63 -52
  176. package/dist/pluginAuthProbe.js.map +7 -1
  177. package/dist/pluginAuthProbe.test.js +85 -62
  178. package/dist/pluginAuthProbe.test.js.map +7 -1
  179. package/dist/pluginCredentials.test.js +282 -259
  180. package/dist/pluginCredentials.test.js.map +7 -1
  181. package/dist/pluginDoctor.test.js +653 -588
  182. package/dist/pluginDoctor.test.js.map +7 -1
  183. package/dist/pluginInstaller.d.ts +7 -5
  184. package/dist/pluginInstaller.js +1173 -1229
  185. package/dist/pluginInstaller.js.map +7 -1
  186. package/dist/pluginInstaller.test.js +1842 -1423
  187. package/dist/pluginInstaller.test.js.map +7 -1
  188. package/dist/pluginPackaging.test.js +417 -413
  189. package/dist/pluginPackaging.test.js.map +7 -1
  190. package/dist/pr.d.ts +114 -131
  191. package/dist/pr.js +1314 -1327
  192. package/dist/pr.js.map +7 -1
  193. package/dist/pr.test.js +967 -653
  194. package/dist/pr.test.js.map +7 -1
  195. package/dist/prAssociation.test.js +2419 -1788
  196. package/dist/prAssociation.test.js.map +7 -1
  197. package/dist/prDispatch.test.js +123 -89
  198. package/dist/prDispatch.test.js.map +7 -1
  199. package/dist/readView.d.ts +184 -0
  200. package/dist/readView.js +218 -0
  201. package/dist/readView.js.map +7 -0
  202. package/dist/readView.test.d.ts +1 -0
  203. package/dist/readView.test.js +146 -0
  204. package/dist/readView.test.js.map +7 -0
  205. package/dist/releaseReconciliation.test.js +267 -288
  206. package/dist/releaseReconciliation.test.js.map +7 -1
  207. package/dist/releaseWorkflow.test.js +2493 -422
  208. package/dist/releaseWorkflow.test.js.map +7 -1
  209. package/dist/review.d.ts +738 -2
  210. package/dist/review.js +601 -348
  211. package/dist/review.js.map +7 -1
  212. package/dist/review.test.js +1218 -812
  213. package/dist/review.test.js.map +7 -1
  214. package/dist/reviewSubmit.test.d.ts +1 -0
  215. package/dist/reviewSubmit.test.js +747 -0
  216. package/dist/reviewSubmit.test.js.map +7 -0
  217. package/dist/services/agentReadinessService.js +42 -37
  218. package/dist/services/agentReadinessService.js.map +7 -1
  219. package/dist/services/blockerGuardService.js +188 -188
  220. package/dist/services/blockerGuardService.js.map +7 -1
  221. package/dist/services/boardReconcileService.d.ts +125 -125
  222. package/dist/services/boardReconcileService.js +1295 -1421
  223. package/dist/services/boardReconcileService.js.map +7 -1
  224. package/dist/services/deliveryHealthService.js +197 -199
  225. package/dist/services/deliveryHealthService.js.map +7 -1
  226. package/dist/services/legacyIssueMigration.js +263 -277
  227. package/dist/services/legacyIssueMigration.js.map +7 -1
  228. package/dist/stagedChecks.test.js +396 -194
  229. package/dist/stagedChecks.test.js.map +7 -1
  230. package/dist/start.test.js +99 -95
  231. package/dist/start.test.js.map +7 -1
  232. package/dist/stdoutRegression.test.js +321 -358
  233. package/dist/stdoutRegression.test.js.map +7 -1
  234. package/dist/targetPolicyDiscovery.test.js +141 -143
  235. package/dist/targetPolicyDiscovery.test.js.map +7 -1
  236. package/dist/targetPolicyEntrypoints.test.js +308 -269
  237. package/dist/targetPolicyEntrypoints.test.js.map +7 -1
  238. package/dist/targetPolicyLocal.test.js +580 -1051
  239. package/dist/targetPolicyLocal.test.js.map +7 -1
  240. package/dist/targetPolicyRoutes.test.js +274 -281
  241. package/dist/targetPolicyRoutes.test.js.map +7 -1
  242. package/dist/targetRepositoryExecution.test.d.ts +1 -0
  243. package/dist/targetRepositoryExecution.test.js +451 -0
  244. package/dist/targetRepositoryExecution.test.js.map +7 -0
  245. package/dist/terminalMessages.js +41 -35
  246. package/dist/terminalMessages.js.map +7 -1
  247. package/dist/toolOutput.d.ts +2 -0
  248. package/dist/toolOutput.js +36 -0
  249. package/dist/toolOutput.js.map +7 -0
  250. package/dist/toolOutput.test.d.ts +1 -0
  251. package/dist/toolOutput.test.js +240 -0
  252. package/dist/toolOutput.test.js.map +7 -0
  253. package/dist/utils/atomicJson.d.ts +0 -2
  254. package/dist/utils/atomicJson.js +81 -77
  255. package/dist/utils/atomicJson.js.map +7 -1
  256. package/dist/utils/filesystem.d.ts +0 -8
  257. package/dist/utils/filesystem.js +5 -19
  258. package/dist/utils/filesystem.js.map +7 -1
  259. package/dist/utils/lockfile.js +68 -71
  260. package/dist/utils/lockfile.js.map +7 -1
  261. package/dist/verification.d.ts +1 -54
  262. package/dist/verification.js +976 -1941
  263. package/dist/verification.js.map +7 -1
  264. package/dist/verificationGate.test.js +127 -117
  265. package/dist/verificationGate.test.js.map +7 -1
  266. package/dist/version.js +45 -24
  267. package/dist/version.js.map +7 -1
  268. package/package.json +9 -8
  269. package/plugins/ai-delivery/.claude-plugin/plugin.json +2 -2
  270. package/plugins/ai-delivery/README.md +47 -156
  271. package/plugins/ai-delivery/plugin.json +1 -1
  272. package/plugins/ai-delivery/runtime/dist/THIRD-PARTY-NOTICES.md +238 -44
  273. package/plugins/ai-delivery/runtime/dist/cli.js +351 -115
  274. package/plugins/ai-delivery/runtime/package.json +1 -1
  275. package/plugins/ai-delivery/skills/intake-create/SKILL.md +14 -78
  276. package/plugins/ai-delivery/skills/pr-handoff/SKILL.md +35 -36
  277. package/plugins/ai-delivery/skills/worktree-lifecycle/SKILL.md +14 -15
  278. package/dist/investigationCompletion.test.js +0 -728
  279. package/dist/investigationCompletion.test.js.map +0 -1
  280. package/dist/services/deliveryAdmission.d.ts +0 -49
  281. package/dist/services/deliveryAdmission.js +0 -165
  282. package/dist/services/deliveryAdmission.js.map +0 -1
  283. package/dist/services/worktreeRegistry.d.ts +0 -434
  284. package/dist/services/worktreeRegistry.js +0 -1248
  285. package/dist/services/worktreeRegistry.js.map +0 -1
  286. package/dist/setup.d.ts +0 -60
  287. package/dist/setup.js +0 -585
  288. package/dist/setup.js.map +0 -1
  289. package/dist/setup.test.js +0 -3329
  290. package/dist/setup.test.js.map +0 -1
  291. package/dist/worktree.d.ts +0 -28
  292. package/dist/worktree.js +0 -188
  293. package/dist/worktree.js.map +0 -1
  294. package/dist/worktreeTransition.d.ts +0 -211
  295. package/dist/worktreeTransition.js +0 -1037
  296. package/dist/worktreeTransition.js.map +0 -1
  297. package/dist/worktreeTransition.test.js +0 -1191
  298. package/dist/worktreeTransition.test.js.map +0 -1
  299. /package/dist/{investigationCompletion.test.d.ts → build.test.d.ts} +0 -0
  300. /package/dist/{setup.test.d.ts → callerErrors.test.d.ts} +0 -0
  301. /package/dist/{worktreeTransition.test.d.ts → deliveryBoard.test.d.ts} +0 -0
@@ -1,3329 +0,0 @@
1
- import assert from 'node:assert/strict';
2
- import { execFileSync, spawn, spawnSync } from 'node:child_process';
3
- import { chmodSync, cpSync, existsSync, truncateSync, linkSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, symlinkSync, utimesSync, writeFileSync, } from 'node:fs';
4
- import { tmpdir } from 'node:os';
5
- import { dirname, join, relative, isAbsolute, sep } from 'node:path';
6
- import { afterEach, test, vi } from 'vitest';
7
- import { z } from 'zod';
8
- import { loadDeliveryConfig } from './config/deliveryConfig.js';
9
- import * as privateFiles from './delivery/common.js';
10
- import { digestBytes, digestValue } from './delivery/index.js';
11
- import { syntheticDiscoveryClients, syntheticOverrides, syntheticDiscoveryConfig } from './fixtures/discovery.js';
12
- import { assertDeliveryRuntimeAdmitted } from './services/deliveryAdmission.js';
13
- import * as atomicJson from './utils/atomicJson.js';
14
- afterEach(() => vi.unstubAllEnvs());
15
- // These two unit scenarios isolate the synthetic controller RSS contract from host-wide PS latency.
16
- // Every integration scenario retains native observation; this is never fallback for a failed native call.
17
- const controllerObservation = vi.hoisted(() => ({
18
- mode: 'native',
19
- }));
20
- vi.mock('node:child_process', async (original) => {
21
- const actual = await original();
22
- return {
23
- ...actual,
24
- spawn: (...args) => {
25
- if (controllerObservation.mode !== 'native')
26
- throw new Error('Controller unit fixture must not launch an owned child.');
27
- return actual.spawn(...args);
28
- },
29
- spawnSync: (...args) => {
30
- if (controllerObservation.mode === 'native')
31
- return actual.spawnSync(...args);
32
- // Native synchronous probes (including inert Git config) retain their actual result and failure.
33
- const psCommand = args[0] === 'ps' || args[0].endsWith('/ps');
34
- if (!psCommand)
35
- return actual.spawnSync(...args);
36
- if ((args[0] !== '/usr/bin/ps' && args[0] !== '/bin/ps') ||
37
- !Array.isArray(args[1]) ||
38
- args[1].join('|') !== '-A|-o|pid=,ppid=,pgid=,rss=,stat=,lstart=' ||
39
- args[2]?.encoding !== 'utf8' ||
40
- args[2]?.timeout !== 1_000 ||
41
- args[2]?.maxBuffer !== 4 * 1024 ** 2)
42
- throw new Error('Controller unit fixture received an unsupported observation signature.');
43
- if (controllerObservation.mode === 'unavailable-controller')
44
- return {
45
- status: null,
46
- error: Object.assign(new Error('Synthetic controller observation unavailable'), { code: 'ETIMEDOUT' }),
47
- signal: 'SIGTERM',
48
- stdout: '',
49
- stderr: '',
50
- };
51
- // This unit owns its own writer and gate; no real child is allowed in this one-controller universe.
52
- return {
53
- status: 0,
54
- signal: null,
55
- stdout: `${process.pid} 0 ${process.pid} 32 S controller unit birth\n`,
56
- stderr: '',
57
- };
58
- },
59
- };
60
- });
61
- function beginControllerObservation(mode) {
62
- assert.equal(controllerObservation.mode, 'native', 'a controller unit observation scope leaked');
63
- assert.equal(process.env.AI_DELIVERY_OUTPUT_OBSERVATION_GATE, undefined, 'controller unit observation requires its own fixture gate');
64
- controllerObservation.mode = mode;
65
- }
66
- const syncFailure = vi.hoisted(() => ({ directory: '' }));
67
- const sharedOutputRead = vi.hoisted(() => ({ path: '', unboundedReads: 0 }));
68
- const retirementFailure = vi.hoisted(() => ({ directory: '', error: undefined, hits: 0 }));
69
- vi.mock('node:fs', async (original) => {
70
- const actual = await original();
71
- return {
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
- },
86
- readFileSync: (...args) => {
87
- if (sharedOutputRead.path && String(args[0]) === sharedOutputRead.path) {
88
- sharedOutputRead.unboundedReads++;
89
- throw new Error('Unbounded shared command-output read attempted');
90
- }
91
- return actual.readFileSync(...args);
92
- },
93
- fsyncSync: (fd) => {
94
- if (syncFailure.directory &&
95
- actual.existsSync(syncFailure.directory) &&
96
- actual.fstatSync(fd).ino === actual.statSync(syncFailure.directory).ino)
97
- throw new Error('Synthetic directory durability unavailable');
98
- actual.fsyncSync(fd);
99
- },
100
- };
101
- });
102
- const actors = vi.hoisted(() => ({
103
- author: 'host-user',
104
- reviewer: 'reviewer[bot]',
105
- access: true,
106
- projectId: 'PROJECT-1',
107
- authorCalls: 0,
108
- reviewerCalls: 0,
109
- authorStarted: false,
110
- authorAborted: false,
111
- pauseAuthor: false,
112
- authorDelayMs: 4_000,
113
- }));
114
- // Only GitHub HTTP/authentication is synthetic. Resolver, process ownership and file operations are real.
115
- vi.mock('./github/client.js', async (original) => ({
116
- ...(await original()),
117
- createDeliveryGitHubClients: async (input) => ({
118
- ...syntheticDiscoveryClients(),
119
- graphql: async (query, variables) => {
120
- const result = await syntheticDiscoveryClients().graphql(query, variables);
121
- if (query.includes('ProjectDeliveryConfiguration'))
122
- result.organization.projectV2.id = actors.projectId;
123
- return result;
124
- },
125
- authSource: input.role === 'author' ? 'personal' : 'app',
126
- credentialSource: input.role === 'author' ? 'env:AUTHOR_TOKEN' : 'app:reviewer',
127
- role: input.role,
128
- authenticatedAuthor: async (signal) => {
129
- actors.authorCalls++;
130
- actors.authorStarted = true;
131
- if (actors.pauseAuthor) {
132
- await new Promise((resolve, reject) => {
133
- // A delayed HTTP response bounds this fixture's request, not the stage's elapsed duration.
134
- const response = setTimeout(resolve, actors.authorDelayMs);
135
- const abort = () => {
136
- clearTimeout(response);
137
- actors.authorAborted = true;
138
- reject(new Error('Synthetic author HTTP request aborted'));
139
- };
140
- const requestSignal = signal ?? input.signal;
141
- if (requestSignal?.aborted)
142
- abort();
143
- else
144
- requestSignal?.addEventListener('abort', abort, { once: true });
145
- });
146
- }
147
- return { actorLogin: actors.author, credentialIdentity: 'user:37' };
148
- },
149
- appActorLogin: async () => {
150
- actors.reviewerCalls++;
151
- return actors.reviewer;
152
- },
153
- rest: {
154
- repos: {
155
- get: async () => {
156
- if (!actors.access)
157
- throw new Error('Synthetic reviewer access denied');
158
- return { data: { full_name: 'example/widget' } };
159
- },
160
- },
161
- request: async () => {
162
- throw new Error('Synthetic rules visibility unavailable');
163
- },
164
- },
165
- }),
166
- }));
167
- async function producer() {
168
- const modulePath = new URL('./setup.js', import.meta.url).href;
169
- const result = (await import(modulePath).catch(() => ({})));
170
- assert.equal(typeof result.stageRuntime, 'function', 'supported producer stage API is missing');
171
- assert.equal(typeof result.admitRuntime, 'function', 'supported producer admission API is missing');
172
- return result;
173
- }
174
- function git(root, ...args) {
175
- return execFileSync('git', args, { cwd: root, encoding: 'utf8' }).trim();
176
- }
177
- async function fixture(native = false, parent = tmpdir()) {
178
- actors.author = 'host-user';
179
- actors.reviewer = 'reviewer[bot]';
180
- actors.access = true;
181
- actors.projectId = 'PROJECT-1';
182
- actors.authorCalls = 0;
183
- actors.reviewerCalls = 0;
184
- actors.authorStarted = false;
185
- actors.authorAborted = false;
186
- actors.pauseAuthor = false;
187
- actors.authorDelayMs = 4_000;
188
- const base = realpathSync(mkdtempSync(join(parent, 'ai-delivery-setup-')));
189
- const root = join(base, 'consumer');
190
- mkdirSync(root);
191
- git(root, 'init', '-q', '-b', 'main');
192
- git(root, 'config', 'user.name', 'Synthetic Delivery');
193
- git(root, 'config', 'user.email', 'delivery@example.test');
194
- git(root, 'remote', 'add', 'origin', 'https://github.com/example/widget.git');
195
- writeFileSync(join(root, 'ai-delivery.config.json'), JSON.stringify(syntheticOverrides(syntheticDiscoveryConfig)));
196
- const roles = {
197
- author: { authSource: 'personal', identity: 'host-author', credentialEnv: { token: 'AUTHOR_TOKEN' } },
198
- reviewer: {
199
- identity: 'synthetic-reviewer',
200
- credentialEnv: {
201
- appId: 'REVIEWER_APP_ID',
202
- installationId: 'REVIEWER_INSTALLATION_ID',
203
- privateKeyPath: 'REVIEWER_KEY_PATH',
204
- },
205
- },
206
- };
207
- writeFileSync(join(root, 'policy.mjs'), `export const deliverySettings=${JSON.stringify({ roles, commandPolicy: { checks: { format: 'REQUIRED', gitClean: 'REQUIRED', lint: 'REQUIRED', test: 'REQUIRED', typecheck: 'REQUIRED' }, timeoutsMs: { lint: 60000, test: 60000, typecheck: 60000 } } })};\n`);
208
- const { policy: _policy, repository: _repository, remote: _remote, schemaVersion: _schema, ...overrides } = syntheticOverrides(syntheticDiscoveryConfig);
209
- const userPath = join(base, 'user.json');
210
- writeFileSync(userPath, JSON.stringify({ schemaVersion: 'ai-delivery.user@1', roles, checkoutRoots: [], ...overrides }));
211
- vi.stubEnv('AI_DELIVERY_CONFIG', userPath);
212
- git(root, 'add', '.');
213
- git(root, 'commit', '-qm', 'Synthetic consumer');
214
- git(root, 'update-ref', 'refs/remotes/origin/main', 'HEAD');
215
- const packageRoot = join(base, 'archive', 'package');
216
- const files = {
217
- 'package.json': JSON.stringify({
218
- name: '@aviaratech/ai-delivery',
219
- version: '0.3.5',
220
- type: 'module',
221
- bin: { 'ai-delivery': './dist/cli.js' },
222
- }),
223
- 'dist/cli.js': "#!/usr/bin/env node\nconsole.log('0.3.5');\n",
224
- 'dist/agent.js': 'export const proof = 2;\n',
225
- 'plugins/ai-delivery/dist/mcp-launcher.js': '/* Synthetic launcher bytes */\n',
226
- 'plugins/ai-delivery/.claude-plugin/plugin.json': JSON.stringify({
227
- name: 'ai-delivery',
228
- packageVersion: '0.3.5',
229
- deliveryCapabilityVersion: 2,
230
- }),
231
- };
232
- if (native) {
233
- files['plugins/ai-delivery/runtime/package.json'] = files['package.json'];
234
- files['plugins/ai-delivery/runtime/dist/cli.js'] = files['dist/cli.js'];
235
- files['plugins/ai-delivery/README.md'] = 'Synthetic copied native plugin.\n';
236
- }
237
- for (const [relative, bytes] of Object.entries(files)) {
238
- const path = join(packageRoot, relative);
239
- mkdirSync(dirname(path), { recursive: true });
240
- writeFileSync(path, bytes);
241
- }
242
- const archivePath = join(base, 'reviewed archive; inert.tgz');
243
- execFileSync('tar', ['-czf', archivePath, '-C', dirname(packageRoot), 'package']);
244
- const nativePluginRoot = join(base, 'native-plugin');
245
- if (native)
246
- cpSync(join(packageRoot, 'plugins', 'ai-delivery'), nativePluginRoot, { recursive: true });
247
- const bin = join(base, 'bin');
248
- mkdirSync(bin);
249
- const counter = join(base, 'installs');
250
- const marker = join(base, 'installer-running');
251
- // Synthetic installer boundary: the real owned command copies fixture bytes; no process manager is mocked.
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`);
253
- chmodSync(join(bin, 'npm'), 0o755);
254
- const previousPath = process.env.PATH;
255
- process.env.PATH = `${bin}:${previousPath ?? ''}`;
256
- const input = {
257
- authority: 'runtime:stage',
258
- identity: 'host-author',
259
- repoRoot: root,
260
- archivePath,
261
- expectedArchiveSha256: digestBytes(readFileSync(archivePath)),
262
- packageVersion: '0.3.5',
263
- expectedSourceCommit: git(root, 'rev-parse', 'HEAD'),
264
- expectedConfigDigest: (await loadDeliveryConfig(root)).configDigest,
265
- runtimeDirectory: join(base, 'staged'),
266
- ...(native ? { nativePluginRoot } : {}),
267
- };
268
- return {
269
- base,
270
- root,
271
- input,
272
- counter,
273
- marker,
274
- cleanup: (retainFiles = false) => {
275
- process.env.PATH = previousPath;
276
- if (!retainFiles)
277
- rmSync(base, { recursive: true, force: true });
278
- },
279
- };
280
- }
281
- function admitInput(input, stageId, prior = null) {
282
- const { archivePath: _archive, expectedArchiveSha256: _digest, packageVersion: _version, nativePluginRoot: _native, ...rest } = input;
283
- return { ...rest, authority: 'runtime:admit', stageId, expectedPriorAdmissionSha256: prior };
284
- }
285
- test('native stage binds exact copied runtime paths and bytes, reuses and admits only that completed stage', async () => {
286
- const f = await fixture(true);
287
- try {
288
- const api = await producer();
289
- const staged = await api.stageRuntime(f.input);
290
- assert.equal(staged.admission.cliPath, join(f.input.nativePluginRoot, 'runtime', 'dist', 'cli.js'));
291
- assert.equal(staged.admission.mcpLauncherPath, join(f.input.nativePluginRoot, 'dist', 'mcp-launcher.js'));
292
- const record = readFileSync(join(f.input.runtimeDirectory, 'runtime-stage.json'));
293
- assert.equal((await api.stageRuntime(f.input)).reused, true);
294
- assert.deepEqual(readFileSync(join(f.input.runtimeDirectory, 'runtime-stage.json')), record);
295
- assert.equal(readFileSync(f.counter, 'utf8'), 'x');
296
- const other = join(f.base, 'other-native-plugin');
297
- cpSync(f.input.nativePluginRoot, other, { recursive: true });
298
- await assert.rejects(api.stageRuntime({ ...f.input, nativePluginRoot: other }), /incompatible setup intent/u);
299
- const admitted = await api.admitRuntime(admitInput(f.input, staged.stageId));
300
- assert.equal(admitted.admission.admissionId, staged.admission.admissionId);
301
- assert.equal((await api.admitRuntime(admitInput(f.input, staged.stageId))).reused, true);
302
- const readback = await assertDeliveryRuntimeAdmitted({
303
- repoRoot: f.root,
304
- runtimeEntryPath: staged.admission.cliPath,
305
- });
306
- assert.equal(readback.admissionId, staged.admission.admissionId);
307
- writeFileSync(join(f.input.nativePluginRoot, 'README.md'), 'Changed native plugin bytes.\n');
308
- await assert.rejects(api.stageRuntime(f.input), /native plugin.*reviewed/iu);
309
- await assert.rejects(api.admitRuntime(admitInput(f.input, staged.stageId)), /native plugin.*reviewed/iu);
310
- }
311
- finally {
312
- f.cleanup();
313
- }
314
- });
315
- test('native stage refuses unreviewed cache bytes without completing or mutating the cache', async () => {
316
- const f = await fixture(true);
317
- try {
318
- const api = await producer();
319
- const target = join(f.input.nativePluginRoot, 'runtime', 'dist', 'cli.js');
320
- const altered = 'console.log("unreviewed");\n';
321
- writeFileSync(target, altered);
322
- await assert.rejects(api.stageRuntime(f.input), /native plugin.*reviewed/iu);
323
- assert.equal(readFileSync(target, 'utf8'), altered);
324
- assert.equal(existsSync(join(f.root, '.git', 'ai-delivery', 'runtime-admission.json')), false);
325
- assert.equal(existsSync(f.input.runtimeDirectory), false);
326
- }
327
- finally {
328
- f.cleanup();
329
- }
330
- });
331
- test('native stage rejects aliased or overlapping cache paths before installing', async () => {
332
- const f = await fixture(true);
333
- try {
334
- const api = await producer();
335
- const alias = join(f.base, 'native-alias');
336
- symlinkSync(f.input.nativePluginRoot, alias);
337
- await assert.rejects(api.stageRuntime({ ...f.input, nativePluginRoot: alias }), /symbolic link/u);
338
- await assert.rejects(api.stageRuntime({ ...f.input, nativePluginRoot: f.base }), /overlap/iu);
339
- assert.equal(existsSync(f.counter), false);
340
- }
341
- finally {
342
- f.cleanup();
343
- }
344
- });
345
- test('runtime-stage controller memory is bounded before authenticated preflight', async () => {
346
- const api = await producer();
347
- const f = await fixture();
348
- try {
349
- await assert.rejects(api.stageRuntime({
350
- ...f.input,
351
- resourceBounds: { maxAggregateRssBytes: 1, minFreeDiskBytes: 1, maxNewOutputBytes: 128 * 1024 ** 2 },
352
- }), /RSS.*limit|RSS.*bound/u);
353
- assert.equal(actors.authorCalls, 0, 'over-budget controller must not start authenticated preflight');
354
- assert.equal(existsSync(f.counter), false);
355
- assert.equal(existsSync(f.input.runtimeDirectory), false);
356
- }
357
- finally {
358
- f.cleanup();
359
- }
360
- });
361
- test('runtime-stage controller growth during preflight fails before installing', async () => {
362
- const api = await producer();
363
- const f = await fixture();
364
- const memoryUsage = process.memoryUsage.bind(process);
365
- const memory = vi.spyOn(process, 'memoryUsage').mockImplementation(() => ({
366
- ...memoryUsage(),
367
- rss: actors.authorCalls === 0 ? 64 * 1024 ** 2 : 1024 ** 3,
368
- }));
369
- try {
370
- beginControllerObservation('healthy-controller');
371
- await assert.rejects(api.stageRuntime({
372
- ...f.input,
373
- resourceBounds: {
374
- maxAggregateRssBytes: 512 * 1024 ** 2,
375
- minFreeDiskBytes: 1,
376
- maxNewOutputBytes: 128 * 1024 ** 2,
377
- },
378
- }), /RSS.*limit|RSS.*bound/u);
379
- assert.ok(actors.authorCalls > 0);
380
- assert.equal(existsSync(f.counter), false, 'preflight failure must not release the npm command');
381
- assert.equal(existsSync(f.input.runtimeDirectory), false);
382
- }
383
- finally {
384
- try {
385
- memory.mockRestore();
386
- }
387
- finally {
388
- try {
389
- f.cleanup();
390
- }
391
- finally {
392
- controllerObservation.mode = 'native';
393
- }
394
- }
395
- }
396
- });
397
- test('runtime-stage unavailable initial controller observation refuses preflight and installer release', async () => {
398
- const api = await producer();
399
- const f = await fixture();
400
- try {
401
- beginControllerObservation('unavailable-controller');
402
- await assert.rejects(api.stageRuntime({
403
- ...f.input,
404
- resourceBounds: {
405
- maxAggregateRssBytes: 512 * 1024 ** 2,
406
- minFreeDiskBytes: 1,
407
- maxNewOutputBytes: 128 * 1024 ** 2,
408
- },
409
- }), (error) => {
410
- assert.ok(error instanceof Error);
411
- assert.equal(error.name, 'DeliveryError');
412
- const prefix = 'Owned process resource observation failed. ';
413
- assert.ok(error.message.startsWith(prefix));
414
- const metadata = JSON.parse(error.message.slice(prefix.length));
415
- assert.ok(typeof metadata.elapsedMs === 'number' && Number.isSafeInteger(metadata.elapsedMs));
416
- assert.ok(metadata.elapsedMs >= 0);
417
- assert.deepEqual(metadata, {
418
- status: null,
419
- errorCode: 'ETIMEDOUT',
420
- signal: 'SIGTERM',
421
- stdoutPresent: true,
422
- stdoutTerminated: false,
423
- elapsedMs: metadata.elapsedMs,
424
- stdoutBytes: 0,
425
- completeLines: 0,
426
- });
427
- return true;
428
- });
429
- assert.equal(actors.authorCalls, 0, 'unavailable observation must refuse before authenticated preflight');
430
- assert.equal(existsSync(f.counter), false, 'unavailable observation must not release the npm command');
431
- assert.equal(existsSync(f.input.runtimeDirectory), false);
432
- }
433
- finally {
434
- try {
435
- f.cleanup();
436
- }
437
- finally {
438
- controllerObservation.mode = 'native';
439
- }
440
- }
441
- });
442
- for (const interruption of ['resource breach', 'caller cancellation']) {
443
- test(`runtime-stage ${interruption} aborts a delayed preflight request and releases ownership before continuation`, async () => {
444
- const api = await producer();
445
- const f = await fixture();
446
- const cancellation = new AbortController();
447
- const actualMemory = process.memoryUsage.bind(process);
448
- const memory = vi.spyOn(process, 'memoryUsage').mockImplementation(() => ({
449
- ...actualMemory(),
450
- rss: interruption === 'resource breach' && actors.authorStarted ? 1024 ** 3 : 64 * 1024 ** 2,
451
- }));
452
- actors.pauseAuthor = true;
453
- try {
454
- const rejected = assert.rejects(api.stageRuntime({
455
- ...f.input,
456
- signal: cancellation.signal,
457
- resourceBounds: {
458
- maxAggregateRssBytes: 512 * 1024 ** 2,
459
- minFreeDiskBytes: 1,
460
- maxNewOutputBytes: 128 * 1024 ** 2,
461
- maxCapturedOutputBytes: 1024 ** 2,
462
- },
463
- }), interruption === 'resource breach' ? /aggregate RSS .* exceeded limit/u : /cancelled/u);
464
- if (interruption === 'caller cancellation') {
465
- while (!actors.authorStarted)
466
- await new Promise((resolve) => setTimeout(resolve, 10));
467
- cancellation.abort();
468
- }
469
- await rejected;
470
- assert.equal(actors.authorAborted, true, 'in-flight author request must receive scope cancellation');
471
- assert.equal(actors.reviewerCalls, 0, 'reviewer preflight must not continue after detection');
472
- assert.equal(existsSync(f.counter), false);
473
- assert.equal(existsSync(f.input.runtimeDirectory), false);
474
- assert.equal(digestBytes(readFileSync(f.input.archivePath)), f.input.expectedArchiveSha256);
475
- memory.mockRestore();
476
- actors.pauseAuthor = false;
477
- const retry = await api.stageRuntime(f.input);
478
- assert.equal(retry.reused, false, 'cancelled preflight must release writer ownership for a clean retry');
479
- assert.equal(readFileSync(f.counter, 'utf8'), 'x');
480
- assert.equal(existsSync(join(f.root, '.git/ai-delivery/runtime-admission.json')), false);
481
- }
482
- finally {
483
- memory.mockRestore();
484
- f.cleanup();
485
- }
486
- });
487
- }
488
- test('runtime-stage failure logs honor the caller retained-output cap outside the stage', async () => {
489
- const api = await producer();
490
- const f = await fixture();
491
- const logLimit = 1024 ** 2;
492
- try {
493
- writeFileSync(join(f.base, 'log-bytes'), String(2 * logLimit));
494
- writeFileSync(join(f.base, 'fail'), 'go');
495
- await assert.rejects(api.stageRuntime({
496
- ...f.input,
497
- resourceBounds: {
498
- maxAggregateRssBytes: 512 * 1024 ** 2,
499
- minFreeDiskBytes: 1,
500
- maxNewOutputBytes: 128 * 1024 ** 2,
501
- maxCapturedOutputBytes: logLimit,
502
- },
503
- }), /captured output exceeded/u);
504
- const outputDirectory = join(f.root, '.git/ai-delivery/verification@1/command-output');
505
- const logs = readdirSync(outputDirectory);
506
- assert.equal(logs.length, 1);
507
- assert.ok(lstatSync(join(outputDirectory, logs[0])).size <= logLimit);
508
- assert.equal(existsSync(f.input.runtimeDirectory), false);
509
- assert.equal(digestBytes(readFileSync(f.input.archivePath)), f.input.expectedArchiveSha256);
510
- }
511
- finally {
512
- f.cleanup();
513
- }
514
- });
515
- test('runtime-stage retries share the retained-output allowance and preserve earlier failure evidence', async () => {
516
- const api = await producer();
517
- const f = await fixture();
518
- const logLimit = 1024 ** 2;
519
- const input = {
520
- ...f.input,
521
- resourceBounds: {
522
- maxAggregateRssBytes: 512 * 1024 ** 2,
523
- minFreeDiskBytes: 1,
524
- maxNewOutputBytes: 128 * 1024 ** 2,
525
- maxCapturedOutputBytes: logLimit,
526
- },
527
- };
528
- const outputDirectory = join(f.root, '.git/ai-delivery/verification@1/command-output');
529
- try {
530
- writeFileSync(join(f.base, 'fail'), 'go');
531
- writeFileSync(join(f.base, 'log-bytes'), String(600 * 1024));
532
- await assert.rejects(api.stageRuntime(input), /failed/u);
533
- const prior = readdirSync(outputDirectory).map((name) => ({
534
- name,
535
- bytes: readFileSync(join(outputDirectory, name)),
536
- }));
537
- writeFileSync(join(f.base, 'log-bytes'), String(700 * 1024));
538
- await assert.rejects(api.stageRuntime(input), /failed|captured output exceeded/u);
539
- const total = readdirSync(outputDirectory).reduce((bytes, name) => bytes + lstatSync(join(outputDirectory, name)).size, 0);
540
- assert.ok(total <= logLimit, `Retained retry logs ${total} exceed total allowance ${logLimit}.`);
541
- for (const evidence of prior)
542
- assert.deepEqual(readFileSync(join(outputDirectory, evidence.name)), evidence.bytes);
543
- assert.equal(readFileSync(f.counter, 'utf8'), 'xx');
544
- await assert.rejects(api.stageRuntime(input), /retained.*exhausted/u);
545
- assert.equal(readFileSync(f.counter, 'utf8'), 'xx', 'exhausted allowance must refuse another installer invocation');
546
- assert.equal(existsSync(f.input.runtimeDirectory), false);
547
- assert.equal(digestBytes(readFileSync(f.input.archivePath)), f.input.expectedArchiveSha256);
548
- }
549
- finally {
550
- f.cleanup();
551
- }
552
- });
553
- for (const existing of ['oversized', 'corrupt', 'valid', 'empty']) {
554
- test(`runtime-stage first publication bounds ${existing} shared output absent from its ledger`, async () => {
555
- const api = await producer();
556
- const f = await fixture();
557
- const bytes = Buffer.alloc(existing === 'empty' ? 0 : 100 * 1024, 65);
558
- const digest = digestBytes(bytes);
559
- const directory = join(f.root, '.git/ai-delivery/verification@1/command-output');
560
- const evidence = join(directory, `${digest.slice(7)}.bin`);
561
- const ledgerDirectory = join(f.root, '.git/ai-delivery/verification@1/runtime-output', digestValue(f.root).slice(7));
562
- try {
563
- mkdirSync(directory, { recursive: true, mode: 0o700 });
564
- writeFileSync(evidence, existing === 'corrupt' ? Buffer.alloc(bytes.length, 66) : bytes, { mode: 0o600 });
565
- if (existing === 'oversized')
566
- truncateSync(evidence, 9 * 1024 ** 2);
567
- const originalDigest = digestBytes(readFileSync(evidence));
568
- const originalIdentity = lstatSync(evidence);
569
- assert.equal(existsSync(ledgerDirectory), false, 'shared evidence must precede this stage ledger');
570
- writeFileSync(join(f.base, 'fail'), 'go');
571
- writeFileSync(join(f.base, 'log-bytes'), String(bytes.length));
572
- sharedOutputRead.path = evidence;
573
- sharedOutputRead.unboundedReads = 0;
574
- await assert.rejects(api.stageRuntime(f.input), /exit 7/u);
575
- assert.equal(sharedOutputRead.unboundedReads, 0, 'publication must bound existing evidence before reading it');
576
- assert.equal(readFileSync(f.counter, 'utf8'), 'x');
577
- const ledgerPath = join(ledgerDirectory, readdirSync(ledgerDirectory)[0]);
578
- const ledger = JSON.parse(readFileSync(ledgerPath, 'utf8'));
579
- const refused = existing === 'oversized' || existing === 'corrupt';
580
- assert.deepEqual(ledger.outputs, [{ digest, bytes: bytes.length, status: refused ? 'reserved' : 'complete' }]);
581
- const retainedLedger = readFileSync(ledgerPath);
582
- await assert.rejects(api.stageRuntime(f.input), refused ? /corrupt|size.*bound/u : /exit 7/u);
583
- assert.equal(readFileSync(f.counter, 'utf8'), refused ? 'x' : 'xx');
584
- assert.equal(sharedOutputRead.unboundedReads, 0);
585
- assert.deepEqual(readFileSync(ledgerPath), retainedLedger, 'retry must preserve the existing reservation or completed charge');
586
- sharedOutputRead.path = '';
587
- assert.equal(digestBytes(readFileSync(evidence)), originalDigest, 'existing shared evidence must remain immutable');
588
- const after = lstatSync(evidence);
589
- assert.equal(after.ino, originalIdentity.ino);
590
- assert.equal(after.size, originalIdentity.size);
591
- assert.equal(existsSync(f.input.runtimeDirectory), false);
592
- }
593
- finally {
594
- sharedOutputRead.path = '';
595
- sharedOutputRead.unboundedReads = 0;
596
- f.cleanup();
597
- }
598
- });
599
- }
600
- for (const fault of [
601
- 'corrupt ledger',
602
- 'incompatible controller',
603
- 'missing evidence',
604
- 'corrupt evidence',
605
- 'oversized evidence',
606
- ]) {
607
- test(`runtime-stage retained-output ${fault} refuses another installer without resetting its allowance`, async () => {
608
- const api = await producer();
609
- const f = await fixture();
610
- try {
611
- writeFileSync(join(f.base, 'fail'), 'go');
612
- writeFileSync(join(f.base, 'log-bytes'), String(100 * 1024));
613
- await assert.rejects(api.stageRuntime(f.input), /exit 7/u);
614
- const directory = join(f.root, '.git/ai-delivery/verification@1/runtime-output', digestValue(f.root).slice(7));
615
- const path = join(directory, readdirSync(directory)[0]);
616
- const ledger = JSON.parse(readFileSync(path, 'utf8'));
617
- const evidence = join(f.root, '.git/ai-delivery/verification@1/command-output', `${ledger.outputs[0].digest.slice(7)}.bin`);
618
- if (fault === 'corrupt ledger') {
619
- ledger.contentDigest = `sha256:${'0'.repeat(64)}`;
620
- writeFileSync(path, JSON.stringify(ledger));
621
- }
622
- else if (fault === 'incompatible controller') {
623
- ledger.producerDigest = `sha256:${'0'.repeat(64)}`;
624
- const { contentDigest: _digest, ...content } = ledger;
625
- ledger.contentDigest = digestValue(content);
626
- writeFileSync(path, JSON.stringify(ledger));
627
- }
628
- else if (fault === 'missing evidence')
629
- rmSync(evidence);
630
- else if (fault === 'oversized evidence')
631
- truncateSync(evidence, 9 * 1024 ** 2);
632
- else
633
- writeFileSync(evidence, 'changed immutable output');
634
- const retained = readFileSync(path);
635
- await assert.rejects(api.stageRuntime(f.input), /corrupt|incompatible|ENOENT|size.*bound/u);
636
- assert.equal(readFileSync(f.counter, 'utf8'), 'x');
637
- assert.deepEqual(readFileSync(path), retained, 'failed integrity check must preserve the charged ledger');
638
- assert.equal(readdirSync(directory).length, 1);
639
- assert.equal(existsSync(f.input.runtimeDirectory), false);
640
- }
641
- finally {
642
- f.cleanup();
643
- }
644
- });
645
- }
646
- test('runtime-stage explicitly isolates npm cache, logs, configuration and temporary destinations', async () => {
647
- const api = await producer();
648
- const f = await fixture();
649
- try {
650
- await api.stageRuntime(f.input);
651
- const settings = JSON.parse(readFileSync(join(f.base, 'installer-settings'), 'utf8'));
652
- const stage = f.input.runtimeDirectory;
653
- for (const option of ['--cache', '--logs-dir', '--userconfig', '--globalconfig']) {
654
- assert.ok(settings.args.includes(option), `missing explicit npm ${option}`);
655
- const value = settings.args[settings.args.indexOf(option) + 1];
656
- assert.ok(value.startsWith(`${stage}/`), `npm ${option} must stay inside the owned stage`);
657
- assert.ok(existsSync(value));
658
- }
659
- assert.equal(settings.cwd, stage);
660
- for (const key of ['TMPDIR', 'TMP', 'TEMP']) {
661
- assert.ok(settings[key].startsWith(`${stage}/`), `${key} must stay inside the owned stage`);
662
- assert.ok(existsSync(settings[key]));
663
- }
664
- assert.equal((await api.stageRuntime(f.input)).reused, true);
665
- assert.equal(readFileSync(f.counter, 'utf8'), 'x');
666
- }
667
- finally {
668
- f.cleanup();
669
- }
670
- });
671
- test('runtime-stage cancellation shares prior failure charges and identical evidence is reused', async () => {
672
- const api = await producer();
673
- const f = await fixture();
674
- const cancellation = new AbortController();
675
- const input = {
676
- ...f.input,
677
- resourceBounds: {
678
- maxAggregateRssBytes: 512 * 1024 ** 2,
679
- minFreeDiskBytes: 1,
680
- maxNewOutputBytes: 128 * 1024 ** 2,
681
- maxCapturedOutputBytes: 1024 ** 2,
682
- },
683
- };
684
- const directory = join(f.root, '.git/ai-delivery/verification@1/command-output');
685
- const write = process.stderr.write.bind(process.stderr);
686
- let sawCaptured = false;
687
- const observation = vi.spyOn(process.stderr, 'write').mockImplementation((chunk, ...args) => {
688
- const text = String(chunk);
689
- if (text.startsWith('ai-delivery.verify ')) {
690
- const value = JSON.parse(text.slice('ai-delivery.verify '.length));
691
- if (value.capturedOutputBytes === 200 * 1024) {
692
- sawCaptured = true;
693
- cancellation.abort();
694
- }
695
- }
696
- return write(chunk, ...args);
697
- });
698
- try {
699
- writeFileSync(join(f.base, 'fail'), 'go');
700
- writeFileSync(join(f.base, 'log-bytes'), String(100 * 1024));
701
- await assert.rejects(api.stageRuntime(input), /exit 7/u);
702
- await assert.rejects(api.stageRuntime(input), /exit 7/u);
703
- assert.equal(readdirSync(directory).length, 1, 'identical complete command evidence must be reused');
704
- const prior = readFileSync(join(directory, readdirSync(directory)[0]));
705
- rmSync(join(f.base, 'fail'));
706
- writeFileSync(join(f.base, 'wait'), 'go');
707
- writeFileSync(join(f.base, 'log-bytes'), String(200 * 1024));
708
- await assert.rejects(api.stageRuntime({ ...input, signal: cancellation.signal }), /cancelled/u);
709
- assert.equal(sawCaptured, true, 'cancel only after the full owned output is captured');
710
- assert.ok(readdirSync(directory).some((name) => readFileSync(join(directory, name)).equals(prior)));
711
- const ledgerRoot = join(f.root, '.git/ai-delivery/verification@1/runtime-output', digestValue(f.root).slice(7));
712
- const ledger = JSON.parse(readFileSync(join(ledgerRoot, readdirSync(ledgerRoot)[0]), 'utf8'));
713
- assert.equal(ledger.outputs.reduce((total, output) => total + output.bytes, 0), 300 * 1024);
714
- assert.equal(readFileSync(f.counter, 'utf8'), 'xxx');
715
- assert.equal(existsSync(f.input.runtimeDirectory), false);
716
- }
717
- finally {
718
- cancellation.abort();
719
- observation.mockRestore();
720
- f.cleanup();
721
- }
722
- });
723
- test('runtime-stage post-install preflight growth cannot publish completion', async () => {
724
- const api = await producer();
725
- const f = await fixture();
726
- const memoryUsage = process.memoryUsage.bind(process);
727
- const memory = vi.spyOn(process, 'memoryUsage').mockImplementation(() => ({
728
- ...memoryUsage(),
729
- rss: actors.authorCalls < 2 ? 64 * 1024 ** 2 : 1024 ** 3,
730
- }));
731
- try {
732
- await assert.rejects(api.stageRuntime({
733
- ...f.input,
734
- resourceBounds: {
735
- maxAggregateRssBytes: 512 * 1024 ** 2,
736
- minFreeDiskBytes: 1,
737
- maxNewOutputBytes: 128 * 1024 ** 2,
738
- },
739
- }), /RSS.*limit|RSS.*bound/u);
740
- assert.equal(readFileSync(f.counter, 'utf8'), 'x', 'installation must finish before the failing final preflight');
741
- assert.equal(existsSync(f.input.runtimeDirectory), false);
742
- assert.equal(existsSync(join(f.root, '.git/ai-delivery/runtime-admission.json')), false);
743
- }
744
- finally {
745
- memory.mockRestore();
746
- f.cleanup();
747
- }
748
- });
749
- test('runtime-stage bounds actual controller and npm memory and preserves an unrelated live peer', async () => {
750
- const api = await producer();
751
- const f = await fixture();
752
- const peer = spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)'], { stdio: 'ignore' });
753
- const closed = new Promise((resolve) => peer.once('close', () => resolve()));
754
- try {
755
- await new Promise((resolve, reject) => {
756
- peer.once('spawn', () => resolve());
757
- peer.once('error', reject);
758
- });
759
- writeFileSync(join(f.base, 'memory-bytes'), String(512 * 1024 ** 2));
760
- await assert.rejects(api.stageRuntime({
761
- ...f.input,
762
- resourceBounds: {
763
- maxAggregateRssBytes: 512 * 1024 ** 2,
764
- minFreeDiskBytes: 1,
765
- maxNewOutputBytes: 128 * 1024 ** 2,
766
- maxCapturedOutputBytes: 1024 ** 2,
767
- },
768
- }), /aggregate RSS .* exceeded limit/u);
769
- const ownedPid = Number(readFileSync(f.marker, 'utf8'));
770
- assert.throws(() => process.kill(ownedPid, 0), { code: 'ESRCH' });
771
- assert.equal(peer.exitCode, null);
772
- process.kill(peer.pid, 0);
773
- assert.equal(existsSync(f.input.runtimeDirectory), false);
774
- assert.equal(existsSync(join(f.root, '.git/ai-delivery/runtime-admission.json')), false);
775
- assert.equal(digestBytes(readFileSync(f.input.archivePath)), f.input.expectedArchiveSha256);
776
- }
777
- finally {
778
- peer.kill('SIGKILL');
779
- await closed;
780
- f.cleanup();
781
- }
782
- });
783
- test('runtime-stage changed resource intent preserves compatible completed bytes without reinstalling', async () => {
784
- const api = await producer();
785
- const f = await fixture();
786
- try {
787
- const stage = await api.stageRuntime(f.input);
788
- const path = join(f.input.runtimeDirectory, 'runtime-stage.json');
789
- const completion = readFileSync(path);
790
- await assert.rejects(api.stageRuntime({
791
- ...f.input,
792
- resourceBounds: {
793
- maxAggregateRssBytes: 512 * 1024 ** 2,
794
- minFreeDiskBytes: 1,
795
- maxNewOutputBytes: 128 * 1024 ** 2,
796
- maxCapturedOutputBytes: 512 * 1024,
797
- },
798
- }), /incompatible setup intent/u);
799
- assert.deepEqual(readFileSync(path), completion);
800
- assert.equal(readFileSync(f.counter, 'utf8'), 'x');
801
- assert.equal((await api.stageRuntime(f.input)).stageId, stage.stageId);
802
- }
803
- finally {
804
- f.cleanup();
805
- }
806
- });
807
- for (const mode of ['success', 'failure', 'cancel']) {
808
- test(`real npm ${mode} disables file logs and preserves unrelated host destinations`, async () => {
809
- const api = await producer();
810
- const realPath = process.env.PATH;
811
- const f = await fixture();
812
- const cancellation = new AbortController();
813
- let operation;
814
- const previous = {
815
- cache: process.env.npm_config_cache,
816
- logs: process.env.npm_config_logs_dir,
817
- userconfig: process.env.npm_config_userconfig,
818
- };
819
- try {
820
- process.env.PATH = realPath;
821
- const outside = join(f.base, 'unrelated-host');
822
- mkdirSync(outside);
823
- const cache = join(outside, 'cache');
824
- const logs = join(outside, 'logs');
825
- for (const path of [cache, logs]) {
826
- mkdirSync(path);
827
- writeFileSync(join(path, 'keep'), 'unrelated');
828
- }
829
- const userconfig = join(outside, 'user.npmrc');
830
- const config = `cache=${cache}\nlogs-dir=${logs}\n`;
831
- writeFileSync(userconfig, config);
832
- const nativeBin = join(f.base, 'native-bin');
833
- mkdirSync(nativeBin);
834
- const probe = join(f.base, 'native-npm-observation.json');
835
- const npmRoot = join(dirname(process.execPath), '../lib/node_modules/npm');
836
- writeFileSync(join(nativeBin, 'npm'), `#!${process.execPath}\nconst fs=require('node:fs'),os=require('node:os'),path=require('node:path');\nconst observation={args:process.argv.slice(2),cwd:process.cwd(),tmpdir:os.tmpdir(),npmVersion:require(${JSON.stringify(join(npmRoot, 'package.json'))}).version};\nconst LogFile=require(${JSON.stringify(join(npmRoot, 'lib/utils/log-file.js'))}),load=LogFile.prototype.load;\nconst observe=()=>{const directory=path.join(process.cwd(),'.npm/logs');observation.fileLogs=fs.existsSync(directory)?fs.readdirSync(directory):[];observation.fileLogBytes=observation.fileLogs.reduce((sum,name)=>sum+fs.statSync(path.join(directory,name)).size,0);fs.writeFileSync(${JSON.stringify(probe)},JSON.stringify(observation),{mode:0o600});};\nLogFile.prototype.load=function(options){const result=load.call(this,options);observation.logsMax=options.logsMax;observe();${mode === 'cancel' ? 'setInterval(observe,20);' : ''}return result;};\nprocess.on('exit',observe);\n${mode === 'failure' ? 'process.argv[2]="synthetic-unknown-command";' : ''}\nrequire(${JSON.stringify(join(npmRoot, 'bin/npm-cli.js'))});\n`);
837
- chmodSync(join(nativeBin, 'npm'), 0o755);
838
- process.env.PATH = `${nativeBin}:${realPath ?? ''}`;
839
- process.env.npm_config_cache = cache;
840
- process.env.npm_config_logs_dir = logs;
841
- process.env.npm_config_userconfig = userconfig;
842
- operation = api.stageRuntime({
843
- ...f.input,
844
- signal: cancellation.signal,
845
- resourceBounds: {
846
- maxAggregateRssBytes: 512 * 1024 ** 2,
847
- minFreeDiskBytes: 1,
848
- maxNewOutputBytes: 128 * 1024 ** 2,
849
- maxCapturedOutputBytes: 1024 ** 2,
850
- },
851
- });
852
- void operation.catch(() => undefined);
853
- if (mode === 'cancel') {
854
- for (let i = 0; i < 1000 && !existsSync(probe); i++)
855
- await new Promise((resolve) => setTimeout(resolve, 20));
856
- assert.equal(existsSync(probe), true, 'actual npm log configuration was not observed');
857
- cancellation.abort();
858
- await assert.rejects(operation, /cancelled/u);
859
- }
860
- else if (mode === 'failure')
861
- await assert.rejects(operation, /exit 1/u);
862
- else {
863
- const stage = await operation;
864
- assert.equal(existsSync(f.counter), false, 'synthetic npm must not execute');
865
- assert.equal(execFileSync(process.execPath, [stage.admission.cliPath, '--version'], { encoding: 'utf8' }).trim(), '0.3.5');
866
- assert.ok(readdirSync(join(f.input.runtimeDirectory, '.npm/cache')).length > 0);
867
- assert.deepEqual(readdirSync(join(f.input.runtimeDirectory, '.npm/logs')), []);
868
- }
869
- const native = JSON.parse(readFileSync(probe, 'utf8'));
870
- assert.equal(native.npmVersion, '11.19.0');
871
- assert.equal(native.cwd, f.input.runtimeDirectory);
872
- assert.equal(native.tmpdir, join(f.input.runtimeDirectory, '.npm/tmp'));
873
- assert.equal(native.logsMax, 0);
874
- assert.equal(native.fileLogBytes, 0);
875
- assert.deepEqual(native.fileLogs, []);
876
- if (mode !== 'success')
877
- assert.equal(existsSync(f.input.runtimeDirectory), false);
878
- for (const option of ['--cache', '--logs-dir', '--userconfig', '--globalconfig']) {
879
- assert.ok(native.args.includes(option));
880
- assert.ok(native.args[native.args.indexOf(option) + 1].startsWith(`${f.input.runtimeDirectory}/`));
881
- }
882
- assert.deepEqual(readdirSync(cache), ['keep']);
883
- assert.deepEqual(readdirSync(logs), ['keep']);
884
- assert.equal(readFileSync(userconfig, 'utf8'), config);
885
- assert.equal(existsSync(join(f.root, '.git/ai-delivery/runtime-admission.json')), false);
886
- console.log('REAL_NPM_ISOLATION_RECEIPT', JSON.stringify({
887
- mode,
888
- npmFileLogBytes: native.fileLogBytes,
889
- npmFileLogsDisabled: true,
890
- temporaryAndConfigInsideStage: true,
891
- unrelatedHostPreserved: true,
892
- controllerInclusiveMemoryBytes: 512 * 1024 ** 2,
893
- retainedLogCapBytes: 1024 ** 2,
894
- hostActivated: false,
895
- sharedAdmissionWritten: false,
896
- }));
897
- }
898
- finally {
899
- cancellation.abort();
900
- await operation?.catch(() => undefined);
901
- for (const [name, value] of [
902
- ['npm_config_cache', previous.cache],
903
- ['npm_config_logs_dir', previous.logs],
904
- ['npm_config_userconfig', previous.userconfig],
905
- ]) {
906
- if (value === undefined)
907
- delete process.env[name];
908
- else
909
- process.env[name] = value;
910
- }
911
- f.cleanup();
912
- }
913
- });
914
- }
915
- test('real npm keeps the reviewed tarball closure after hidden-lock invalidation and completed reuse', async () => {
916
- const api = await producer();
917
- const realPath = process.env.PATH;
918
- const f = await fixture();
919
- try {
920
- const npmRoot = join(dirname(process.execPath), '../lib/node_modules/npm');
921
- const npmCli = join(npmRoot, 'bin/npm-cli.js');
922
- assert.equal(JSON.parse(readFileSync(join(npmRoot, 'package.json'), 'utf8')).version, '11.19.0');
923
- const bin = join(f.base, 'real-npm-bin');
924
- mkdirSync(bin);
925
- 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`);
926
- chmodSync(join(bin, 'npm'), 0o755);
927
- process.env.PATH = `${bin}:${realPath ?? ''}`;
928
- const manifestPath = join(f.base, 'archive/package/package.json');
929
- const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'));
930
- manifest.scripts = { preinstall: 'node -e "process.exit(91)"', install: 'node -e "process.exit(92)"' };
931
- writeFileSync(manifestPath, JSON.stringify(manifest));
932
- execFileSync('tar', ['-czf', f.input.archivePath, '-C', join(f.base, 'archive'), 'package']);
933
- f.input.expectedArchiveSha256 = digestBytes(readFileSync(f.input.archivePath));
934
- const installed = join(f.input.runtimeDirectory, 'node_modules');
935
- const hidden = join(installed, '.package-lock.json');
936
- const stage = await api.stageRuntime(f.input);
937
- const completeBytes = readFileSync(join(f.input.runtimeDirectory, 'runtime-stage.json'));
938
- const metadataPaths = ['package.json', 'package-lock.json'].map((name) => join(f.input.runtimeDirectory, name));
939
- const metadataBytes = metadataPaths.map((path) => readFileSync(path));
940
- 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 });
941
- const closure = () => {
942
- const result = inspectClosure();
943
- assert.equal(result.error, undefined);
944
- assert.equal(result.status, 0, result.stderr + result.stdout);
945
- const graph = JSON.parse(result.stdout);
946
- assert.equal(graph.problems, undefined);
947
- const target = graph.dependencies['@aviaratech/ai-delivery'];
948
- assert.equal(target.version, '0.3.5');
949
- assert.equal(target.invalid, undefined);
950
- assert.equal(target.missing, undefined);
951
- assert.equal(target.resolved, `file:${join(f.input.runtimeDirectory, 'reviewed-archive.tgz')}`);
952
- };
953
- closure();
954
- const lockTime = lstatSync(hidden).mtime;
955
- utimesSync(installed, new Date(lockTime.getTime() + 2000), new Date(lockTime.getTime() + 2000));
956
- assert.ok(lstatSync(installed).mtimeMs > lstatSync(hidden).mtimeMs);
957
- closure();
958
- assert.deepEqual(await api.stageRuntime(f.input), { ...stage, reused: true });
959
- assert.deepEqual(readFileSync(join(f.input.runtimeDirectory, 'runtime-stage.json')), completeBytes);
960
- assert.deepEqual(metadataPaths.map((path) => readFileSync(path)), metadataBytes);
961
- rmSync(hidden);
962
- closure();
963
- assert.deepEqual(await api.stageRuntime(f.input), { ...stage, reused: true });
964
- await api.admitRuntime(admitInput(f.input, stage.stageId));
965
- assert.equal(readFileSync(f.counter, 'utf8'), 'x', 'completed reuse must never reinstall');
966
- assert.deepEqual(readFileSync(join(f.input.runtimeDirectory, 'runtime-stage.json')), completeBytes);
967
- assert.deepEqual(metadataPaths.map((path) => readFileSync(path)), metadataBytes);
968
- const admissionPath = join(f.root, '.git/ai-delivery/runtime-admission.json');
969
- const admissionBytes = readFileSync(admissionPath);
970
- for (const { field, edges, problem } of [
971
- { field: 'optionalDependencies', edges: { '@aviaratech/ai-delivery': 'file:other.tgz' }, problem: /invalid:/u },
972
- { field: 'peerDependencies', edges: { 'missing-runtime-stage-peer': '1.0.0' }, problem: /missing:/u },
973
- ]) {
974
- const changed = JSON.parse(metadataBytes[0].toString('utf8'));
975
- changed[field] = edges;
976
- writeFileSync(metadataPaths[0], JSON.stringify(changed));
977
- const damaged = readFileSync(metadataPaths[0]);
978
- const native = inspectClosure();
979
- assert.equal(native.error, undefined);
980
- assert.equal(native.status, 1, native.stderr + native.stdout);
981
- const graph = JSON.parse(native.stdout);
982
- assert.equal(graph.error?.code, 'ELSPROBLEMS');
983
- assert.ok(graph.problems?.some((entry) => problem.test(entry)));
984
- await assert.rejects(api.stageRuntime(f.input), /dependency metadata/iu);
985
- await assert.rejects(api.admitRuntime(admitInput(f.input, stage.stageId)), /dependency metadata/iu);
986
- assert.deepEqual(readFileSync(metadataPaths[0]), damaged);
987
- assert.deepEqual(readFileSync(metadataPaths[1]), metadataBytes[1]);
988
- assert.deepEqual(readFileSync(join(f.input.runtimeDirectory, 'runtime-stage.json')), completeBytes);
989
- assert.deepEqual(readFileSync(admissionPath), admissionBytes);
990
- assert.equal(readFileSync(f.counter, 'utf8'), 'x');
991
- writeFileSync(metadataPaths[0], metadataBytes[0]);
992
- }
993
- }
994
- finally {
995
- f.cleanup();
996
- process.env.PATH = realPath;
997
- }
998
- });
999
- test('completed stages refuse missing, corrupt or incompatible dependency metadata without reinstalling or rewriting', async () => {
1000
- const api = await producer();
1001
- const f = await fixture();
1002
- try {
1003
- const staged = await api.stageRuntime(f.input);
1004
- const record = join(f.input.runtimeDirectory, 'runtime-stage.json');
1005
- const complete = readFileSync(record);
1006
- const paths = ['package.json', 'package-lock.json'].map((name) => join(f.input.runtimeDirectory, name));
1007
- const retained = paths.map((path) => (existsSync(path) ? readFileSync(path) : undefined));
1008
- for (const [index, path] of paths.entries()) {
1009
- for (const fault of [
1010
- 'missing',
1011
- 'corrupt',
1012
- 'incompatible',
1013
- 'symlink',
1014
- 'hardlink',
1015
- 'fifo',
1016
- ...(index === 1 ? ['version', 'resolved', 'integrity'] : []),
1017
- ]) {
1018
- const sentinel = join(f.base, `unrelated-metadata-${index}-${fault}`);
1019
- if (fault === 'missing')
1020
- rmSync(path, { force: true });
1021
- else if (fault === 'symlink' || fault === 'hardlink') {
1022
- writeFileSync(sentinel, retained[index]);
1023
- rmSync(path);
1024
- if (fault === 'symlink')
1025
- symlinkSync(sentinel, path);
1026
- else
1027
- linkSync(sentinel, path);
1028
- }
1029
- else if (fault === 'fifo') {
1030
- rmSync(path);
1031
- execFileSync('mkfifo', [path]);
1032
- }
1033
- else if (['version', 'resolved', 'integrity'].includes(fault)) {
1034
- const lock = JSON.parse(retained[index].toString('utf8'));
1035
- lock.packages['node_modules/@aviaratech/ai-delivery'][fault] = 'incompatible';
1036
- writeFileSync(path, JSON.stringify(lock));
1037
- }
1038
- else
1039
- writeFileSync(path, fault === 'corrupt'
1040
- ? '{'
1041
- : JSON.stringify(index === 0
1042
- ? { dependencies: { '@aviaratech/ai-delivery': 'file:other.tgz' } }
1043
- : { lockfileVersion: 99, packages: {} }));
1044
- const damaged = fault !== 'fifo' && existsSync(path) ? readFileSync(path) : undefined;
1045
- await assert.rejects(api.stageRuntime(f.input), fault === 'symlink' ? /symbolic link/iu : fault === 'fifo' ? /unsupported file/iu : /dependency metadata/iu);
1046
- await assert.rejects(api.admitRuntime(admitInput(f.input, staged.stageId)), /dependency metadata/iu);
1047
- assert.deepEqual(readFileSync(record), complete);
1048
- if (fault === 'fifo')
1049
- assert.equal(lstatSync(path).isFIFO(), true);
1050
- else
1051
- assert.deepEqual(existsSync(path) ? readFileSync(path) : undefined, damaged);
1052
- if (fault === 'symlink' || fault === 'hardlink') {
1053
- assert.deepEqual(readFileSync(sentinel), retained[index]);
1054
- assert.equal(lstatSync(path).isSymbolicLink(), fault === 'symlink');
1055
- }
1056
- assert.equal(readFileSync(f.counter, 'utf8'), 'x', 'metadata refusal must not reinstall');
1057
- rmSync(path, { force: true });
1058
- if (retained[index] !== undefined)
1059
- writeFileSync(path, retained[index]);
1060
- }
1061
- }
1062
- }
1063
- finally {
1064
- f.cleanup();
1065
- }
1066
- });
1067
- for (const metadata of ['package.json', 'package-lock.json']) {
1068
- test(`lost completion response refuses ${metadata} drift during final preflight without reinstalling`, async () => {
1069
- const api = await producer();
1070
- const f = await fixture();
1071
- let operation;
1072
- try {
1073
- const record = join(f.input.runtimeDirectory, 'runtime-stage.json');
1074
- const target = join(f.input.runtimeDirectory, metadata);
1075
- let complete;
1076
- let notifyWritten;
1077
- const written = new Promise((resolve) => {
1078
- notifyWritten = resolve;
1079
- });
1080
- const actual = atomicJson.writePrivateJsonFileAtomically;
1081
- vi.spyOn(atomicJson, 'writePrivateJsonFileAtomically').mockImplementation((path, value) => {
1082
- actual(path, value);
1083
- if (path === record && value.status === 'complete') {
1084
- complete = readFileSync(record);
1085
- actors.authorStarted = false;
1086
- actors.pauseAuthor = true;
1087
- notifyWritten();
1088
- throw new Error('Synthetic completion response lost after durable write');
1089
- }
1090
- });
1091
- operation = api.stageRuntime(f.input);
1092
- const settled = operation.then((value) => ({ status: 'fulfilled', value }), (error) => ({ status: 'rejected', error }));
1093
- const prematurelySettled = settled.then((result) => {
1094
- if (result.status === 'rejected')
1095
- throw result.error;
1096
- throw new Error('Stage completed before the recovery fault was injected.');
1097
- });
1098
- await Promise.race([written, prematurelySettled]);
1099
- while (!actors.authorStarted)
1100
- await Promise.race([new Promise((resolve) => setTimeout(resolve, 10)), prematurelySettled]);
1101
- assert.ok(complete);
1102
- assert.equal(JSON.parse(complete.toString('utf8')).status, 'complete');
1103
- if (metadata === 'package.json')
1104
- rmSync(target);
1105
- else
1106
- writeFileSync(target, '{');
1107
- const damaged = existsSync(target) ? readFileSync(target) : undefined;
1108
- await assert.rejects(operation, /dependency metadata/iu);
1109
- assert.deepEqual(readFileSync(record), complete);
1110
- assert.deepEqual(existsSync(target) ? readFileSync(target) : undefined, damaged);
1111
- assert.equal(readFileSync(f.counter, 'utf8'), 'x');
1112
- assert.equal(existsSync(join(f.root, '.git/ai-delivery/runtime-admission.json')), false);
1113
- }
1114
- finally {
1115
- await operation?.catch(() => undefined);
1116
- actors.pauseAuthor = false;
1117
- vi.restoreAllMocks();
1118
- f.cleanup();
1119
- }
1120
- });
1121
- }
1122
- test('public producer stages exact bytes, explicitly admits and reuses completed work without installing again', async () => {
1123
- const api = await producer();
1124
- const f = await fixture();
1125
- try {
1126
- const staged = await api.stageRuntime(f.input);
1127
- const admissionPath = join(f.root, '.git/ai-delivery/runtime-admission.json');
1128
- assert.equal(existsSync(admissionPath), false);
1129
- assert.equal(staged.admission.sourceCommit, f.input.expectedSourceCommit);
1130
- assert.equal(staged.admission.sourceArchiveSha256, f.input.expectedArchiveSha256);
1131
- const admitted = await api.admitRuntime(admitInput(f.input, staged.stageId));
1132
- assert.equal((await assertDeliveryRuntimeAdmitted({ repoRoot: f.root, runtimeEntryPath: staged.admission.cliPath }))
1133
- .admissionId, admitted.admission.admissionId);
1134
- assert.equal((await api.stageRuntime(f.input)).reused, true);
1135
- assert.equal((await api.admitRuntime(admitInput(f.input, staged.stageId))).reused, true);
1136
- assert.equal(readFileSync(f.counter, 'utf8'), 'x');
1137
- }
1138
- finally {
1139
- f.cleanup();
1140
- }
1141
- });
1142
- test('archive replacement and restoration during install cannot admit alternate bytes under the reviewed digest', async () => {
1143
- const api = await producer();
1144
- const f = await fixture();
1145
- try {
1146
- const reviewed = readFileSync(f.input.archivePath);
1147
- const cli = join(f.base, 'archive/package/dist/cli.js');
1148
- const expectedCli = readFileSync(cli);
1149
- writeFileSync(cli, "#!/usr/bin/env node\nconsole.log('same version, alternate archive bytes');\n");
1150
- execFileSync('tar', ['-czf', join(f.base, 'replacement.tgz'), '-C', join(f.base, 'archive'), 'package']);
1151
- assert.notEqual(digestBytes(readFileSync(join(f.base, 'replacement.tgz'))), f.input.expectedArchiveSha256);
1152
- // The separate installer process replaces the public pathname before extraction and restores A afterward.
1153
- const staged = await api.stageRuntime(f.input);
1154
- const admitted = await api.admitRuntime(admitInput(f.input, staged.stageId));
1155
- assert.ok(readFileSync(f.input.archivePath).equals(reviewed), 'the original archive was restored before revalidation');
1156
- assert.ok(readFileSync(admitted.admission.cliPath).equals(expectedCli), 'alternate archive B was installed and admitted under reviewed archive A digest');
1157
- assert.equal(admitted.admission.sourceArchiveSha256, digestBytes(reviewed));
1158
- assert.equal(admitted.admission.cliSha256, digestBytes(expectedCli));
1159
- const snapshot = join(f.input.runtimeDirectory, 'reviewed-archive.tgz');
1160
- assert.equal(readFileSync(join(f.base, 'installer-archive'), 'utf8'), snapshot);
1161
- assert.ok(readFileSync(snapshot).equals(reviewed));
1162
- const metadata = lstatSync(snapshot);
1163
- assert.ok(metadata.isFile() && !metadata.isSymbolicLink());
1164
- assert.equal(metadata.mode & 0o777, 0o600);
1165
- assert.equal(metadata.nlink, 1);
1166
- assert.equal((await api.stageRuntime(f.input)).reused, true);
1167
- assert.equal(readFileSync(f.counter, 'utf8'), 'x');
1168
- console.log('ARCHIVE_SUBSTITUTION_RECEIPT', JSON.stringify({
1169
- stageId: staged.stageId,
1170
- archiveSha256: digestBytes(reviewed),
1171
- installedCliSha256: digestBytes(expectedCli),
1172
- originalRestored: true,
1173
- privateSnapshotInstalled: true,
1174
- completeRetrySkipped: true,
1175
- }));
1176
- }
1177
- finally {
1178
- f.cleanup();
1179
- }
1180
- });
1181
- for (const corruption of ['missing', 'corrupt', 'symlink', 'hardlink']) {
1182
- test(`completed snapshot ${corruption} rejects reuse and admission while preserving current admission`, async () => {
1183
- const api = await producer();
1184
- const f = await fixture();
1185
- try {
1186
- const staged = await api.stageRuntime(f.input);
1187
- await api.admitRuntime(admitInput(f.input, staged.stageId));
1188
- const admissionPath = join(f.root, '.git/ai-delivery/runtime-admission.json');
1189
- const prior = readFileSync(admissionPath);
1190
- const snapshot = join(f.input.runtimeDirectory, 'reviewed-archive.tgz');
1191
- assert.ok(existsSync(snapshot), 'completed stage must retain its verified archive snapshot');
1192
- if (corruption === 'corrupt')
1193
- writeFileSync(snapshot, 'alternate bytes');
1194
- else {
1195
- rmSync(snapshot);
1196
- if (corruption === 'symlink')
1197
- symlinkSync(f.input.archivePath, snapshot);
1198
- if (corruption === 'hardlink')
1199
- linkSync(f.input.archivePath, snapshot);
1200
- }
1201
- await assert.rejects(api.stageRuntime(f.input));
1202
- await assert.rejects(api.admitRuntime(admitInput(f.input, staged.stageId)));
1203
- assert.ok(readFileSync(admissionPath).equals(prior));
1204
- assert.equal(existsSync(f.input.runtimeDirectory), true);
1205
- assert.equal(readFileSync(f.counter, 'utf8'), 'x');
1206
- }
1207
- finally {
1208
- f.cleanup();
1209
- }
1210
- });
1211
- }
1212
- test('archive snapshot consumes the bounded stage output allowance before running npm', async () => {
1213
- const api = await producer();
1214
- const f = await fixture();
1215
- try {
1216
- await assert.rejects(api.stageRuntime({
1217
- ...f.input,
1218
- resourceBounds: {
1219
- maxAggregateRssBytes: 1024 ** 3,
1220
- minFreeDiskBytes: 256 * 1024 ** 2,
1221
- maxNewOutputBytes: readFileSync(f.input.archivePath).length - 1,
1222
- },
1223
- }), /output.*limit|allowance/u);
1224
- assert.equal(existsSync(f.counter), false);
1225
- assert.equal(existsSync(f.input.runtimeDirectory), false);
1226
- assert.equal(digestBytes(readFileSync(f.input.archivePath)), f.input.expectedArchiveSha256);
1227
- }
1228
- finally {
1229
- f.cleanup();
1230
- }
1231
- });
1232
- test('snapshot durability failure removes the owned partial copy and preserves the original and unrelated files', async () => {
1233
- const api = await producer();
1234
- const f = await fixture();
1235
- const actual = privateFiles.writeCreateOnly;
1236
- const snapshot = join(f.input.runtimeDirectory, 'reviewed-archive.tgz');
1237
- const unrelated = join(f.base, 'unrelated');
1238
- try {
1239
- writeFileSync(unrelated, 'keep');
1240
- const write = vi.spyOn(privateFiles, 'writeCreateOnly').mockImplementation((path, bytes, digest) => {
1241
- if (path === snapshot)
1242
- syncFailure.directory = dirname(path);
1243
- try {
1244
- return actual(path, bytes, digest);
1245
- }
1246
- finally {
1247
- syncFailure.directory = '';
1248
- }
1249
- });
1250
- await assert.rejects(api.stageRuntime(f.input), /durability unavailable/u);
1251
- write.mockRestore();
1252
- assert.equal(existsSync(f.counter), false);
1253
- assert.equal(existsSync(f.input.runtimeDirectory), false);
1254
- assert.equal(digestBytes(readFileSync(f.input.archivePath)), f.input.expectedArchiveSha256);
1255
- assert.equal(readFileSync(unrelated, 'utf8'), 'keep');
1256
- const stage = await api.stageRuntime(f.input);
1257
- assert.equal(stage.reused, false);
1258
- assert.equal(readFileSync(f.counter, 'utf8'), 'x');
1259
- }
1260
- finally {
1261
- syncFailure.directory = '';
1262
- vi.restoreAllMocks();
1263
- f.cleanup();
1264
- }
1265
- });
1266
- for (const denied of [
1267
- 'authority',
1268
- 'archive',
1269
- 'version',
1270
- 'source',
1271
- 'config',
1272
- 'identity',
1273
- 'same-actor',
1274
- 'reviewer-access',
1275
- 'unowned',
1276
- ]) {
1277
- test(`stage rejects ${denied} before adopting or publishing a runtime`, async () => {
1278
- const api = await producer();
1279
- const f = await fixture();
1280
- try {
1281
- const input = { ...f.input };
1282
- if (denied === 'authority')
1283
- input.authority = '';
1284
- if (denied === 'archive')
1285
- writeFileSync(input.archivePath, 'corrupt archive');
1286
- if (denied === 'version')
1287
- input.packageVersion = '0.3.4';
1288
- if (denied === 'source')
1289
- input.expectedSourceCommit = 'a'.repeat(40);
1290
- if (denied === 'config')
1291
- input.expectedConfigDigest = `sha256:${'a'.repeat(64)}`;
1292
- if (denied === 'identity')
1293
- input.identity = 'ambient-author';
1294
- if (denied === 'same-actor')
1295
- actors.reviewer = actors.author;
1296
- if (denied === 'reviewer-access')
1297
- actors.access = false;
1298
- if (denied === 'unowned') {
1299
- mkdirSync(input.runtimeDirectory);
1300
- writeFileSync(join(input.runtimeDirectory, 'preserve'), 'unrelated');
1301
- }
1302
- await assert.rejects(api.stageRuntime(input));
1303
- assert.equal(existsSync(join(f.root, '.git/ai-delivery/runtime-admission.json')), false);
1304
- if (denied === 'unowned')
1305
- assert.equal(readFileSync(join(input.runtimeDirectory, 'preserve'), 'utf8'), 'unrelated');
1306
- else
1307
- assert.equal(existsSync(input.runtimeDirectory), false);
1308
- }
1309
- finally {
1310
- f.cleanup();
1311
- }
1312
- });
1313
- }
1314
- test('admission rejects CAS and actual byte or actor drift while preserving the prior record', async () => {
1315
- const api = await producer();
1316
- const f = await fixture();
1317
- try {
1318
- const staged = await api.stageRuntime(f.input);
1319
- const path = join(f.root, '.git/ai-delivery/runtime-admission.json');
1320
- mkdirSync(dirname(path), { recursive: true });
1321
- writeFileSync(path, 'prior admission\n', { mode: 0o600 });
1322
- await assert.rejects(api.admitRuntime(admitInput(f.input, staged.stageId)), /prior|conflict|compare/u);
1323
- const prior = digestBytes(readFileSync(path));
1324
- actors.author = 'changed-host-user';
1325
- await assert.rejects(api.admitRuntime(admitInput(f.input, staged.stageId, prior)), /actor|route/u);
1326
- actors.author = 'host-user';
1327
- writeFileSync(staged.admission.cliPath, 'changed bytes');
1328
- await assert.rejects(api.admitRuntime(admitInput(f.input, staged.stageId, prior)), /source|bytes|admission/u);
1329
- assert.equal(readFileSync(path, 'utf8'), 'prior admission\n');
1330
- }
1331
- finally {
1332
- f.cleanup();
1333
- }
1334
- });
1335
- test('post-rename errors reconcile desired bytes and never overwrite third-party replacement', async () => {
1336
- const api = await producer();
1337
- const f = await fixture();
1338
- try {
1339
- const staged = await api.stageRuntime(f.input);
1340
- const path = join(f.root, '.git/ai-delivery/runtime-admission.json');
1341
- const actual = atomicJson.writePrivateJsonFileAtomically;
1342
- const write = vi.spyOn(atomicJson, 'writePrivateJsonFileAtomically').mockImplementation((target, value) => {
1343
- actual(target, value);
1344
- if (target === path)
1345
- throw new Error('Synthetic response lost after rename');
1346
- });
1347
- assert.equal((await api.admitRuntime(admitInput(f.input, staged.stageId))).admission.admissionId, staged.admission.admissionId);
1348
- write.mockRestore();
1349
- assert.equal((await api.admitRuntime(admitInput(f.input, staged.stageId))).reused, true);
1350
- rmSync(path);
1351
- const replacement = vi.spyOn(atomicJson, 'writePrivateJsonFileAtomically').mockImplementation((target, value) => {
1352
- actual(target, value);
1353
- if (target === path) {
1354
- writeFileSync(path, 'third-party replacement\n');
1355
- throw new Error('Synthetic concurrent replacement');
1356
- }
1357
- });
1358
- await assert.rejects(api.admitRuntime(admitInput(f.input, staged.stageId)), /conflict|replacement/u);
1359
- replacement.mockRestore();
1360
- assert.equal(readFileSync(path, 'utf8'), 'third-party replacement\n');
1361
- }
1362
- finally {
1363
- vi.restoreAllMocks();
1364
- f.cleanup();
1365
- }
1366
- });
1367
- async function cancelNativeStageWhenReady(running, input, controller, onReady = () => { }) {
1368
- const settled = running.then(() => ({ status: 'fulfilled' }), (reason) => ({ status: 'rejected', reason }));
1369
- let failed = false;
1370
- let failure;
1371
- let outcome;
1372
- try {
1373
- // The real operation retains its native request/resource/cancellation/drain guards.
1374
- // Readiness is an installer condition, not an assumed elapsed preparation duration.
1375
- while (!existsSync(join(input.runtimeDirectory, 'node_modules/.bin/ai-delivery'))) {
1376
- const outcome = await Promise.race([
1377
- settled,
1378
- new Promise((resolve) => setTimeout(resolve, 20, undefined)),
1379
- ]);
1380
- if (outcome?.status === 'rejected')
1381
- throw outcome.reason;
1382
- assert.notEqual(outcome?.status, 'fulfilled', 'Stage completed before the pending installer became ready');
1383
- }
1384
- assert.equal(digestBytes(readFileSync(join(input.runtimeDirectory, 'reviewed-archive.tgz'))), input.expectedArchiveSha256);
1385
- onReady();
1386
- controller.abort();
1387
- await assert.rejects(running, /cancelled/u);
1388
- }
1389
- catch (error) {
1390
- failed = true;
1391
- failure = error;
1392
- }
1393
- finally {
1394
- controller.abort();
1395
- outcome = await settled;
1396
- }
1397
- if (outcome?.status === 'rejected' && !/cancelled/u.test(String(outcome.reason)) && outcome.reason !== failure) {
1398
- if (failed)
1399
- throw new AggregateError([failure, outcome.reason], 'Native fixture assertion and staging both failed');
1400
- throw outcome.reason;
1401
- }
1402
- if (failed)
1403
- throw failure;
1404
- }
1405
- for (const native of [false, true]) {
1406
- test(`${native ? 'native ' : ''}failure and cancellation remove only the owned incomplete stage and preserve unrelated output`, async () => {
1407
- const api = await producer();
1408
- const f = await fixture(native);
1409
- const controller = new AbortController();
1410
- try {
1411
- const unrelated = join(f.base, 'unrelated');
1412
- mkdirSync(unrelated);
1413
- writeFileSync(join(unrelated, 'keep'), 'keep');
1414
- writeFileSync(join(f.base, 'fail'), 'go');
1415
- await assert.rejects(api.stageRuntime(f.input), /exit 7/u);
1416
- assert.equal(existsSync(f.input.runtimeDirectory), false);
1417
- rmSync(join(f.base, 'fail'));
1418
- writeFileSync(join(f.base, 'wait'), 'go');
1419
- const running = api.stageRuntime({ ...f.input, signal: controller.signal });
1420
- if (native)
1421
- await cancelNativeStageWhenReady(running, f.input, controller);
1422
- else {
1423
- void running.catch(() => undefined);
1424
- for (let i = 0; i < 100 && !existsSync(join(f.input.runtimeDirectory, 'node_modules/.bin/ai-delivery')); i++)
1425
- await new Promise((resolve) => setTimeout(resolve, 20));
1426
- assert.equal(digestBytes(readFileSync(join(f.input.runtimeDirectory, 'reviewed-archive.tgz'))), f.input.expectedArchiveSha256);
1427
- controller.abort();
1428
- await assert.rejects(running, /cancelled/u);
1429
- }
1430
- assert.equal(existsSync(f.input.runtimeDirectory), false);
1431
- assert.equal(readFileSync(join(unrelated, 'keep'), 'utf8'), 'keep');
1432
- assert.equal(digestBytes(readFileSync(f.input.archivePath)), f.input.expectedArchiveSha256);
1433
- if (native)
1434
- assert.equal(readFileSync(join(f.input.nativePluginRoot, 'README.md'), 'utf8'), 'Synthetic copied native plugin.\n');
1435
- }
1436
- finally {
1437
- controller.abort();
1438
- f.cleanup();
1439
- }
1440
- });
1441
- }
1442
- test('native cancellation fixture waits for delayed installer readiness', async () => {
1443
- const api = await producer();
1444
- const f = await fixture(true);
1445
- const controller = new AbortController();
1446
- writeFileSync(join(f.base, 'wait'), 'go');
1447
- writeFileSync(join(f.base, 'unrelated'), 'keep');
1448
- actors.pauseAuthor = true;
1449
- const running = api.stageRuntime({ ...f.input, signal: controller.signal });
1450
- const settled = running.then(() => 'fulfilled', () => 'rejected');
1451
- try {
1452
- await cancelNativeStageWhenReady(running, f.input, controller);
1453
- assert.equal(actors.authorStarted, true);
1454
- assert.equal(readFileSync(f.counter, 'utf8'), 'x');
1455
- assert.equal(existsSync(f.input.runtimeDirectory), false);
1456
- assert.equal(readFileSync(join(f.base, 'unrelated'), 'utf8'), 'keep');
1457
- assert.equal(digestBytes(readFileSync(f.input.archivePath)), f.input.expectedArchiveSha256);
1458
- assert.equal(readFileSync(join(f.input.nativePluginRoot, 'README.md'), 'utf8'), 'Synthetic copied native plugin.\n');
1459
- }
1460
- finally {
1461
- controller.abort();
1462
- await settled;
1463
- actors.pauseAuthor = false;
1464
- f.cleanup();
1465
- }
1466
- });
1467
- test('native cancellation fixture preserves an early staging rejection', async () => {
1468
- const api = await producer();
1469
- const f = await fixture(true);
1470
- const controller = new AbortController();
1471
- const input = { ...f.input, authority: '', signal: controller.signal };
1472
- const running = api.stageRuntime(input);
1473
- const settled = running.then(() => 'fulfilled', () => 'rejected');
1474
- try {
1475
- await assert.rejects(cancelNativeStageWhenReady(running, input, controller), /Explicit runtime:stage authority is required/u);
1476
- assert.equal(existsSync(f.counter), false);
1477
- assert.equal(existsSync(f.input.runtimeDirectory), false);
1478
- }
1479
- finally {
1480
- controller.abort();
1481
- await settled;
1482
- f.cleanup();
1483
- }
1484
- });
1485
- test('native cancellation fixture settles a real installer before assertion-failure cleanup', async () => {
1486
- const api = await producer();
1487
- const f = await fixture(true);
1488
- const controller = new AbortController();
1489
- writeFileSync(join(f.base, 'wait'), 'go');
1490
- writeFileSync(join(f.base, 'unrelated'), 'keep');
1491
- const running = api.stageRuntime({ ...f.input, signal: controller.signal });
1492
- let finished = false;
1493
- const settled = running.then(() => {
1494
- finished = true;
1495
- }, () => {
1496
- finished = true;
1497
- });
1498
- const fault = new Error('Synthetic assertion failed with a pending native installer');
1499
- try {
1500
- // Establish readiness independently so this regression isolates teardown ordering.
1501
- while (!existsSync(join(f.input.runtimeDirectory, 'node_modules/.bin/ai-delivery'))) {
1502
- if (finished)
1503
- await running;
1504
- assert.equal(finished, false, 'Stage settled before the pending installer became ready');
1505
- await new Promise((resolve) => setTimeout(resolve, 20));
1506
- }
1507
- await assert.rejects(cancelNativeStageWhenReady(running, f.input, controller, () => {
1508
- throw fault;
1509
- }), (error) => error === fault);
1510
- assert.equal(finished, true, 'Fixture cleanup must wait for actual staging settlement');
1511
- assert.equal(existsSync(f.input.runtimeDirectory), false);
1512
- assert.equal(readFileSync(f.counter, 'utf8'), 'x');
1513
- assert.equal(readFileSync(join(f.base, 'unrelated'), 'utf8'), 'keep');
1514
- assert.equal(readFileSync(join(f.input.nativePluginRoot, 'README.md'), 'utf8'), 'Synthetic copied native plugin.\n');
1515
- }
1516
- finally {
1517
- controller.abort();
1518
- await settled;
1519
- f.cleanup();
1520
- }
1521
- });
1522
- async function assertRetirementErrorBoundaries(error, repoRoot, forbidden) {
1523
- const { printCommandError } = await import('./cliResult.js');
1524
- const stderr = vi.spyOn(process.stderr, 'write').mockReturnValue(true);
1525
- const exitCode = process.exitCode;
1526
- let cliOutput;
1527
- try {
1528
- printCommandError(error);
1529
- cliOutput = stderr.mock.calls.map(([chunk]) => String(chunk)).join('');
1530
- assert.equal(process.exitCode, 1);
1531
- }
1532
- finally {
1533
- stderr.mockRestore();
1534
- process.exitCode = exitCode;
1535
- }
1536
- const dispatch = await import('./dispatch.js');
1537
- const invoke = vi.spyOn(dispatch, 'executeTool').mockRejectedValueOnce(error);
1538
- const { Client } = await import('@modelcontextprotocol/sdk/client/index.js');
1539
- const { InMemoryTransport } = await import('@modelcontextprotocol/sdk/inMemory.js');
1540
- const { createAiDeliveryMcpServer } = await import('./mcp/index.js');
1541
- const server = createAiDeliveryMcpServer({ repoRoot });
1542
- const client = new Client({ name: 'retirement-cause-privacy', version: '1.0.0' });
1543
- const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
1544
- try {
1545
- await server.connect(serverTransport);
1546
- await client.connect(clientTransport);
1547
- const result = await client.callTool({
1548
- name: 'issue_info',
1549
- arguments: { repo: 'example/widget', issueNumber: 17 },
1550
- });
1551
- assert.equal(invoke.mock.calls.length, 1);
1552
- assert.equal(result.isError, true);
1553
- assert.deepEqual(result.content, [{ type: 'text', text: error.message }]);
1554
- const output = cliOutput + JSON.stringify(result);
1555
- assert.ok(output.length < 2048);
1556
- for (const value of forbidden)
1557
- assert.equal(output.includes(value), false);
1558
- }
1559
- finally {
1560
- await client.close();
1561
- await server.close();
1562
- invoke.mockRestore();
1563
- }
1564
- }
1565
- for (const fault of [
1566
- 'installer',
1567
- 'accessors',
1568
- 'cycle',
1569
- 'proxy',
1570
- 'observer',
1571
- 'observer-zero',
1572
- 'observer-retired',
1573
- 'observer-missing',
1574
- 'observer-negative',
1575
- 'observer-fractional',
1576
- 'observer-unsafe',
1577
- 'observer-nonfinite',
1578
- 'observer-string',
1579
- 'observer-array',
1580
- 'observer-malformed',
1581
- 'observer-trailing',
1582
- 'inherited-message',
1583
- 'proxy-root',
1584
- ]) {
1585
- test(`output retirement retains a bounded operation cause without exposing ${fault} failure data`, async () => {
1586
- const api = await producer();
1587
- const f = await fixture();
1588
- const secret = 'fictional_operation_credential';
1589
- const priorSecret = 'fictional_existing_cause_credential';
1590
- const prior = new Error(priorSecret);
1591
- Object.defineProperty(prior, 'cause', { value: prior });
1592
- const primary = new Error('Synthetic retirement refusal', { cause: prior });
1593
- let reads = 0;
1594
- let operation = new Error(secret.repeat(2048));
1595
- let expectedNumbers;
1596
- if (fault.startsWith('observer') || fault === 'inherited-message' || fault === 'proxy-root') {
1597
- const metadata = {
1598
- errorCode: 'ETIMEDOUT',
1599
- elapsedMs: 1001,
1600
- stdoutBytes: 57,
1601
- completeLines: 1,
1602
- rawRows: secret,
1603
- argv: [secret],
1604
- };
1605
- if (fault === 'observer-missing') {
1606
- delete metadata.completeLines;
1607
- Object.defineProperty(metadata, '__proto__', { value: { completeLines: 1 }, enumerable: true });
1608
- }
1609
- else if (fault === 'observer-negative')
1610
- metadata.elapsedMs = -1;
1611
- else if (fault === 'observer-fractional')
1612
- metadata.stdoutBytes = 0.5;
1613
- else if (fault === 'observer-unsafe')
1614
- metadata.completeLines = Number.MAX_SAFE_INTEGER + 1;
1615
- else if (fault === 'observer-nonfinite')
1616
- metadata.elapsedMs = Infinity;
1617
- else if (fault === 'observer-string')
1618
- metadata.stdoutBytes = '57';
1619
- else if (fault === 'observer-zero') {
1620
- metadata.elapsedMs = 0;
1621
- metadata.stdoutBytes = 0;
1622
- metadata.completeLines = 0;
1623
- }
1624
- let payload = JSON.stringify(fault === 'observer-array' ? [metadata] : metadata);
1625
- if (fault === 'observer-malformed')
1626
- payload = `{"errorCode":"ETIMEDOUT","rawRows":"${secret}"`;
1627
- else if (fault === 'observer-trailing')
1628
- payload += secret;
1629
- else if (fault === 'observer-retired')
1630
- payload += ' Output-gate retirement: wrappedOperation=failed.';
1631
- const message = 'Owned process resource observation failed. ' + payload;
1632
- operation = new Error(message);
1633
- if (fault === 'observer' || fault === 'observer-retired')
1634
- expectedNumbers = 'elapsedMs=1001; stdoutBytes=57; completeLines=1';
1635
- else if (fault === 'observer-zero')
1636
- expectedNumbers = 'elapsedMs=0; stdoutBytes=0; completeLines=0';
1637
- if (fault === 'inherited-message') {
1638
- Reflect.deleteProperty(operation, 'message');
1639
- Object.setPrototypeOf(operation, Object.create(Error.prototype, {
1640
- message: {
1641
- get: () => {
1642
- reads++;
1643
- throw new Error(message);
1644
- },
1645
- },
1646
- }));
1647
- }
1648
- else if (fault === 'proxy-root') {
1649
- const trap = () => {
1650
- reads++;
1651
- throw new Error(secret);
1652
- };
1653
- operation = new Proxy(operation, { get: trap, ownKeys: trap, getOwnPropertyDescriptor: trap });
1654
- }
1655
- }
1656
- if (fault === 'accessors') {
1657
- operation = Object.defineProperties(new Error(), {
1658
- message: {
1659
- get: () => {
1660
- reads++;
1661
- throw new Error(secret);
1662
- },
1663
- },
1664
- name: {
1665
- get: () => {
1666
- reads++;
1667
- throw new Error(secret);
1668
- },
1669
- },
1670
- stack: {
1671
- get: () => {
1672
- reads++;
1673
- throw new Error(secret);
1674
- },
1675
- },
1676
- cause: {
1677
- get: () => {
1678
- reads++;
1679
- throw new Error(secret);
1680
- },
1681
- },
1682
- });
1683
- }
1684
- else if (fault === 'cycle') {
1685
- Object.defineProperty(operation, 'cause', { value: operation });
1686
- Object.freeze(operation);
1687
- }
1688
- else if (fault === 'proxy') {
1689
- const trap = () => {
1690
- reads++;
1691
- throw new Error(secret);
1692
- };
1693
- operation = new Error(secret, {
1694
- // The spy checks the thrown root with instanceof; the diagnostic must never inspect its hostile cause.
1695
- cause: new Proxy({}, { get: trap, getPrototypeOf: trap, ownKeys: trap, getOwnPropertyDescriptor: trap }),
1696
- });
1697
- }
1698
- const write = atomicJson.writePrivateJsonFileAtomically;
1699
- const injected = vi.spyOn(atomicJson, 'writePrivateJsonFileAtomically').mockImplementation((path, value) => {
1700
- if (fault !== 'installer' && path === join(f.input.runtimeDirectory, 'runtime-stage.json'))
1701
- throw operation;
1702
- write(path, value);
1703
- });
1704
- try {
1705
- if (fault === 'installer')
1706
- writeFileSync(join(f.base, 'fail'), '');
1707
- retirementFailure.directory = join(f.root, '.git/ai-delivery/output-observation');
1708
- retirementFailure.error = primary;
1709
- retirementFailure.hits = 0;
1710
- let received;
1711
- try {
1712
- await api.stageRuntime(f.input);
1713
- }
1714
- catch (error) {
1715
- received = error;
1716
- }
1717
- assert.equal(retirementFailure.hits, 1, 'the actual gate must retire before the injected refusal');
1718
- assert.equal(received, primary, 'retirement failure keeps its original instance and precedence');
1719
- assert.equal(primary.message, 'Synthetic retirement refusal');
1720
- const cause = Object.getOwnPropertyDescriptor(primary, 'cause')?.value;
1721
- assert.notEqual(cause, prior, 'the masked operation must have its own bounded diagnostic cause');
1722
- assert.ok(cause instanceof Error);
1723
- assert.match(cause.message, /^Wrapped operation failed/u);
1724
- if (fault === 'installer')
1725
- assert.match(cause.message, /exit=7/u);
1726
- if (fault.startsWith('observer'))
1727
- assert.match(cause.message, /observation=ETIMEDOUT/u);
1728
- if (expectedNumbers === undefined)
1729
- assert.doesNotMatch(cause.message, /elapsedMs=|stdoutBytes=|completeLines=/u);
1730
- else
1731
- assert.ok(cause.message.includes(expectedNumbers));
1732
- assert.ok(cause.message.length < 1024);
1733
- assert.equal(cause.message.includes(secret), false);
1734
- assert.equal(Object.getOwnPropertyDescriptor(cause, 'cause')?.value, prior, 'existing retirement cause is retained');
1735
- assert.equal(reads, 0, 'operation getters, proxy traps and cause graphs are never evaluated');
1736
- await assertRetirementErrorBoundaries(primary, f.root, [secret, priorSecret]);
1737
- assert.equal(reads, 0);
1738
- assert.equal(existsSync(f.input.runtimeDirectory), false);
1739
- if (fault === 'installer')
1740
- assert.equal(readFileSync(f.counter, 'utf8'), 'x');
1741
- else
1742
- assert.equal(existsSync(f.counter), false);
1743
- }
1744
- finally {
1745
- retirementFailure.directory = '';
1746
- retirementFailure.error = undefined;
1747
- injected.mockRestore();
1748
- f.cleanup();
1749
- }
1750
- });
1751
- }
1752
- for (const shape of ['nonextensible', 'readonly', 'accessor', 'mutable-nonextensible']) {
1753
- test(`output retirement preserves primary cause descriptors for ${shape} errors`, async () => {
1754
- const api = await producer();
1755
- const f = await fixture();
1756
- const secret = 'fictional_descriptor_credential';
1757
- const prior = new Error(secret);
1758
- const primary = new Error('Synthetic retirement refusal');
1759
- let reads = 0;
1760
- if (shape === 'readonly')
1761
- Object.defineProperty(primary, 'cause', { value: prior, configurable: false, writable: false, enumerable: true });
1762
- else if (shape === 'accessor')
1763
- Object.defineProperty(primary, 'cause', {
1764
- configurable: true,
1765
- get: () => {
1766
- reads++;
1767
- throw new Error(secret);
1768
- },
1769
- });
1770
- else if (shape === 'mutable-nonextensible')
1771
- Object.defineProperty(primary, 'cause', { value: prior, configurable: false, writable: true, enumerable: true });
1772
- if (shape === 'nonextensible' || shape === 'mutable-nonextensible')
1773
- Object.preventExtensions(primary);
1774
- const before = Object.getOwnPropertyDescriptor(primary, 'cause');
1775
- const operation = new Error('Owned process resource observation failed. {"errorCode":"ETIMEDOUT","elapsedMs":1001,"stdoutBytes":57,"completeLines":1}');
1776
- const write = atomicJson.writePrivateJsonFileAtomically;
1777
- const injected = vi.spyOn(atomicJson, 'writePrivateJsonFileAtomically').mockImplementation((path, value) => {
1778
- if (path === join(f.input.runtimeDirectory, 'runtime-stage.json'))
1779
- throw operation;
1780
- write(path, value);
1781
- });
1782
- try {
1783
- retirementFailure.directory = join(f.root, '.git/ai-delivery/output-observation');
1784
- retirementFailure.error = primary;
1785
- retirementFailure.hits = 0;
1786
- let received;
1787
- try {
1788
- await api.stageRuntime(f.input);
1789
- }
1790
- catch (error) {
1791
- received = error;
1792
- }
1793
- assert.equal(received, primary);
1794
- assert.equal(primary.message, 'Synthetic retirement refusal');
1795
- assert.equal(retirementFailure.hits, 1);
1796
- const after = Object.getOwnPropertyDescriptor(primary, 'cause');
1797
- if (shape === 'mutable-nonextensible') {
1798
- assert.ok(after?.value instanceof Error);
1799
- assert.notEqual(after.value, prior);
1800
- assert.match(after.value.message, /elapsedMs=1001; stdoutBytes=57; completeLines=1/u);
1801
- assert.equal(Object.getOwnPropertyDescriptor(after.value, 'cause')?.value, prior);
1802
- assert.deepEqual({ ...after, value: undefined }, { ...before, value: undefined });
1803
- }
1804
- else
1805
- assert.deepEqual(after, before);
1806
- assert.equal(Object.isExtensible(primary), shape === 'readonly' || shape === 'accessor');
1807
- assert.equal(reads, 0);
1808
- await assertRetirementErrorBoundaries(primary, f.root, [secret]);
1809
- assert.equal(reads, 0);
1810
- assert.equal(existsSync(f.input.runtimeDirectory), false);
1811
- assert.equal(existsSync(f.counter), false);
1812
- }
1813
- finally {
1814
- retirementFailure.directory = '';
1815
- retirementFailure.error = undefined;
1816
- injected.mockRestore();
1817
- f.cleanup();
1818
- }
1819
- });
1820
- }
1821
- test('output retirement preserves an operation failure when native retirement succeeds', async () => {
1822
- const api = await producer();
1823
- const f = await fixture();
1824
- try {
1825
- writeFileSync(join(f.base, 'fail'), '');
1826
- await assert.rejects(api.stageRuntime(f.input), /exit 7/u);
1827
- assert.equal(readFileSync(f.counter, 'utf8'), 'x');
1828
- assert.equal(existsSync(f.input.runtimeDirectory), false);
1829
- }
1830
- finally {
1831
- f.cleanup();
1832
- }
1833
- });
1834
- test('output retirement preserves its existing cause after a successful real stage', async () => {
1835
- const api = await producer();
1836
- const f = await fixture();
1837
- const prior = new Error('Existing retirement cause');
1838
- const primary = new Error('Synthetic retirement refusal', { cause: prior });
1839
- try {
1840
- retirementFailure.directory = join(f.root, '.git/ai-delivery/output-observation');
1841
- retirementFailure.error = primary;
1842
- retirementFailure.hits = 0;
1843
- await assert.rejects(api.stageRuntime(f.input), (error) => error === primary);
1844
- assert.equal(retirementFailure.hits, 1);
1845
- assert.equal(primary.cause, prior, 'successful operation does not add a failure cause');
1846
- assert.equal(JSON.parse(readFileSync(join(f.input.runtimeDirectory, 'runtime-stage.json'), 'utf8'))
1847
- .status, 'complete');
1848
- assert.equal((await api.stageRuntime(f.input)).reused, true);
1849
- assert.equal(readFileSync(f.counter, 'utf8'), 'x');
1850
- }
1851
- finally {
1852
- retirementFailure.directory = '';
1853
- retirementFailure.error = undefined;
1854
- f.cleanup();
1855
- }
1856
- });
1857
- test('admission reports unknown durability with exact same-stage reconciliation and preserves desired bytes', async () => {
1858
- const api = await producer();
1859
- const f = await fixture();
1860
- try {
1861
- const stage = await api.stageRuntime(f.input);
1862
- const path = join(f.root, '.git/ai-delivery/runtime-admission.json');
1863
- syncFailure.directory = dirname(path);
1864
- await assert.rejects(api.admitRuntime(admitInput(f.input, stage.stageId)), /commit-status-unknown.*same stage/u);
1865
- const desired = readFileSync(path, 'utf8');
1866
- assert.equal(JSON.parse(desired).admissionId, stage.admission.admissionId);
1867
- syncFailure.directory = '';
1868
- assert.equal((await api.admitRuntime(admitInput(f.input, stage.stageId))).reused, true);
1869
- assert.equal(readFileSync(path, 'utf8'), desired);
1870
- }
1871
- finally {
1872
- syncFailure.directory = '';
1873
- f.cleanup();
1874
- }
1875
- });
1876
- for (const denied of [
1877
- 'candidate',
1878
- 'symlink',
1879
- 'capability',
1880
- 'complete-corrupt',
1881
- 'archive-drift',
1882
- 'source-drift',
1883
- 'config-drift',
1884
- ]) {
1885
- test(`setup preserves completed output and admission on ${denied}`, async () => {
1886
- const api = await producer();
1887
- const f = await fixture();
1888
- try {
1889
- if (denied === 'candidate') {
1890
- const candidate = join(f.base, 'candidate');
1891
- git(f.root, 'worktree', 'add', '-qb', 'candidate', candidate);
1892
- await assert.rejects(api.stageRuntime({ ...f.input, repoRoot: candidate }), /primary/u);
1893
- assert.equal(existsSync(f.input.runtimeDirectory), false);
1894
- return;
1895
- }
1896
- if (denied === 'symlink') {
1897
- symlinkSync(f.base, join(f.base, 'alias'));
1898
- await assert.rejects(api.stageRuntime({ ...f.input, runtimeDirectory: join(f.base, 'alias', 'stage') }), /symbolic link/u);
1899
- return;
1900
- }
1901
- if (denied === 'capability') {
1902
- const manifest = join(f.base, 'archive/package/plugins/ai-delivery/.claude-plugin/plugin.json');
1903
- writeFileSync(manifest, JSON.stringify({ name: 'ai-delivery', packageVersion: '0.3.5', deliveryCapabilityVersion: 1 }));
1904
- execFileSync('tar', ['-czf', f.input.archivePath, '-C', join(f.base, 'archive'), 'package']);
1905
- f.input.expectedArchiveSha256 = digestBytes(readFileSync(f.input.archivePath));
1906
- await assert.rejects(api.stageRuntime(f.input), /capability/u);
1907
- assert.equal(existsSync(f.input.runtimeDirectory), false);
1908
- return;
1909
- }
1910
- const stage = await api.stageRuntime(f.input);
1911
- await api.admitRuntime(admitInput(f.input, stage.stageId));
1912
- const path = join(f.root, '.git/ai-delivery/runtime-admission.json');
1913
- const before = readFileSync(path, 'utf8');
1914
- if (denied === 'complete-corrupt')
1915
- writeFileSync(join(f.input.runtimeDirectory, 'runtime-stage.json'), 'corrupt completion');
1916
- if (denied === 'archive-drift')
1917
- writeFileSync(f.input.archivePath, 'changed archive');
1918
- if (denied === 'source-drift')
1919
- git(f.root, 'commit', '--allow-empty', '-qm', 'source drift');
1920
- if (denied === 'config-drift') {
1921
- const userPath = process.env.AI_DELIVERY_CONFIG;
1922
- const settings = JSON.parse(readFileSync(userPath, 'utf8'));
1923
- settings.roles.author.identity = 'changed-author';
1924
- writeFileSync(userPath, JSON.stringify(settings));
1925
- }
1926
- await assert.rejects(api.admitRuntime(admitInput(f.input, stage.stageId)));
1927
- assert.equal(readFileSync(path, 'utf8'), before);
1928
- assert.equal(existsSync(f.input.runtimeDirectory), true);
1929
- assert.equal(readFileSync(f.counter, 'utf8'), 'x');
1930
- }
1931
- finally {
1932
- f.cleanup();
1933
- }
1934
- });
1935
- }
1936
- test('setup interruption child', { skip: !process.env.AI_DELIVERY_SETUP_INTERRUPT_INPUT }, async () => {
1937
- if (process.env.AI_DELIVERY_CLI_PREPARE) {
1938
- await prepareOwnedCliStage();
1939
- return;
1940
- }
1941
- const api = await producer();
1942
- const phase = process.env.AI_DELIVERY_SETUP_LOG_INTERRUPT_PHASE;
1943
- if (phase) {
1944
- const actual = atomicJson.writePrivateJsonFileAtomically;
1945
- vi.spyOn(atomicJson, 'writePrivateJsonFileAtomically').mockImplementation((path, value) => {
1946
- const record = value;
1947
- const interrupt = path.includes('/runtime-output/') &&
1948
- record.outputs?.[0]?.status === (phase === 'reservation' ? 'reserved' : 'complete');
1949
- if (!(interrupt && phase === 'publication'))
1950
- actual(path, value);
1951
- if (interrupt) {
1952
- writeFileSync(process.env.AI_DELIVERY_SETUP_LOG_INTERRUPT_MARKER, JSON.stringify({ phase, path, owner: process.pid }));
1953
- process.kill(process.pid, 'SIGKILL');
1954
- }
1955
- });
1956
- }
1957
- await api.stageRuntime(JSON.parse(process.env.AI_DELIVERY_SETUP_INTERRUPT_INPUT));
1958
- });
1959
- for (const phase of ['reservation', 'publication']) {
1960
- test(`runtime-stage retained-output recovery preserves charges after hard interruption at ${phase}`, async () => {
1961
- const api = await producer();
1962
- const f = await fixture();
1963
- const marker = join(f.base, 'log-interruption-marker');
1964
- const input = {
1965
- ...f.input,
1966
- resourceBounds: {
1967
- maxAggregateRssBytes: 512 * 1024 ** 2,
1968
- minFreeDiskBytes: 1,
1969
- maxNewOutputBytes: 128 * 1024 ** 2,
1970
- maxCapturedOutputBytes: 1024 ** 2,
1971
- },
1972
- };
1973
- let child;
1974
- try {
1975
- writeFileSync(join(f.base, 'fail'), 'go');
1976
- writeFileSync(join(f.base, 'log-bytes'), String(100 * 1024));
1977
- child = spawn(process.execPath, [
1978
- join(process.cwd(), 'node_modules/vitest/vitest.mjs'),
1979
- 'run',
1980
- new URL(import.meta.url).pathname,
1981
- '-t',
1982
- '^setup interruption child$',
1983
- '--maxWorkers=1',
1984
- '--no-file-parallelism',
1985
- ], {
1986
- env: {
1987
- ...process.env,
1988
- AI_DELIVERY_SETUP_INTERRUPT_INPUT: JSON.stringify(input),
1989
- AI_DELIVERY_SETUP_LOG_INTERRUPT_PHASE: phase,
1990
- AI_DELIVERY_SETUP_LOG_INTERRUPT_MARKER: marker,
1991
- },
1992
- stdio: 'ignore',
1993
- });
1994
- await new Promise((resolve) => child.once('close', () => resolve()));
1995
- assert.equal(existsSync(marker), true, 'hard interruption must occur at the selected durable log boundary');
1996
- const writerPath = join(f.root, '.git/ai-delivery/writers@1', `${digestValue(f.root).slice(7)}.json`);
1997
- const stale = new Date(Date.now() - 20_000);
1998
- utimesSync(`${writerPath}.lock`, stale, stale);
1999
- const { path } = JSON.parse(readFileSync(marker, 'utf8'));
2000
- const prior = JSON.parse(readFileSync(path, 'utf8'));
2001
- assert.equal(prior.outputs[0].status, 'reserved');
2002
- assert.equal(prior.outputs[0].bytes, 100 * 1024);
2003
- const outputDirectory = join(f.root, '.git/ai-delivery/verification@1/command-output');
2004
- const priorOutput = join(outputDirectory, `${prior.outputs[0].digest.slice(7)}.bin`);
2005
- assert.equal(existsSync(priorOutput), phase === 'publication');
2006
- const preserved = phase === 'publication' ? readFileSync(priorOutput) : undefined;
2007
- writeFileSync(join(f.base, 'log-bytes'), String(128 * 1024));
2008
- await assert.rejects(api.stageRuntime(input), /exit 7/u);
2009
- const recovered = JSON.parse(readFileSync(path, 'utf8'));
2010
- assert.equal(recovered.outputs.reduce((total, output) => total + output.bytes, 0), 228 * 1024);
2011
- assert.equal(recovered.outputs[0].status, phase === 'publication' ? 'complete' : 'reserved');
2012
- if (preserved)
2013
- assert.deepEqual(readFileSync(priorOutput), preserved);
2014
- if (phase === 'reservation') {
2015
- writeFileSync(join(f.base, 'log-bytes'), String(100 * 1024));
2016
- await assert.rejects(api.stageRuntime(input), /identical output cannot be rewritten/u);
2017
- assert.equal(existsSync(priorOutput), false, 'unresolved reservation must not authorize a second raw-log write');
2018
- }
2019
- rmSync(join(f.base, 'fail'));
2020
- rmSync(join(f.base, 'log-bytes'));
2021
- const completed = await api.stageRuntime(input);
2022
- const count = readFileSync(f.counter, 'utf8');
2023
- assert.equal(completed.reused, false);
2024
- assert.equal((await api.stageRuntime(input)).reused, true);
2025
- assert.equal(readFileSync(f.counter, 'utf8'), count, 'completed recovered stage must skip the installer');
2026
- assert.equal(readFileSync(completed.admission.cliPath, 'utf8'), "#!/usr/bin/env node\nconsole.log('0.3.5');\n");
2027
- }
2028
- finally {
2029
- if (child?.exitCode === null && child.signalCode === null)
2030
- child.kill('SIGKILL');
2031
- f.cleanup();
2032
- }
2033
- });
2034
- }
2035
- for (const native of [false, true]) {
2036
- test(`${native ? 'native ' : ''}stopped setup owners stay busy and orphan recovery confirms cleanup before retrying the incomplete install`, async () => {
2037
- const api = await producer();
2038
- const f = await fixture(native);
2039
- let child;
2040
- let ownedPid;
2041
- let ownedIdentity;
2042
- let ownerPid;
2043
- const peer = spawn(process.execPath, ['-e', 'setInterval(()=>{},1000)'], { detached: true, stdio: 'ignore' });
2044
- try {
2045
- writeFileSync(join(f.base, 'wait'), 'go');
2046
- child = spawn(process.execPath, [
2047
- join(process.cwd(), 'node_modules/vitest/vitest.mjs'),
2048
- 'run',
2049
- 'dist/setup.test.js',
2050
- '-t',
2051
- '^setup interruption child$',
2052
- ], {
2053
- cwd: process.cwd(),
2054
- stdio: 'ignore',
2055
- env: { ...process.env, AI_DELIVERY_SETUP_INTERRUPT_INPUT: JSON.stringify(f.input) },
2056
- });
2057
- const closed = new Promise((resolve) => child.once('close', resolve));
2058
- const writerPath = join(f.root, '.git/ai-delivery/writers@1', `${(await import('./delivery/index.js')).digestValue(f.root).slice(7)}.json`);
2059
- let record;
2060
- // Bound this cold installer-start observation, not the recovery run.
2061
- for (let i = 0; i < 1000; i++) {
2062
- if (existsSync(writerPath))
2063
- record = JSON.parse(readFileSync(writerPath, 'utf8'));
2064
- if (record?.command.phase === 'running' && existsSync(f.marker))
2065
- break;
2066
- await new Promise((resolve) => setTimeout(resolve, 20));
2067
- }
2068
- assert.equal(record?.command.phase, 'running');
2069
- assert.equal(existsSync(f.marker), true, 'interrupt only after the owned installer actually starts');
2070
- const snapshot = join(f.input.runtimeDirectory, 'reviewed-archive.tgz');
2071
- assert.equal(digestBytes(readFileSync(snapshot)), f.input.expectedArchiveSha256);
2072
- ownerPid = record.owner.pid;
2073
- ownedPid = record.command.root.pid;
2074
- ownedIdentity = record.command.root.identity;
2075
- process.kill(ownerPid, 'SIGSTOP');
2076
- const stale = new Date(Date.now() - 20_000);
2077
- utimesSync(`${writerPath}.lock`, stale, stale);
2078
- await assert.rejects(api.stageRuntime(f.input), /live verification writer/u);
2079
- assert.equal(readFileSync(f.counter, 'utf8'), 'x');
2080
- process.kill(ownerPid, 'SIGKILL');
2081
- ownerPid = undefined;
2082
- await closed;
2083
- process.kill(ownedPid, 0);
2084
- writeFileSync(snapshot, 'interrupted incomplete snapshot');
2085
- rmSync(join(f.base, 'wait'));
2086
- const recovered = await api.stageRuntime(f.input).catch((error) => {
2087
- if (error instanceof Error)
2088
- error.message += ` Fictional setup interruption phase=orphan-recovery; native=${native}.`;
2089
- throw error;
2090
- });
2091
- assert.equal(recovered.reused, false);
2092
- assert.equal(readFileSync(f.counter, 'utf8'), 'xx');
2093
- assert.equal(existsSync(writerPath), false);
2094
- assert.equal(digestBytes(readFileSync(snapshot)), f.input.expectedArchiveSha256);
2095
- const completedSnapshot = lstatSync(snapshot);
2096
- process.kill(peer.pid, 0);
2097
- const state = spawnSync('/bin/ps', ['-p', String(ownedPid), '-o', 'stat='], { encoding: 'utf8' });
2098
- assert.ok(state.status === 1 || state.stdout.trim().startsWith('Z'));
2099
- ownedPid = undefined;
2100
- assert.equal((await api.stageRuntime(f.input)).reused, true);
2101
- assert.equal(readFileSync(f.counter, 'utf8'), 'xx');
2102
- assert.equal(lstatSync(snapshot).ino, completedSnapshot.ino);
2103
- console.log('SETUP_INTERRUPTION_RECEIPT', JSON.stringify({
2104
- completedStageId: recovered.stageId,
2105
- installerExecutions: 2,
2106
- peerPreserved: true,
2107
- ownedCleanupConfirmed: true,
2108
- completedRetrySkipped: true,
2109
- incompleteSnapshotRebuilt: true,
2110
- completedSnapshotReused: true,
2111
- archiveSha256: f.input.expectedArchiveSha256,
2112
- nativePluginRoot: f.input.nativePluginRoot ?? null,
2113
- }));
2114
- }
2115
- finally {
2116
- if (ownerPid !== undefined) {
2117
- process.kill(ownerPid, 'SIGCONT');
2118
- process.kill(ownerPid, 'SIGKILL');
2119
- }
2120
- if (ownedPid !== undefined &&
2121
- spawnSync('/bin/ps', ['-p', String(ownedPid), '-o', 'lstart='], { encoding: 'utf8' }).stdout.trim() ===
2122
- ownedIdentity)
2123
- process.kill(ownedPid, 'SIGKILL');
2124
- if (peer.exitCode === null && peer.signalCode === null)
2125
- peer.kill('SIGKILL');
2126
- if (child?.exitCode === null && child.signalCode === null)
2127
- child.kill('SIGKILL');
2128
- f.cleanup();
2129
- }
2130
- });
2131
- }
2132
- const stageAdmitCase = 'CLI stage and admit execute the same public producer with explicit authority and prior absence';
2133
- const preparedCliSchema = z.strictObject({
2134
- ownerRoot: z.string(),
2135
- base: z.string(),
2136
- stageId: z.string().regex(/^sha256:[a-f0-9]{64}$/u),
2137
- configPath: z.string(),
2138
- npmBin: z.string(),
2139
- author: z.literal('host-user'),
2140
- reviewer: z.literal('reviewer[bot]'),
2141
- input: z.strictObject({
2142
- authority: z.literal('runtime:stage'),
2143
- identity: z.literal('host-author'),
2144
- repoRoot: z.string(),
2145
- archivePath: z.string(),
2146
- expectedArchiveSha256: z.string(),
2147
- packageVersion: z.literal('0.3.5'),
2148
- expectedSourceCommit: z.string(),
2149
- expectedConfigDigest: z.string(),
2150
- runtimeDirectory: z.string(),
2151
- }),
2152
- files: z.array(z.strictObject({ path: z.string(), digest: z.string() })).length(6),
2153
- });
2154
- function preparedCliClosure(input) {
2155
- const npmRoot = join(dirname(process.execPath), '../lib/node_modules/npm');
2156
- assert.equal(JSON.parse(readFileSync(join(npmRoot, 'package.json'), 'utf8')).version, '11.19.0');
2157
- const result = spawnSync(process.execPath, [
2158
- join(npmRoot, 'bin/npm-cli.js'),
2159
- 'ls',
2160
- '--prefix',
2161
- input.runtimeDirectory,
2162
- '--omit=dev',
2163
- '--all',
2164
- '--json',
2165
- '--logs-max',
2166
- '0',
2167
- ], {
2168
- cwd: input.repoRoot,
2169
- encoding: 'utf8',
2170
- maxBuffer: 1024 ** 2,
2171
- });
2172
- assert.equal(result.error, undefined);
2173
- assert.equal(result.status, 0, result.stderr + result.stdout);
2174
- const graph = JSON.parse(result.stdout);
2175
- assert.equal(graph.problems, undefined);
2176
- const dependency = graph.dependencies['@aviaratech/ai-delivery'];
2177
- assert.equal(dependency.version, input.packageVersion);
2178
- assert.equal(dependency.resolved, `file:${join(input.runtimeDirectory, 'reviewed-archive.tgz')}`);
2179
- assert.equal(dependency.invalid, undefined);
2180
- assert.equal(dependency.missing, undefined);
2181
- }
2182
- function readPreparedCli(ownerRoot) {
2183
- assert.equal(realpathSync(ownerRoot), ownerRoot);
2184
- const prepared = preparedCliSchema.parse(JSON.parse(privateFiles.assertPrivateFile(join(ownerRoot, 'prepared.json'), { maxBytes: 16 * 1024 }).toString('utf8')));
2185
- assert.equal(prepared.ownerRoot, ownerRoot);
2186
- const below = (path) => {
2187
- const name = relative(ownerRoot, path);
2188
- assert.ok(name !== '' && name !== '..' && !name.startsWith('..' + sep) && !isAbsolute(name));
2189
- assert.equal(realpathSync(path), path);
2190
- };
2191
- for (const path of [
2192
- prepared.base,
2193
- prepared.configPath,
2194
- prepared.npmBin,
2195
- prepared.input.repoRoot,
2196
- prepared.input.archivePath,
2197
- prepared.input.runtimeDirectory,
2198
- ...prepared.files.map((f) => f.path),
2199
- ])
2200
- below(path);
2201
- assert.equal(dirname(prepared.base), ownerRoot);
2202
- assert.ok(prepared.base.split(sep).at(-1).startsWith('ai-delivery-setup-'));
2203
- assert.equal(prepared.input.repoRoot, join(prepared.base, 'consumer'));
2204
- assert.equal(prepared.input.runtimeDirectory, join(prepared.base, 'staged'));
2205
- assert.equal(prepared.input.archivePath, join(prepared.base, 'reviewed archive; inert.tgz'));
2206
- assert.equal(prepared.configPath, join(prepared.base, 'user.json'));
2207
- assert.equal(prepared.npmBin, join(prepared.base, 'prepared-npm'));
2208
- assert.equal(digestBytes(readFileSync(prepared.input.archivePath)), prepared.input.expectedArchiveSha256);
2209
- assert.equal(git(prepared.input.repoRoot, 'rev-parse', 'HEAD'), prepared.input.expectedSourceCommit);
2210
- assert.equal(git(prepared.input.repoRoot, 'status', '--porcelain'), '');
2211
- const recordPath = join(prepared.input.runtimeDirectory, 'runtime-stage.json');
2212
- const record = JSON.parse(privateFiles.assertPrivateFile(recordPath).toString('utf8'));
2213
- const { recordId, ...content } = record;
2214
- assert.equal(digestValue(content), recordId);
2215
- assert.equal(record.status, 'complete');
2216
- assert.equal(record.stageId, prepared.stageId, 'Prepared CLI stage identity mismatch');
2217
- assert.equal(digestValue(record.intent), prepared.stageId);
2218
- for (const [field, value] of Object.entries({
2219
- repoRoot: prepared.input.repoRoot,
2220
- runtimeDirectory: prepared.input.runtimeDirectory,
2221
- sourceCommit: prepared.input.expectedSourceCommit,
2222
- configDigest: prepared.input.expectedConfigDigest,
2223
- archivePath: prepared.input.archivePath,
2224
- archiveSha256: prepared.input.expectedArchiveSha256,
2225
- packageVersion: prepared.input.packageVersion,
2226
- }))
2227
- assert.equal(record.intent[field], value);
2228
- assert.deepEqual(record.intent.resourceBounds, {
2229
- maxAggregateRssBytes: 1024 ** 3,
2230
- minFreeDiskBytes: 256 * 1024 ** 2,
2231
- maxNewOutputBytes: 512 * 1024 ** 2,
2232
- maxCapturedOutputBytes: 1024 ** 2,
2233
- });
2234
- const expectedPaths = [
2235
- recordPath,
2236
- join(prepared.input.runtimeDirectory, 'package.json'),
2237
- join(prepared.input.runtimeDirectory, 'package-lock.json'),
2238
- join(prepared.input.runtimeDirectory, 'reviewed-archive.tgz'),
2239
- join(prepared.input.runtimeDirectory, 'node_modules/@aviaratech/ai-delivery/dist/cli.js'),
2240
- prepared.configPath,
2241
- ];
2242
- assert.deepEqual(prepared.files.map((f) => f.path), expectedPaths);
2243
- for (const file of prepared.files)
2244
- assert.equal(digestBytes(readFileSync(file.path)), file.digest);
2245
- assert.equal(readFileSync(join(prepared.base, 'installs'), 'utf8'), 'x');
2246
- return prepared;
2247
- }
2248
- async function prepareOwnedCliStage() {
2249
- const ownerRoot = process.env.AI_DELIVERY_CLI_PREPARE;
2250
- const f = await fixture(false, ownerRoot);
2251
- const previousPath = process.env.PATH;
2252
- const scenario = process.env.AI_DELIVERY_STAGE_ADMIT_SCENARIO;
2253
- try {
2254
- writeFileSync(join(f.base, 'unrelated-preparation'), 'unrelated');
2255
- const npmRoot = join(dirname(process.execPath), '../lib/node_modules/npm');
2256
- assert.equal(JSON.parse(readFileSync(join(npmRoot, 'package.json'), 'utf8')).version, '11.19.0');
2257
- const npmBin = join(f.base, 'prepared-npm');
2258
- mkdirSync(npmBin);
2259
- 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`);
2260
- chmodSync(join(npmBin, 'npm'), 0o755);
2261
- process.env.PATH = `${npmBin}:${previousPath ?? ''}`;
2262
- const stage = await (await producer()).stageRuntime(f.input);
2263
- preparedCliClosure(f.input);
2264
- assert.equal(stage.reused, false);
2265
- assert.equal(existsSync(join(f.root, '.git/ai-delivery/runtime-admission.json')), false);
2266
- const files = [
2267
- join(f.input.runtimeDirectory, 'runtime-stage.json'),
2268
- join(f.input.runtimeDirectory, 'package.json'),
2269
- join(f.input.runtimeDirectory, 'package-lock.json'),
2270
- join(f.input.runtimeDirectory, 'reviewed-archive.tgz'),
2271
- stage.admission.cliPath,
2272
- join(f.base, 'user.json'),
2273
- ].map((path) => ({ path, digest: digestBytes(readFileSync(path)) }));
2274
- atomicJson.writePrivateJsonFileAtomically(join(ownerRoot, 'prepared.json'), {
2275
- ownerRoot,
2276
- base: f.base,
2277
- stageId: stage.stageId,
2278
- configPath: join(f.base, 'user.json'),
2279
- npmBin,
2280
- author: actors.author,
2281
- reviewer: actors.reviewer,
2282
- input: f.input,
2283
- files,
2284
- });
2285
- readPreparedCli(ownerRoot);
2286
- }
2287
- finally {
2288
- // The outer supervisor owns fixture disposal, including a killed preparation process.
2289
- process.env.PATH = previousPath;
2290
- }
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
- }
2317
- // Re-enter this same case so cancellation can contain synchronous CLI work as well as promises.
2318
- // The existing producer supervisor owns the native process; these callbacks only retain its observations.
2319
- async function observeStageAdmitCase(scenario = 'normal', traceFault) {
2320
- const { runStageCommand } = await import('./verification.js');
2321
- const root = realpathSync(mkdtempSync(join(tmpdir(), 'ai-delivery-cli-case-')));
2322
- const tracePath = join(root, 'phases.json');
2323
- const cancellation = new AbortController();
2324
- let idle = false;
2325
- let cleanupFailure;
2326
- let receiptFailure;
2327
- let lastPhase = [];
2328
- let deadline = 0;
2329
- const active = new Map();
2330
- const pendingUnits = new Map();
2331
- const startedUnits = new Set();
2332
- const completedUnits = [];
2333
- let fixtureBinding;
2334
- let seen = 0;
2335
- let cancelledPhase;
2336
- let failure;
2337
- let failedBytes;
2338
- let owned;
2339
- const identities = new Map();
2340
- let residualInstaller;
2341
- let cleanupState;
2342
- let traceFaultInjected = false;
2343
- let unreadableSince;
2344
- let prepared;
2345
- let preparationStartedAt;
2346
- let preparationElapsedMs;
2347
- let preparationCompleted = false;
2348
- const needsPreparation = [
2349
- 'budget',
2350
- 'admission-stall',
2351
- 'handoff-mismatch',
2352
- 'preparation-failure',
2353
- 'preparation-cancel',
2354
- ].includes(scenario);
2355
- const readPhases = () => {
2356
- const value = JSON.parse(privateFiles.assertPrivateFile(tracePath, { maxBytes: 64 * 1024 }).toString('utf8'));
2357
- assert.ok(Array.isArray(value) && value.length <= 64, 'CLI phase count exceeded its bound');
2358
- let previous = -1;
2359
- for (const item of value) {
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');
2364
- const entry = item;
2365
- assert.ok(typeof entry.phase === 'string' &&
2366
- entry.phase.length <= 64 &&
2367
- ['start', 'end', 'settled', 'pending'].includes(entry.event ?? '') &&
2368
- typeof entry.atMs === 'number' &&
2369
- Number.isFinite(entry.atMs) &&
2370
- entry.atMs >= 0 &&
2371
- entry.atMs >= previous, 'CLI phase entry is invalid');
2372
- previous = entry.atMs;
2373
- if (entry.unit !== undefined)
2374
- cliUnitSchema.parse(entry.unit);
2375
- }
2376
- const phases = value;
2377
- assert.ok(phases.length >= lastPhase.length &&
2378
- lastPhase.every((entry, index) => {
2379
- const current = phases[index];
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));
2384
- }), 'CLI phase history changed after observation');
2385
- return phases;
2386
- };
2387
- const save = () => {
2388
- try {
2389
- writeFileSync(join(root, 'ownership.json'), JSON.stringify({ idle, owned, cleanupFailure, receiptFailure }), {
2390
- mode: 0o600,
2391
- });
2392
- }
2393
- catch (error) {
2394
- receiptFailure = error instanceof Error ? error.message : String(error);
2395
- cancellation.abort();
2396
- }
2397
- };
2398
- let watch;
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) => {
2418
- try {
2419
- if (existsSync(tracePath)) {
2420
- const phases = readPhases();
2421
- unreadableSince = undefined;
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
- }
2465
- if (entry.event === 'start')
2466
- active.set(entry.phase, performance.now() + (scenario === 'unfinished' && entry.phase === 'runtime:stage' ? 30_000 : 15_000));
2467
- else if (entry.event === 'end' || entry.event === 'settled')
2468
- active.delete(entry.phase);
2469
- }
2470
- lastPhase = phases;
2471
- if (phases.length > seen)
2472
- deadline = performance.now() + 15_000;
2473
- seen = phases.length;
2474
- if (injectFault && !idle && traceFault !== undefined && traceFault !== 'write' && !traceFaultInjected) {
2475
- const fixtureRoot = readdirSync(root).find((name) => name.startsWith('ai-delivery-setup-'));
2476
- const marker = fixtureRoot === undefined ? undefined : join(root, fixtureRoot, 'installer-running');
2477
- if (marker !== undefined && existsSync(marker)) {
2478
- assert.equal(readFileSync(join(dirname(marker), 'installs'), 'utf8'), 'x');
2479
- traceFaultInjected = true;
2480
- if (traceFault === 'missing')
2481
- rmSync(tracePath);
2482
- else if (traceFault === 'oversized') {
2483
- writeFileSync(tracePath, Buffer.alloc(64 * 1024 + 1, 32));
2484
- sharedOutputRead.path = tracePath;
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
- }
2507
- else
2508
- writeFileSync(tracePath, JSON.stringify(Array.from({ length: 65 }, () => phases[0])));
2509
- }
2510
- }
2511
- }
2512
- else if (seen > 0)
2513
- throw new Error('CLI phase evidence disappeared after observation');
2514
- }
2515
- catch (error) {
2516
- const message = error instanceof Error ? error.message : String(error);
2517
- // Atomic replacement can race an identity-bound read. Retry only that bounded observation,
2518
- // while operation deadlines continue to run; missing, oversized or invalid history fails immediately.
2519
- 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);
2520
- if (changing)
2521
- unreadableSince ??= performance.now();
2522
- if (!changing || performance.now() - unreadableSince >= 1_000) {
2523
- receiptFailure ??= message;
2524
- cancellation.abort();
2525
- }
2526
- }
2527
- const overdue = [...active].find(([, limit]) => performance.now() >= limit);
2528
- if (overdue !== undefined || (active.size === 0 && performance.now() >= deadline)) {
2529
- cancelledPhase ??= overdue?.[0] ?? (seen === 0 ? 'bootstrap' : 'native-drain');
2530
- cancellation.abort();
2531
- }
2532
- };
2533
- const executeChild = async (preparing) => {
2534
- idle = false;
2535
- failedBytes = undefined;
2536
- const output = await runStageCommand(process.cwd(), [
2537
- process.execPath,
2538
- join(process.cwd(), 'node_modules/vitest/vitest.mjs'),
2539
- 'run',
2540
- 'dist/setup.test.js',
2541
- '-t',
2542
- preparing ? '^setup interruption child$' : `^${stageAdmitCase}$`,
2543
- ], cancellation.signal, undefined,
2544
- // This bounded synthetic case uses the fixture floor, not a local host's 100 GiB reserve.
2545
- { maxAggregateRssBytes: 3 * 1024 ** 3, minFreeDiskBytes: 256 * 1024 ** 2 }, undefined, undefined, {
2546
- starting: () => {
2547
- idle = false;
2548
- save();
2549
- },
2550
- observed: (state) => {
2551
- cleanupState = { ...state, tracked: new Map(state.tracked) };
2552
- for (const member of state.tracked.values()) {
2553
- if (identities.size >= 512 && !identities.has(`${member.pid}:${member.identity}`)) {
2554
- receiptFailure ??= 'CLI ownership observation count exceeded its bound';
2555
- cancellation.abort();
2556
- break;
2557
- }
2558
- identities.set(`${member.pid}:${member.identity}`, {
2559
- pid: member.pid,
2560
- identity: member.identity,
2561
- pgid: member.pgid,
2562
- });
2563
- }
2564
- owned = {
2565
- rootPid: state.rootPid,
2566
- rootIdentity: state.rootIdentity,
2567
- sampled: state.sampled,
2568
- tracked: [...identities.values()],
2569
- };
2570
- save();
2571
- },
2572
- idle: () => {
2573
- idle = true;
2574
- save();
2575
- },
2576
- assertQuiescent: () => assert.ok(idle && cleanupFailure === undefined),
2577
- }, {
2578
- environment: {
2579
- ...process.env,
2580
- TMPDIR: root,
2581
- TMP: root,
2582
- TEMP: root,
2583
- AI_DELIVERY_STAGE_ADMIT_CHILD: tracePath,
2584
- AI_DELIVERY_STAGE_ADMIT_SCENARIO: scenario,
2585
- AI_DELIVERY_STAGE_ADMIT_TRACE_FAULT: traceFault ?? '',
2586
- AI_DELIVERY_CLI_PREPARE: preparing ? root : '',
2587
- ...(preparing ? { AI_DELIVERY_SETUP_INTERRUPT_INPUT: 'owned-cli-preparation' } : {}),
2588
- AI_DELIVERY_CLI_PREPARED_ROOT: !preparing && prepared !== undefined ? root : '',
2589
- },
2590
- maxCapturedOutputBytes: 32 * 1024 ** 2,
2591
- includeControllerTree: true,
2592
- failedOutput: (bytes) => {
2593
- failedBytes = bytes;
2594
- if (bytes.includes(Buffer.from('SETUP_CLI_TRACE_WRITE_FAULT_WITH_PENDING')))
2595
- traceFaultInjected = true;
2596
- if (bytes.includes(Buffer.from('SETUP_CLI_TRACE_FAILURE')))
2597
- receiptFailure ??= 'Child CLI phase write failed';
2598
- return ` CLI case output ${digestBytes(bytes)} (${bytes.length} bytes).`;
2599
- },
2600
- onCleanupFailure: (reason) => {
2601
- cleanupFailure = reason;
2602
- save();
2603
- },
2604
- });
2605
- if (output.includes(Buffer.from('SETUP_CLI_TRACE_FAILURE')))
2606
- receiptFailure ??= 'Child CLI phase write failed';
2607
- process.stdout.write(output);
2608
- };
2609
- try {
2610
- if (needsPreparation) {
2611
- preparationStartedAt = performance.now();
2612
- const cancelPreparation = scenario === 'preparation-cancel'
2613
- ? setInterval(() => {
2614
- const base = readdirSync(root).find((name) => name.startsWith('ai-delivery-setup-'));
2615
- if (base !== undefined && existsSync(join(root, base, 'installer-running')))
2616
- cancellation.abort();
2617
- }, 50)
2618
- : undefined;
2619
- try {
2620
- await executeChild(true);
2621
- assert.ok(idle && cleanupFailure === undefined, 'preparation must settle with native quiescence');
2622
- prepared = readPreparedCli(root);
2623
- preparedCliClosure(prepared.input);
2624
- preparationCompleted = true;
2625
- if (scenario === 'handoff-mismatch')
2626
- atomicJson.writePrivateJsonFileAtomically(join(root, 'prepared.json'), {
2627
- ...prepared,
2628
- stageId: 'sha256:' + '0'.repeat(64),
2629
- });
2630
- }
2631
- finally {
2632
- if (cancelPreparation !== undefined)
2633
- clearInterval(cancelPreparation);
2634
- preparationElapsedMs = performance.now() - preparationStartedAt;
2635
- }
2636
- }
2637
- deadline = performance.now() + 15_000;
2638
- watch = setInterval(watchPhases, 50);
2639
- await executeChild(false);
2640
- }
2641
- catch (error) {
2642
- failure = error instanceof Error ? error.message : String(error);
2643
- if (failedBytes !== undefined)
2644
- process.stdout.write(failedBytes);
2645
- }
2646
- finally {
2647
- if (watch !== undefined)
2648
- clearInterval(watch);
2649
- if (needsPreparation && !preparationCompleted)
2650
- receiptFailure ??= 'CLI preparation failed before completed handoff';
2651
- else {
2652
- try {
2653
- watchPhases(false);
2654
- }
2655
- catch (error) {
2656
- receiptFailure ??= error instanceof Error ? error.message : String(error);
2657
- }
2658
- }
2659
- if (idle && cleanupFailure === undefined) {
2660
- try {
2661
- for (const name of readdirSync(root).filter((name) => name.startsWith('ai-delivery-setup-'))) {
2662
- const base = join(root, name);
2663
- const marker = join(base, 'installer-running');
2664
- if (existsSync(marker)) {
2665
- assert.ok(lstatSync(marker).size <= 64 && lstatSync(join(base, 'installs')).size <= 64);
2666
- residualInstaller = {
2667
- pid: Number(readFileSync(marker, 'utf8')),
2668
- counter: readFileSync(join(base, 'installs'), 'utf8'),
2669
- noiseWrites: existsSync(join(base, 'noise-writes')) ? lstatSync(join(base, 'noise-writes')).size : 0,
2670
- };
2671
- }
2672
- }
2673
- }
2674
- catch (error) {
2675
- receiptFailure ??= error instanceof Error ? error.message : String(error);
2676
- }
2677
- }
2678
- process.stdout.write('SETUP_CLI_PHASE_RECEIPT ' +
2679
- JSON.stringify({
2680
- scenario,
2681
- traceFault,
2682
- traceFaultInjected,
2683
- phases: lastPhase,
2684
- nativeIdle: idle,
2685
- cancelledPhase,
2686
- failure,
2687
- cleanupFailure,
2688
- receiptFailure,
2689
- owned,
2690
- root,
2691
- residualInstaller,
2692
- preparationElapsedMs,
2693
- preparationCompleted,
2694
- completedUnits,
2695
- }) +
2696
- '\n');
2697
- }
2698
- if (!idle || cleanupFailure !== undefined || receiptFailure !== undefined)
2699
- throw Object.assign(new Error(`CLI case ownership unresolved; preserve ${root}`), {
2700
- root,
2701
- nativeIdle: idle,
2702
- cleanupState,
2703
- receiptFailure,
2704
- residualInstaller,
2705
- retainedPhaseCount: lastPhase.length,
2706
- traceFaultInjected,
2707
- restoredGlobalsWithPending: failedBytes?.includes(Buffer.from('SETUP_CLI_ENV_RESTORED_WITH_PENDING')) ?? false,
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
- }
2736
- if (prepared !== undefined) {
2737
- // Parent retains original validated bindings even when the child receives the mismatch fault.
2738
- for (const file of prepared.files)
2739
- assert.equal(digestBytes(readFileSync(file.path)), file.digest);
2740
- assert.equal(readFileSync(join(prepared.base, 'installs'), 'utf8'), 'x');
2741
- preparedCliClosure(prepared.input);
2742
- if (scenario !== 'budget' || failure !== undefined)
2743
- assert.equal(existsSync(join(prepared.input.repoRoot, '.git/ai-delivery/runtime-admission.json')), false);
2744
- }
2745
- rmSync(root, { recursive: true, force: true });
2746
- assert.equal(existsSync(root), false, 'Owned CLI case root was not removed');
2747
- return {
2748
- phases: lastPhase,
2749
- completedUnits,
2750
- nativeIdle: idle,
2751
- cancelledPhase,
2752
- failure,
2753
- rootRemoved: true,
2754
- residualInstaller,
2755
- identities: [...identities.values()],
2756
- installerFailureReported: failedBytes?.includes(Buffer.from('exit 7')) ?? false,
2757
- handoffMismatchReported: failedBytes?.includes(Buffer.from('Prepared CLI stage identity mismatch')) ?? false,
2758
- };
2759
- }
2760
- test(stageAdmitCase, async () => {
2761
- const tracePath = process.env.AI_DELIVERY_STAGE_ADMIT_CHILD;
2762
- if (tracePath === undefined) {
2763
- const result = await observeStageAdmitCase();
2764
- assert.equal(result.failure, undefined);
2765
- return;
2766
- }
2767
- const scenario = process.env.AI_DELIVERY_STAGE_ADMIT_SCENARIO;
2768
- const traceFault = process.env.AI_DELIVERY_STAGE_ADMIT_TRACE_FAULT;
2769
- const phases = [];
2770
- let activeCommands = 0;
2771
- let traceFailure;
2772
- const phase = (name, event, unit) => {
2773
- if (traceFailure !== undefined)
2774
- return;
2775
- try {
2776
- assert.ok(phases.length < 64, 'CLI phase count exceeded its bound');
2777
- phases.push({ phase: name, event, atMs: performance.now(), ...(unit === undefined ? {} : { unit }) });
2778
- if (traceFault === 'write' && name === 'import:runtime:stage' && event === 'end') {
2779
- assert.ok(activeCommands > 0, 'Trace write fault requires an actually pending CLI command');
2780
- process.stderr.write('SETUP_CLI_TRACE_WRITE_FAULT_WITH_PENDING\n');
2781
- rmSync(tracePath);
2782
- mkdirSync(tracePath);
2783
- }
2784
- atomicJson.writePrivateJsonFileAtomically(tracePath, phases);
2785
- }
2786
- catch (error) {
2787
- traceFailure = error instanceof Error ? error : new Error(String(error));
2788
- try {
2789
- process.stderr.write('SETUP_CLI_TRACE_FAILURE\n');
2790
- }
2791
- catch {
2792
- /* The parent also validates the retained trace. */
2793
- }
2794
- }
2795
- };
2796
- phase('preparation', 'start');
2797
- if (scenario === 'budget')
2798
- await new Promise((resolve) => setTimeout(resolve, 12_000));
2799
- const preparedRoot = process.env.AI_DELIVERY_CLI_PREPARED_ROOT;
2800
- const prepared = preparedRoot ? readPreparedCli(preparedRoot) : undefined;
2801
- const ownedFixture = prepared === undefined ? await fixture() : undefined;
2802
- const f = ownedFixture ?? {
2803
- base: prepared.base,
2804
- root: prepared.input.repoRoot,
2805
- input: prepared.input,
2806
- counter: join(prepared.base, 'installs'),
2807
- marker: join(prepared.base, 'installer-running'),
2808
- };
2809
- const previousPath = process.env.PATH;
2810
- if (prepared !== undefined) {
2811
- vi.stubEnv('AI_DELIVERY_CONFIG', prepared.configPath);
2812
- process.env.PATH = `${prepared.npmBin}:${previousPath ?? ''}`;
2813
- assert.equal((await loadDeliveryConfig(f.root)).configDigest, f.input.expectedConfigDigest);
2814
- assert.equal(actors.author, prepared.author);
2815
- assert.equal(actors.reviewer, prepared.reviewer);
2816
- assert.equal(existsSync(join(f.root, '.git/ai-delivery/runtime-admission.json')), false);
2817
- preparedCliClosure(f.input);
2818
- }
2819
- if (scenario === 'unfinished') {
2820
- writeFileSync(join(f.base, 'wait'), '');
2821
- writeFileSync(join(f.base, 'wait-noise'), '');
2822
- }
2823
- if (scenario === 'installer-failure')
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);
2838
- phase('preparation', 'end');
2839
- const argv = process.argv;
2840
- const exitCode = process.exitCode;
2841
- const stdout = vi.spyOn(process.stdout, 'write');
2842
- const pending = [];
2843
- const restoreObservations = [];
2844
- const restoreEnvs = vi.unstubAllEnvs.bind(vi);
2845
- const environmentProbe = traceFault === 'write'
2846
- ? vi.spyOn(vi, 'unstubAllEnvs').mockImplementation(() => {
2847
- if (activeCommands > 0)
2848
- process.stderr.write('SETUP_CLI_ENV_RESTORED_WITH_PENDING\n');
2849
- return restoreEnvs();
2850
- })
2851
- : undefined;
2852
- try {
2853
- const runCli = async (args) => {
2854
- const begin = stdout.mock.calls.length;
2855
- let settled = false;
2856
- process.argv = [
2857
- process.execPath,
2858
- join(process.cwd(), 'dist/cli.js'),
2859
- '--repo-root',
2860
- f.root,
2861
- '--identity',
2862
- 'host-author',
2863
- ...args,
2864
- ];
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());
2938
- if (args[0] === 'runtime:admit') {
2939
- const clientsModule = await import('./github/client.js');
2940
- const create = clientsModule.createDeliveryGitHubClients;
2941
- let authorChecks = 0;
2942
- const clients = vi
2943
- .spyOn(clientsModule, 'createDeliveryGitHubClients')
2944
- .mockImplementation(async (...input) => {
2945
- const client = await create(...input);
2946
- const authenticatedAuthor = client.authenticatedAuthor;
2947
- if (authenticatedAuthor !== undefined) {
2948
- client.authenticatedAuthor = async (...request) => {
2949
- const name = `admit:author:${++authorChecks}${actors.pauseAuthor ? ':delayed' : ''}`;
2950
- phase(name, 'start');
2951
- try {
2952
- assert.ok(scenario !== 'budget' || authorChecks === 1 || !actors.pauseAuthor, 'Budget fixture repeated its deliberate HTTP delay at another required authority check');
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
- });
2963
- }
2964
- finally {
2965
- // The budget regression needs one four-second response, not one per required recheck.
2966
- if (scenario === 'budget')
2967
- actors.pauseAuthor = false;
2968
- phase(name, 'end');
2969
- }
2970
- };
2971
- }
2972
- return client;
2973
- });
2974
- restoreObservations.push(() => clients.mockRestore());
2975
- }
2976
- const { Command } = await import('commander');
2977
- const descriptor = Object.getOwnPropertyDescriptor(Command.prototype, 'parseAsync');
2978
- assert.equal(typeof descriptor?.value, 'function', 'Commander parse operation is unavailable');
2979
- const parse = descriptor.value;
2980
- let command;
2981
- let observation;
2982
- const observe = vi.spyOn(Command.prototype, 'parseAsync').mockImplementation(function (...input) {
2983
- phase(args[0], 'start');
2984
- if (traceFailure !== undefined)
2985
- throw traceFailure;
2986
- const operation = parse.apply(this, input);
2987
- activeCommands++;
2988
- command = operation;
2989
- observation = operation.then(() => {
2990
- activeCommands--;
2991
- settled = true;
2992
- phase(args[0], 'settled');
2993
- }, () => {
2994
- activeCommands--;
2995
- settled = true;
2996
- phase(args[0], 'settled');
2997
- });
2998
- pending.push(operation, observation);
2999
- // Retain observer failures for the explicit join without an interim unhandled rejection.
3000
- void observation.catch(() => { });
3001
- return operation;
3002
- });
3003
- try {
3004
- phase(`import:${args[0]}`, 'start');
3005
- if (traceFailure !== undefined)
3006
- throw traceFailure;
3007
- await import('./cli.js');
3008
- phase(`import:${args[0]}`, 'end');
3009
- }
3010
- finally {
3011
- observe.mockRestore();
3012
- }
3013
- assert.ok(command, 'CLI import did not start its actual parse operation');
3014
- await command;
3015
- await observation;
3016
- if (traceFailure !== undefined)
3017
- throw traceFailure;
3018
- for (let i = 0; i < 300; i++) {
3019
- const output = stdout.mock.calls
3020
- .slice(begin)
3021
- .map(([bytes]) => String(bytes))
3022
- .find((bytes) => bytes.startsWith('{'));
3023
- if (output) {
3024
- phase(`return:${args[0]}`, settled ? 'end' : 'pending');
3025
- return JSON.parse(output);
3026
- }
3027
- await new Promise((resolve) => setTimeout(resolve, 20));
3028
- }
3029
- phase(`return:${args[0]}`, settled ? 'end' : 'pending');
3030
- throw new Error('CLI completion output unavailable');
3031
- };
3032
- const common = [
3033
- '--source-commit',
3034
- f.input.expectedSourceCommit,
3035
- '--config-digest',
3036
- f.input.expectedConfigDigest,
3037
- '--runtime-directory',
3038
- f.input.runtimeDirectory,
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
- }
3045
- const staged = await runCli([
3046
- 'runtime:stage',
3047
- '--authorize-stage',
3048
- '--archive',
3049
- f.input.archivePath,
3050
- '--archive-sha256',
3051
- f.input.expectedArchiveSha256,
3052
- '--package-version',
3053
- f.input.packageVersion,
3054
- ...common,
3055
- ]);
3056
- phase('assertions:stageId', 'start');
3057
- assert.equal(typeof staged.stageId, 'string');
3058
- if (prepared !== undefined) {
3059
- assert.equal(staged.reused, true, 'the actual CLI must reuse the completed prepared stage');
3060
- assert.equal(staged.stageId, prepared.stageId);
3061
- assert.equal(readFileSync(f.counter, 'utf8'), 'x');
3062
- for (const file of prepared.files)
3063
- assert.equal(digestBytes(readFileSync(file.path)), file.digest);
3064
- }
3065
- phase('assertions:stageId', 'end');
3066
- if (scenario === 'progress')
3067
- actors.pauseAuthor = false;
3068
- const authorCallsBeforeAdmission = actors.authorCalls;
3069
- if (scenario === 'budget')
3070
- actors.pauseAuthor = true;
3071
- const admitted = await runCli([
3072
- 'runtime:admit',
3073
- '--authorize-admit',
3074
- '--stage-id',
3075
- String(staged.stageId),
3076
- '--expected-absent',
3077
- ...common,
3078
- ]);
3079
- phase('assertions', 'start');
3080
- assert.equal(actors.authorCalls - authorCallsBeforeAdmission, 3, 'Admission must authenticate at its initial, locked and final controller checks');
3081
- assert.equal(admitted.admission.sourceCommit, f.input.expectedSourceCommit);
3082
- assert.equal(readFileSync(f.counter, 'utf8'), 'x');
3083
- assert.equal(process.exitCode, exitCode);
3084
- phase('assertions', 'end');
3085
- }
3086
- finally {
3087
- phase('drain', 'start');
3088
- await Promise.allSettled(pending);
3089
- for (const restore of restoreObservations)
3090
- restore();
3091
- environmentProbe?.mockRestore();
3092
- phase('drain', 'end');
3093
- phase('cleanup', 'start');
3094
- stdout.mockRestore();
3095
- process.argv = argv;
3096
- process.exitCode = exitCode;
3097
- // The existing parent owns final artifact corroboration and disposal after native quiescence.
3098
- if (ownedFixture !== undefined)
3099
- ownedFixture.cleanup(true);
3100
- else
3101
- process.env.PATH = previousPath;
3102
- phase('cleanup', 'end');
3103
- }
3104
- if (traceFailure !== undefined)
3105
- throw traceFailure;
3106
- },
3107
- // The parent supervises bootstrap, each overlapping phase, and native drain independently.
3108
- // Cancellation may terminate this isolated process; it never proves JavaScript settlement.
3109
- 0);
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 () => {
3120
- const result = await observeStageAdmitCase('budget');
3121
- const authorChecks = result.phases.filter((entry) => entry.phase.startsWith('admit:author:') && entry.event === 'start');
3122
- assert.equal(authorChecks.length, 3, 'All three admission authority checks must execute');
3123
- 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');
3124
- assert.equal(result.failure, undefined, 'A CLI operation failed; inspect the retained phase and ownership evidence');
3125
- assert.ok(result.phases.at(-1).atMs - result.phases[0].atMs > 15_000);
3126
- for (const entry of result.phases.filter((entry) => entry.event === 'start')) {
3127
- const end = result.phases.find((candidate) => candidate.phase === entry.phase && ['end', 'settled'].includes(candidate.event));
3128
- assert.ok(end !== undefined, `${entry.phase} did not settle`);
3129
- }
3130
- });
3131
- test('CLI prepared handoff rejects a mismatched stage identity without reinstall or admission', async () => {
3132
- const result = await observeStageAdmitCase('handoff-mismatch');
3133
- assert.equal(result.handoffMismatchReported, true, 'the actual child must refuse its mismatched prepared stage');
3134
- assert.ok(result.failure !== undefined && result.nativeIdle && result.rootRemoved);
3135
- assert.equal(result.phases.some((entry) => entry.phase === 'runtime:admit'), false);
3136
- });
3137
- for (const fault of ['failure', 'cancel']) {
3138
- test(`CLI preparation ${fault} retains owned evidence through native drain`, async () => {
3139
- const previousPath = process.env.PATH;
3140
- let received;
3141
- try {
3142
- await observeStageAdmitCase(`preparation-${fault}`);
3143
- }
3144
- catch (error) {
3145
- received = error;
3146
- }
3147
- assert.ok(received instanceof Error, 'failed preparation must retain its owned root for recovery');
3148
- const error = received;
3149
- assert.equal(error.nativeIdle, true);
3150
- assert.ok(error.cleanupState !== undefined);
3151
- assert.equal(error.restoredGlobalsWithPending, false);
3152
- assert.equal(realpathSync(error.root), error.root);
3153
- assert.equal(dirname(error.root), realpathSync(tmpdir()));
3154
- assert.match(error.root, /ai-delivery-cli-case-/u);
3155
- const ownership = JSON.parse(privateFiles.assertPrivateFile(join(error.root, 'ownership.json')).toString('utf8'));
3156
- assert.equal(ownership.idle, true);
3157
- assert.equal(ownership.owned.rootPid, error.cleanupState.rootPid);
3158
- assert.equal(ownership.owned.rootIdentity, error.cleanupState.rootIdentity);
3159
- const { confirmOwnedCleanup } = await import('./verification.js');
3160
- await confirmOwnedCleanup(error.cleanupState);
3161
- try {
3162
- const bases = readdirSync(error.root).filter((name) => name.startsWith('ai-delivery-setup-'));
3163
- assert.equal(bases.length, 1);
3164
- const base = join(error.root, bases[0]);
3165
- assert.equal(readFileSync(join(base, 'unrelated-preparation'), 'utf8'), 'unrelated');
3166
- assert.equal(readFileSync(join(base, 'installs'), 'utf8'), 'x');
3167
- assert.equal(existsSync(join(base, 'consumer/.git/ai-delivery/runtime-admission.json')), false);
3168
- if (fault === 'cancel') {
3169
- assert.equal(error.residualInstaller?.counter, 'x');
3170
- assert.ok(error.cleanupState.tracked.has(error.residualInstaller.pid));
3171
- }
3172
- assert.equal(process.env.PATH, previousPath);
3173
- }
3174
- finally {
3175
- rmSync(error.root, { recursive: true, force: true });
3176
- }
3177
- assert.equal(existsSync(error.root), false);
3178
- process.stdout.write('SETUP_CLI_PREPARATION_RECOVERY ' +
3179
- JSON.stringify({ fault, root: error.root, quiescenceRechecked: true, removed: true }) +
3180
- '\n');
3181
- });
3182
- }
3183
- test('CLI stage/admit keeps an unfinished real installer owned until native quiescence', async () => {
3184
- const result = await observeStageAdmitCase('unfinished');
3185
- assert.ok(result.failure !== undefined && result.nativeIdle && result.rootRemoved);
3186
- assert.equal(result.residualInstaller?.counter, 'x', 'A real installer must execute exactly once');
3187
- assert.ok(result.identities.some((member) => member.pid === result.residualInstaller?.pid), 'Installer birth identity was not observed by the native supervisor');
3188
- assert.equal(result.phases.some((entry) => entry.event === 'pending'), false, 'CLI caller relinquished an unfinished command');
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);
3192
- assert.equal(result.phases.some((entry) => entry.phase === 'cleanup'), false, 'Child cleaned a fixture with active work');
3193
- });
3194
- test('CLI stage/admit joins a failed real installer before restoring its fixture', async () => {
3195
- const result = await observeStageAdmitCase('installer-failure');
3196
- assert.ok(result.failure !== undefined && result.nativeIdle && result.rootRemoved);
3197
- assert.equal(result.installerFailureReported, true, 'The real installer failure was not reported');
3198
- const settled = result.phases.findIndex((entry) => entry.phase === 'runtime:stage' && entry.event === 'settled');
3199
- const cleanup = result.phases.findIndex((entry) => entry.phase === 'cleanup' && entry.event === 'start');
3200
- assert.ok(settled >= 0 && cleanup > settled, 'Failure cleanup preceded actual command settlement');
3201
- assert.equal(result.phases.some((entry) => entry.phase === 'runtime:admit'), false);
3202
- });
3203
- test('CLI stage/admit keeps a stalled admission response owned until native quiescence', async () => {
3204
- const result = await observeStageAdmitCase('admission-stall');
3205
- assert.ok(result.failure !== undefined && result.nativeIdle && result.rootRemoved);
3206
- assert.equal(result.cancelledPhase, 'runtime:admit');
3207
- assert.ok(result.phases.some((entry) => entry.phase === 'runtime:stage' && entry.event === 'settled'));
3208
- assert.ok(result.phases.some((entry) => entry.phase === 'admit:author:1' && entry.event === 'start'));
3209
- assert.equal(result.phases.some((entry) => entry.phase === 'cleanup' ||
3210
- entry.phase === 'return:runtime:admit' ||
3211
- (entry.phase === 'admit:author:1' && entry.event === 'end')), false, 'The stalled HTTP response must keep the original command pending until native cancellation');
3212
- });
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) => {
3223
- let failure;
3224
- sharedOutputRead.unboundedReads = 0;
3225
- try {
3226
- try {
3227
- await observeStageAdmitCase('unfinished', fault);
3228
- }
3229
- catch (error) {
3230
- assert.ok(error instanceof Error);
3231
- failure = error;
3232
- }
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);
3236
- assert.equal(failure.nativeIdle, true);
3237
- assert.equal(failure.traceFaultInjected, true, 'The real pending CLI trace fault did not execute');
3238
- assert.equal(existsSync(failure.root), true, 'Untrusted phase evidence was discarded before recovery');
3239
- assert.ok(failure.retainedPhaseCount <= 64, 'Invalid final trace replaced validated bounded evidence');
3240
- assert.equal(sharedOutputRead.unboundedReads, 0, 'Failure handling attempted an unbounded final trace read');
3241
- assert.equal(failure.restoredGlobalsWithPending, false, 'Trace failure bypassed the actual command join');
3242
- if (fault !== 'write')
3243
- assert.equal(failure.residualInstaller?.counter, 'x');
3244
- }
3245
- finally {
3246
- sharedOutputRead.path = '';
3247
- if (failure?.nativeIdle && failure.cleanupState !== undefined) {
3248
- const recorded = JSON.parse(privateFiles.assertPrivateFile(join(failure.root, 'ownership.json'), { maxBytes: 256 * 1024 }).toString('utf8'));
3249
- assert.equal(recorded.idle, true);
3250
- assert.equal(recorded.owned.rootPid, failure.cleanupState.rootPid);
3251
- const { confirmOwnedCleanup } = await import('./verification.js');
3252
- await confirmOwnedCleanup(failure.cleanupState);
3253
- rmSync(failure.root, { recursive: true, force: true });
3254
- assert.equal(existsSync(failure.root), false);
3255
- process.stdout.write(`SETUP_CLI_TRACE_RECOVERY ${JSON.stringify({ fault, root: failure.root, quiescenceRechecked: true, removed: true })}\n`);
3256
- }
3257
- sharedOutputRead.unboundedReads = 0;
3258
- }
3259
- });
3260
- 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 () => {
3261
- const realPath = process.env.PATH;
3262
- const api = await producer();
3263
- const f = await fixture();
3264
- try {
3265
- process.env.PATH = realPath;
3266
- const input = {
3267
- ...f.input,
3268
- archivePath: process.env.AI_DELIVERY_REAL_PACKAGE_ARCHIVE,
3269
- packageVersion: '0.3.4',
3270
- expectedArchiveSha256: 'sha256:4e5171a4d398dcc486852f08e58f2ef4267765e6f33a34a3ecd5e1ad01830e6d',
3271
- };
3272
- const stage = await api.stageRuntime(input);
3273
- assert.equal(execFileSync(process.execPath, [stage.admission.cliPath, '--version'], { encoding: 'utf8' }).trim(), '0.3.4');
3274
- assert.equal(stage.admission.capability.mcp, 2);
3275
- assert.equal(existsSync(f.counter), false);
3276
- await api.admitRuntime(admitInput(input, stage.stageId));
3277
- const installedValidatorUrl = new URL(`file://${join(dirname(stage.admission.cliPath), 'services/deliveryAdmission.js')}`).href;
3278
- const installed = (await import(installedValidatorUrl));
3279
- const admitted = await installed.assertDeliveryRuntimeAdmitted({
3280
- repoRoot: f.root,
3281
- runtimeEntryPath: stage.admission.cliPath,
3282
- configuration: await loadDeliveryConfig(f.root),
3283
- });
3284
- assert.equal(admitted.admissionId, stage.admission.admissionId);
3285
- assert.equal((await api.stageRuntime(input)).reused, true);
3286
- console.log('REAL_INSTALLER_QUALIFICATION_RECEIPT', JSON.stringify({
3287
- archiveSha256: input.expectedArchiveSha256,
3288
- packageVersion: admitted.packageVersion,
3289
- packageDistSha256: admitted.packageDistSha256,
3290
- cliSha256: admitted.cliSha256,
3291
- pluginManifestSha256: admitted.pluginManifestSha256,
3292
- installedValidator: true,
3293
- installer: 'real npm production dependencies; ignore-scripts',
3294
- httpBoundary: 'synthetic GitHub authentication/discovery',
3295
- temporaryConsumer: true,
3296
- hostActivated: false,
3297
- sharedAdmissionWritten: false,
3298
- }));
3299
- }
3300
- finally {
3301
- f.cleanup();
3302
- }
3303
- });
3304
- test('live routing and reviewer access drift cannot replace an already admitted stage', async () => {
3305
- const api = await producer();
3306
- const f = await fixture();
3307
- try {
3308
- const stage = await api.stageRuntime(f.input);
3309
- await api.admitRuntime(admitInput(f.input, stage.stageId));
3310
- const path = join(f.root, '.git/ai-delivery/runtime-admission.json');
3311
- const before = readFileSync(path);
3312
- actors.projectId = 'PROJECT-2';
3313
- await assert.rejects(api.admitRuntime(admitInput(f.input, stage.stageId)), /config digest/u);
3314
- const changed = { ...f.input, expectedConfigDigest: (await loadDeliveryConfig(f.root)).configDigest };
3315
- await assert.rejects(api.admitRuntime(admitInput(changed, stage.stageId)), /configuration/u);
3316
- actors.projectId = 'PROJECT-1';
3317
- actors.access = false;
3318
- await assert.rejects(api.admitRuntime(admitInput(f.input, stage.stageId)), /cannot read/u);
3319
- actors.access = true;
3320
- await assert.rejects(api.admitRuntime({ ...admitInput(f.input, stage.stageId), authority: '' }), /authority/u);
3321
- await assert.rejects(api.stageRuntime({ ...f.input, packageVersion: '0.3.4' }), /incompatible/u);
3322
- assert.deepEqual(readFileSync(path), before);
3323
- assert.equal(readFileSync(f.counter, 'utf8'), 'x');
3324
- }
3325
- finally {
3326
- f.cleanup();
3327
- }
3328
- });
3329
- //# sourceMappingURL=setup.test.js.map