@aviaratech/ai-delivery 0.3.34 → 0.3.36

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 +57 -506
  3. package/dist/agent.d.ts +0 -2
  4. package/dist/agent.js +76 -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 +1746 -0
  9. package/dist/boardReconcile.test.js.map +7 -0
  10. package/dist/build.test.js +130 -0
  11. package/dist/build.test.js.map +7 -0
  12. package/dist/callerErrors.test.js +105 -0
  13. package/dist/callerErrors.test.js.map +7 -0
  14. package/dist/cli.js +406 -485
  15. package/dist/cli.js.map +7 -1
  16. package/dist/cliResult.d.ts +2 -2
  17. package/dist/cliResult.js +42 -25
  18. package/dist/cliResult.js.map +7 -1
  19. package/dist/cliResult.test.js +434 -297
  20. package/dist/cliResult.test.js.map +7 -1
  21. package/dist/config/deliveryConfig.d.ts +320 -14
  22. package/dist/config/deliveryConfig.js +472 -385
  23. package/dist/config/deliveryConfig.js.map +7 -1
  24. package/dist/config/deliveryConfig.test.js +775 -584
  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 -477
  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.d.ts +1 -0
  53. package/dist/deliveryBoard.test.js +649 -0
  54. package/dist/deliveryBoard.test.js.map +7 -0
  55. package/dist/deliveryHealth.test.js +179 -155
  56. package/dist/deliveryHealth.test.js.map +7 -1
  57. package/dist/dependencyCompatibility.test.js +154 -140
  58. package/dist/dependencyCompatibility.test.js.map +7 -1
  59. package/dist/directoryIndependent.test.js +417 -383
  60. package/dist/directoryIndependent.test.js.map +7 -1
  61. package/dist/dispatch.d.ts +17 -12
  62. package/dist/dispatch.js +330 -322
  63. package/dist/dispatch.js.map +7 -1
  64. package/dist/errors.d.ts +16 -3
  65. package/dist/errors.js +104 -82
  66. package/dist/errors.js.map +7 -1
  67. package/dist/fixtures/deliveryBoardReplay.d.ts +56 -0
  68. package/dist/fixtures/deliveryBoardReplay.js +617 -0
  69. package/dist/fixtures/deliveryBoardReplay.js.map +7 -0
  70. package/dist/fixtures/discovery.d.ts +59 -19
  71. package/dist/fixtures/discovery.js +96 -90
  72. package/dist/fixtures/discovery.js.map +7 -1
  73. package/dist/fixtures/inertEntrypointChild.js +57 -56
  74. package/dist/fixtures/inertEntrypointChild.js.map +7 -1
  75. package/dist/fixtures/inertEntrypoints.d.ts +1 -1
  76. package/dist/fixtures/inertEntrypoints.js +321 -276
  77. package/dist/fixtures/inertEntrypoints.js.map +7 -1
  78. package/dist/fixtures/inertTarget.d.ts +78 -7
  79. package/dist/fixtures/inertTarget.js +769 -691
  80. package/dist/fixtures/inertTarget.js.map +7 -1
  81. package/dist/fixtures/issue63.d.ts +4 -3
  82. package/dist/fixtures/issue63.js +260 -274
  83. package/dist/fixtures/issue63.js.map +7 -1
  84. package/dist/fixtures/issueProjectItems.d.ts +20 -0
  85. package/dist/fixtures/issueProjectItems.js +15 -0
  86. package/dist/fixtures/issueProjectItems.js.map +7 -0
  87. package/dist/fixtures/readView.d.ts +120 -0
  88. package/dist/fixtures/readView.js +172 -0
  89. package/dist/fixtures/readView.js.map +7 -0
  90. package/dist/fixtures/recordedGitHubFlows.d.ts +120 -0
  91. package/dist/fixtures/recordedGitHubFlows.js +109 -0
  92. package/dist/fixtures/recordedGitHubFlows.js.map +7 -0
  93. package/dist/genericCompatibility.test.js +64 -55
  94. package/dist/genericCompatibility.test.js.map +7 -1
  95. package/dist/git.js +73 -67
  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 +44 -51
  104. package/dist/github/commandIdentityPolicy.js.map +7 -1
  105. package/dist/github/discovery.d.ts +3 -0
  106. package/dist/github/discovery.js +197 -201
  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 +53 -1
  121. package/dist/github/projectDelivery.js +623 -460
  122. package/dist/github/projectDelivery.js.map +7 -1
  123. package/dist/github/relationships.d.ts +5 -2
  124. package/dist/github/relationships.js +434 -333
  125. package/dist/github/relationships.js.map +7 -1
  126. package/dist/github/repo.d.ts +1 -0
  127. package/dist/github/repo.js +123 -96
  128. package/dist/github/repo.js.map +7 -1
  129. package/dist/index.js +3 -3
  130. package/dist/index.js.map +7 -1
  131. package/dist/issue.d.ts +103 -7
  132. package/dist/issue.js +2104 -1547
  133. package/dist/issue.js.map +7 -1
  134. package/dist/issue63History.test.js +40 -42
  135. package/dist/issue63History.test.js.map +7 -1
  136. package/dist/issue63Routes.test.js +154 -143
  137. package/dist/issue63Routes.test.js.map +7 -1
  138. package/dist/issueBatchUpdate.test.js +1004 -683
  139. package/dist/issueBatchUpdate.test.js.map +7 -1
  140. package/dist/issueBlockerGuard.test.js +262 -226
  141. package/dist/issueBlockerGuard.test.js.map +7 -1
  142. package/dist/issueContract.d.ts +23 -4
  143. package/dist/issueContract.js +416 -395
  144. package/dist/issueContract.js.map +7 -1
  145. package/dist/issueContract.test.d.ts +4 -3
  146. package/dist/issueContract.test.js +358 -321
  147. package/dist/issueContract.test.js.map +7 -1
  148. package/dist/issueDates.test.js +235 -233
  149. package/dist/issueDates.test.js.map +7 -1
  150. package/dist/issueInfoReadback.test.js +304 -190
  151. package/dist/issueInfoReadback.test.js.map +7 -1
  152. package/dist/issueIntake.test.js +1945 -1732
  153. package/dist/issueIntake.test.js.map +7 -1
  154. package/dist/issueJournal.d.ts +40 -19
  155. package/dist/issueJournal.js +229 -138
  156. package/dist/issueJournal.js.map +7 -1
  157. package/dist/issueJournal.test.js +605 -422
  158. package/dist/issueJournal.test.js.map +7 -1
  159. package/dist/issueRollup.test.d.ts +1 -0
  160. package/dist/issueRollup.test.js +476 -0
  161. package/dist/issueRollup.test.js.map +7 -0
  162. package/dist/issueTracking.test.js +1088 -593
  163. package/dist/issueTracking.test.js.map +7 -1
  164. package/dist/issueWriteRecovery.test.d.ts +1 -0
  165. package/dist/issueWriteRecovery.test.js +260 -0
  166. package/dist/issueWriteRecovery.test.js.map +7 -0
  167. package/dist/lifecycle.test.js +112 -441
  168. package/dist/lifecycle.test.js.map +7 -1
  169. package/dist/logger.js +80 -74
  170. package/dist/logger.js.map +7 -1
  171. package/dist/mcp/index.js +116 -90
  172. package/dist/mcp/index.js.map +7 -1
  173. package/dist/mcp/tools.d.ts +790 -220
  174. package/dist/mcp/tools.js +267 -333
  175. package/dist/mcp/tools.js.map +7 -1
  176. package/dist/pluginAuthProbe.js +63 -52
  177. package/dist/pluginAuthProbe.js.map +7 -1
  178. package/dist/pluginAuthProbe.test.js +85 -62
  179. package/dist/pluginAuthProbe.test.js.map +7 -1
  180. package/dist/pluginCredentials.test.js +282 -259
  181. package/dist/pluginCredentials.test.js.map +7 -1
  182. package/dist/pluginDoctor.test.js +653 -588
  183. package/dist/pluginDoctor.test.js.map +7 -1
  184. package/dist/pluginInstaller.d.ts +7 -5
  185. package/dist/pluginInstaller.js +1173 -1231
  186. package/dist/pluginInstaller.js.map +7 -1
  187. package/dist/pluginInstaller.test.js +1822 -1283
  188. package/dist/pluginInstaller.test.js.map +7 -1
  189. package/dist/pluginPackaging.test.js +485 -305
  190. package/dist/pluginPackaging.test.js.map +7 -1
  191. package/dist/pr.d.ts +132 -94
  192. package/dist/pr.js +1521 -1323
  193. package/dist/pr.js.map +7 -1
  194. package/dist/pr.test.js +1678 -632
  195. package/dist/pr.test.js.map +7 -1
  196. package/dist/prAssociation.test.js +2419 -1788
  197. package/dist/prAssociation.test.js.map +7 -1
  198. package/dist/prDispatch.test.js +150 -89
  199. package/dist/prDispatch.test.js.map +7 -1
  200. package/dist/readView.d.ts +183 -0
  201. package/dist/readView.js +217 -0
  202. package/dist/readView.js.map +7 -0
  203. package/dist/readView.test.d.ts +1 -0
  204. package/dist/readView.test.js +119 -0
  205. package/dist/readView.test.js.map +7 -0
  206. package/dist/releaseReconciliation.test.js +267 -288
  207. package/dist/releaseReconciliation.test.js.map +7 -1
  208. package/dist/releaseWorkflow.test.js +2493 -422
  209. package/dist/releaseWorkflow.test.js.map +7 -1
  210. package/dist/review.d.ts +738 -2
  211. package/dist/review.js +601 -348
  212. package/dist/review.js.map +7 -1
  213. package/dist/review.test.js +1218 -812
  214. package/dist/review.test.js.map +7 -1
  215. package/dist/reviewSubmit.test.d.ts +1 -0
  216. package/dist/reviewSubmit.test.js +747 -0
  217. package/dist/reviewSubmit.test.js.map +7 -0
  218. package/dist/services/agentReadinessService.js +42 -37
  219. package/dist/services/agentReadinessService.js.map +7 -1
  220. package/dist/services/blockerGuardService.js +188 -188
  221. package/dist/services/blockerGuardService.js.map +7 -1
  222. package/dist/services/boardReconcileService.d.ts +1204 -0
  223. package/dist/services/boardReconcileService.js +1445 -0
  224. package/dist/services/boardReconcileService.js.map +7 -0
  225. package/dist/services/deliveryAdmission.d.ts +2 -0
  226. package/dist/services/deliveryAdmission.js +129 -152
  227. package/dist/services/deliveryAdmission.js.map +7 -1
  228. package/dist/services/deliveryHealthService.js +197 -199
  229. package/dist/services/deliveryHealthService.js.map +7 -1
  230. package/dist/services/legacyIssueMigration.js +263 -277
  231. package/dist/services/legacyIssueMigration.js.map +7 -1
  232. package/dist/services/worktreeRegistry.d.ts +27 -119
  233. package/dist/services/worktreeRegistry.js +765 -1182
  234. package/dist/services/worktreeRegistry.js.map +7 -1
  235. package/dist/stagedChecks.test.js +396 -194
  236. package/dist/stagedChecks.test.js.map +7 -1
  237. package/dist/start.test.js +99 -95
  238. package/dist/start.test.js.map +7 -1
  239. package/dist/stdoutRegression.test.js +354 -350
  240. package/dist/stdoutRegression.test.js.map +7 -1
  241. package/dist/targetPolicyDiscovery.test.js +141 -143
  242. package/dist/targetPolicyDiscovery.test.js.map +7 -1
  243. package/dist/targetPolicyEntrypoints.test.js +308 -269
  244. package/dist/targetPolicyEntrypoints.test.js.map +7 -1
  245. package/dist/targetPolicyLocal.test.js +580 -1051
  246. package/dist/targetPolicyLocal.test.js.map +7 -1
  247. package/dist/targetPolicyRoutes.test.js +305 -281
  248. package/dist/targetPolicyRoutes.test.js.map +7 -1
  249. package/dist/targetRepositoryExecution.test.d.ts +1 -0
  250. package/dist/targetRepositoryExecution.test.js +463 -0
  251. package/dist/targetRepositoryExecution.test.js.map +7 -0
  252. package/dist/terminalMessages.js +41 -35
  253. package/dist/terminalMessages.js.map +7 -1
  254. package/dist/toolOutput.d.ts +2 -0
  255. package/dist/toolOutput.js +36 -0
  256. package/dist/toolOutput.js.map +7 -0
  257. package/dist/toolOutput.test.d.ts +1 -0
  258. package/dist/toolOutput.test.js +240 -0
  259. package/dist/toolOutput.test.js.map +7 -0
  260. package/dist/utils/atomicJson.js +84 -76
  261. package/dist/utils/atomicJson.js.map +7 -1
  262. package/dist/utils/filesystem.js +15 -18
  263. package/dist/utils/filesystem.js.map +7 -1
  264. package/dist/utils/lockfile.js +68 -71
  265. package/dist/utils/lockfile.js.map +7 -1
  266. package/dist/verification.d.ts +1 -19
  267. package/dist/verification.js +1020 -1929
  268. package/dist/verification.js.map +7 -1
  269. package/dist/verificationGate.test.js +127 -117
  270. package/dist/verificationGate.test.js.map +7 -1
  271. package/dist/version.d.ts +6 -0
  272. package/dist/version.js +24 -10
  273. package/dist/version.js.map +7 -1
  274. package/dist/worktree.d.ts +3 -15
  275. package/dist/worktree.js +97 -177
  276. package/dist/worktree.js.map +7 -1
  277. package/package.json +10 -8
  278. package/plugins/ai-delivery/.claude-plugin/plugin.json +2 -2
  279. package/plugins/ai-delivery/README.md +47 -156
  280. package/plugins/ai-delivery/plugin.json +1 -1
  281. package/plugins/ai-delivery/runtime/dist/THIRD-PARTY-NOTICES.md +261 -43
  282. package/plugins/ai-delivery/runtime/dist/cli.js +369 -125
  283. package/plugins/ai-delivery/runtime/package.json +1 -1
  284. package/plugins/ai-delivery/skills/intake-create/SKILL.md +14 -78
  285. package/plugins/ai-delivery/skills/pr-handoff/SKILL.md +35 -36
  286. package/plugins/ai-delivery/skills/worktree-lifecycle/SKILL.md +14 -15
  287. package/dist/investigationCompletion.test.js +0 -728
  288. package/dist/investigationCompletion.test.js.map +0 -1
  289. package/dist/setup.d.ts +0 -60
  290. package/dist/setup.js +0 -585
  291. package/dist/setup.js.map +0 -1
  292. package/dist/setup.test.js +0 -3058
  293. package/dist/setup.test.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 → boardReconcile.test.d.ts} +0 -0
  300. /package/dist/{setup.test.d.ts → build.test.d.ts} +0 -0
  301. /package/dist/{worktreeTransition.test.d.ts → callerErrors.test.d.ts} +0 -0
@@ -1,1114 +1,643 @@
1
- import assert from 'node:assert/strict';
2
- import { execFileSync } from 'node:child_process';
3
- import { existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync, } from 'node:fs';
4
- import { tmpdir } from 'node:os';
5
- import { dirname, join } from 'node:path';
6
- import { fileURLToPath } from 'node:url';
7
- import { afterEach, beforeEach, describe, test, vi } from 'vitest';
8
- import { loadDeliveryConfig } from './config/deliveryConfig.js';
9
- import { digestBytes, digestValue } from './delivery/common.js';
10
- import { investigationAcceptanceBody, investigationAuthorityBody } from './pr.js';
11
- import { readInvestigationPreparation } from './services/worktreeRegistry.js';
12
- import { WorktreeTransitionPlanSchema } from './worktreeTransition.js';
13
- import { fixtureGit, inertTarget } from './fixtures/inertTarget.js';
14
- const ASSERTED_MS = 15_000;
15
- const DRAIN_MS = 15_000;
16
- const GIT_MS = 5_000;
17
- const REQUEST_MS = 60_000; // Existing MCP initialize/callTool request bound.
18
- // Acquisition has seven 5s Git calls. Policy has three Git calls and one 5s
19
- // child. Archive is one 5s tar; local config retains its former 15s bound.
20
- // Closing is handler drain, not a new 60s request allowance.
21
- const stageSteps = [
22
- ['fixture', 7 * GIT_MS],
23
- ['archive', GIT_MS],
24
- ['config', ASSERTED_MS],
25
- ['policy', 4 * GIT_MS],
26
- ['connect', REQUEST_MS],
27
- ['runtime_stage', REQUEST_MS],
28
- ];
29
- const transitionSteps = [
30
- ['fixture', 7 * GIT_MS],
31
- ['worktree', GIT_MS],
32
- ['connect', REQUEST_MS],
33
- ['archive', GIT_MS],
34
- ['config', ASSERTED_MS],
35
- ['runtime_stage', REQUEST_MS],
36
- ['runtime_admit', REQUEST_MS],
37
- ['close', DRAIN_MS],
38
- ['reconnect', REQUEST_MS],
39
- ];
40
- // Each scoped case owns its fixture, signal bridge, operation promises and disposal.
41
- // A hook deadline can reject before the real MCP handler settles; join never releases
42
- // fixture globals until the existing active-handler drain completes.
1
+ import assert from "node:assert/strict";
2
+ import {
3
+ existsSync,
4
+ lstatSync,
5
+ mkdirSync,
6
+ mkdtempSync,
7
+ readFileSync,
8
+ realpathSync,
9
+ rmSync,
10
+ writeFileSync
11
+ } from "node:fs";
12
+ import { tmpdir } from "node:os";
13
+ import { join } from "node:path";
14
+ import { fileURLToPath } from "node:url";
15
+ import { test, vi } from "vitest";
16
+ import { loadDeliveryConfig } from "./config/deliveryConfig.js";
17
+ import { inertTarget } from "./fixtures/inertTarget.js";
18
+ const ASSERTED_MS = 15e3;
19
+ const DRAIN_MS = 15e3;
20
+ const GIT_MS = 5e3;
21
+ const REQUEST_MS = 6e4;
43
22
  function runtimeScope(steps = []) {
44
- const controller = new AbortController();
45
- const pending = new Set();
46
- const unlink = new Set();
47
- let cleanup;
48
- let disposal;
49
- let joined;
50
- const scope = {
51
- controller,
52
- signal: controller.signal,
53
- pending,
54
- phases: [],
55
- steps,
56
- nextStep: 0,
57
- fixture: undefined,
58
- forward(signal) {
59
- const abort = () => controller.abort(signal.reason);
60
- if (signal.aborted)
61
- abort();
62
- else {
63
- signal.addEventListener('abort', abort, { once: true });
64
- unlink.add(() => signal.removeEventListener('abort', abort));
65
- }
66
- },
67
- acquire(fixtureCancellation) {
68
- controller.signal.throwIfAborted();
69
- assert.equal(scope.fixture, undefined, 'Each case acquires exactly one fixture');
70
- // Expected fixture cancellation must not cancel the scope that still owns
71
- // the cancellation assertions and actual handler/disposal join.
72
- const signal = fixtureCancellation
73
- ? AbortSignal.any([controller.signal, fixtureCancellation])
74
- : controller.signal;
75
- scope.fixture = inertTarget(signal, (ownedCleanup) => {
76
- cleanup = ownedCleanup;
77
- });
78
- return scope.fixture;
79
- },
80
- join() {
81
- if (joined)
82
- return joined;
83
- // This disposal remains owned after a stalled observation. Transport
84
- // rejection or elapsed time never authorizes fixture/global removal.
85
- disposal ??= (async () => {
86
- controller.abort(new Error('Owned scoped runtime case finished'));
87
- try {
88
- while (pending.size)
89
- await Promise.allSettled(pending);
90
- await cleanup?.();
91
- }
92
- finally {
93
- for (const remove of unlink)
94
- remove();
95
- unlink.clear();
96
- }
97
- })();
98
- const phase = { name: 'drain', budgetMs: DRAIN_MS, started: performance.now(), outcome: 'running' };
99
- scope.phases.push(phase);
100
- let timer;
101
- joined = Promise.race([
102
- disposal,
103
- new Promise((_, reject) => {
104
- timer = setTimeout(() => {
105
- phase.outcome = 'drain-stall';
106
- reject(new Error('Owned drain-stall: real handler/disposal did not settle within 15000ms'));
107
- }, DRAIN_MS);
108
- }),
109
- ])
110
- .then(() => {
111
- phase.outcome = 'passed';
112
- }, (error) => {
113
- if (phase.outcome !== 'drain-stall')
114
- phase.outcome = 'failed';
115
- throw error;
116
- })
117
- .finally(() => {
118
- clearTimeout(timer);
119
- phase.elapsedMs = performance.now() - phase.started;
120
- joined = undefined; // Later joins observe the SAME actual disposal.
121
- });
122
- return joined;
23
+ const controller = new AbortController();
24
+ const pending = /* @__PURE__ */ new Set();
25
+ const unlink = /* @__PURE__ */ new Set();
26
+ let cleanup;
27
+ let disposal;
28
+ let joined;
29
+ const scope = {
30
+ controller,
31
+ signal: controller.signal,
32
+ pending,
33
+ phases: [],
34
+ steps,
35
+ nextStep: 0,
36
+ fixture: void 0,
37
+ forward(signal) {
38
+ const abort = () => controller.abort(signal.reason);
39
+ if (signal.aborted) abort();
40
+ else {
41
+ signal.addEventListener("abort", abort, { once: true });
42
+ unlink.add(() => signal.removeEventListener("abort", abort));
43
+ }
44
+ },
45
+ acquire(fixtureCancellation) {
46
+ controller.signal.throwIfAborted();
47
+ assert.equal(scope.fixture, void 0, "Each case acquires exactly one fixture");
48
+ const signal = fixtureCancellation ? AbortSignal.any([controller.signal, fixtureCancellation]) : controller.signal;
49
+ scope.fixture = inertTarget(signal, (ownedCleanup) => {
50
+ cleanup = ownedCleanup;
51
+ });
52
+ return scope.fixture;
53
+ },
54
+ join() {
55
+ if (joined) return joined;
56
+ disposal ??= (async () => {
57
+ controller.abort(new Error("Owned scoped runtime case finished"));
58
+ try {
59
+ while (pending.size) await Promise.allSettled(pending);
60
+ await cleanup?.();
61
+ } finally {
62
+ for (const remove of unlink) remove();
63
+ unlink.clear();
64
+ }
65
+ })();
66
+ const phase = { name: "drain", budgetMs: DRAIN_MS, started: performance.now(), outcome: "running" };
67
+ scope.phases.push(phase);
68
+ let timer;
69
+ joined = Promise.race([
70
+ disposal,
71
+ new Promise((_, reject) => {
72
+ timer = setTimeout(() => {
73
+ phase.outcome = "drain-stall";
74
+ reject(new Error("Owned drain-stall: real handler/disposal did not settle within 15000ms"));
75
+ }, DRAIN_MS);
76
+ })
77
+ ]).then(
78
+ () => {
79
+ phase.outcome = "passed";
123
80
  },
124
- };
125
- return scope;
81
+ (error) => {
82
+ if (phase.outcome !== "drain-stall") phase.outcome = "failed";
83
+ throw error;
84
+ }
85
+ ).finally(() => {
86
+ clearTimeout(timer);
87
+ phase.elapsedMs = performance.now() - phase.started;
88
+ joined = void 0;
89
+ });
90
+ return joined;
91
+ }
92
+ };
93
+ return scope;
126
94
  }
127
95
  async function scopedPhase(scope, name, budgetMs, operation) {
96
+ scope.signal.throwIfAborted();
97
+ const started = performance.now();
98
+ const timeout = new Error(`Owned ${name} deadline exceeded (${budgetMs}ms)`);
99
+ const phase = { name, budgetMs, started, outcome: "running" };
100
+ scope.phases.push(phase);
101
+ const timer = setTimeout(() => scope.controller.abort(timeout), budgetMs);
102
+ const pending = Promise.resolve().then(async () => {
128
103
  scope.signal.throwIfAborted();
129
- const started = performance.now();
130
- const timeout = new Error(`Owned ${name} deadline exceeded (${budgetMs}ms)`);
131
- const phase = { name, budgetMs, started, outcome: 'running' };
132
- scope.phases.push(phase);
133
- const timer = setTimeout(() => scope.controller.abort(timeout), budgetMs);
134
- const pending = Promise.resolve().then(async () => {
135
- scope.signal.throwIfAborted();
136
- const value = await operation();
137
- // Synchronous owned subprocesses may delay timers. Late settlement still fails.
138
- if (performance.now() - started >= budgetMs)
139
- scope.controller.abort(timeout);
140
- scope.signal.throwIfAborted();
141
- return value;
142
- });
143
- scope.pending.add(pending);
144
- // Cancellation may win the observation; actual work remains owned until settled.
145
- void pending.then(() => scope.pending.delete(pending), () => scope.pending.delete(pending));
146
- let removeAbort = () => { };
147
- try {
148
- const value = await Promise.race([
149
- pending,
150
- new Promise((_, reject) => {
151
- const abort = () => reject(scope.signal.reason);
152
- removeAbort = () => scope.signal.removeEventListener('abort', abort);
153
- scope.signal.addEventListener('abort', abort, { once: true });
154
- if (scope.signal.aborted)
155
- abort();
156
- }),
157
- ]);
158
- phase.outcome = 'passed';
159
- return value;
160
- }
161
- catch (error) {
162
- phase.outcome = scope.signal.reason === timeout ? 'deadline' : scope.signal.aborted ? 'cancelled' : 'failed';
163
- throw error;
164
- }
165
- finally {
166
- clearTimeout(timer);
167
- removeAbort();
168
- phase.elapsedMs = performance.now() - started;
169
- }
104
+ const value = await operation();
105
+ if (performance.now() - started >= budgetMs) scope.controller.abort(timeout);
106
+ scope.signal.throwIfAborted();
107
+ return value;
108
+ });
109
+ scope.pending.add(pending);
110
+ void pending.then(
111
+ () => scope.pending.delete(pending),
112
+ () => scope.pending.delete(pending)
113
+ );
114
+ let removeAbort = () => {
115
+ };
116
+ try {
117
+ const value = await Promise.race([
118
+ pending,
119
+ new Promise((_, reject) => {
120
+ const abort = () => reject(scope.signal.reason);
121
+ removeAbort = () => scope.signal.removeEventListener("abort", abort);
122
+ scope.signal.addEventListener("abort", abort, { once: true });
123
+ if (scope.signal.aborted) abort();
124
+ })
125
+ ]);
126
+ phase.outcome = "passed";
127
+ return value;
128
+ } catch (error) {
129
+ phase.outcome = scope.signal.reason === timeout ? "deadline" : scope.signal.aborted ? "cancelled" : "failed";
130
+ throw error;
131
+ } finally {
132
+ clearTimeout(timer);
133
+ removeAbort();
134
+ phase.elapsedMs = performance.now() - started;
135
+ }
170
136
  }
171
137
  async function setupStep(scope, name, operation) {
172
- const declared = scope.steps[scope.nextStep++];
173
- assert.ok(declared, `Undeclared setup operation: ${name}`);
174
- assert.equal(name, declared[0], 'Setup must execute the declared ledger in order');
175
- return scopedPhase(scope, `setup:${name}`, declared[1], async () => operation());
138
+ const declared = scope.steps[scope.nextStep++];
139
+ assert.ok(declared, `Undeclared setup operation: ${name}`);
140
+ assert.equal(name, declared[0], "Setup must execute the declared ledger in order");
141
+ return scopedPhase(scope, `setup:${name}`, declared[1], async () => operation());
176
142
  }
177
143
  async function prepareScope(scope, prepare) {
178
- try {
179
- const prepared = await prepare();
180
- assert.equal(scope.nextStep, scope.steps.length, 'Every declared setup operation must complete');
181
- return prepared;
182
- }
183
- catch (error) {
184
- scope.controller.abort(error);
185
- await scope.join();
186
- throw error;
187
- }
144
+ try {
145
+ const prepared = await prepare();
146
+ assert.equal(scope.nextStep, scope.steps.length, "Every declared setup operation must complete");
147
+ return prepared;
148
+ } catch (error) {
149
+ scope.controller.abort(error);
150
+ await scope.join();
151
+ throw error;
152
+ }
188
153
  }
189
- test('sequential setup operations may exceed the former aggregate budget while each operation stays bounded', async () => {
154
+ test(
155
+ "sequential setup operations may exceed the former aggregate budget while each operation stays bounded",
156
+ { tags: ["release"] },
157
+ async () => {
190
158
  const scope = runtimeScope([
191
- ['first', 10_000],
192
- ['second', 10_000],
159
+ ["first", 1e4],
160
+ ["second", 1e4]
193
161
  ]);
194
162
  const observed = [];
195
163
  vi.useFakeTimers();
196
164
  try {
197
- const result = prepareScope(scope, async () => {
198
- for (const [name, step] of [
199
- ['first', 1],
200
- ['second', 2],
201
- ])
202
- await setupStep(scope, name, async () => {
203
- await new Promise((resolve) => setTimeout(resolve, 8_000));
204
- observed.push(step);
205
- });
206
- return 'prepared';
207
- }).catch((error) => error);
208
- await vi.advanceTimersByTimeAsync(16_000);
209
- assert.equal(await result, 'prepared');
210
- assert.deepEqual(observed, [1, 2]);
211
- assert.deepEqual(scope.phases.map(({ name, outcome }) => ({ name, outcome })), [
212
- { name: 'setup:first', outcome: 'passed' },
213
- { name: 'setup:second', outcome: 'passed' },
214
- ]);
165
+ const result = prepareScope(scope, async () => {
166
+ for (const [name, step] of [
167
+ ["first", 1],
168
+ ["second", 2]
169
+ ])
170
+ await setupStep(scope, name, async () => {
171
+ await new Promise((resolve) => setTimeout(resolve, 8e3));
172
+ observed.push(step);
173
+ });
174
+ return "prepared";
175
+ }).catch((error) => error);
176
+ await vi.advanceTimersByTimeAsync(16e3);
177
+ assert.equal(await result, "prepared");
178
+ assert.deepEqual(observed, [1, 2]);
179
+ assert.deepEqual(
180
+ scope.phases.map(({ name, outcome }) => ({ name, outcome })),
181
+ [
182
+ { name: "setup:first", outcome: "passed" },
183
+ { name: "setup:second", outcome: "passed" }
184
+ ]
185
+ );
186
+ } finally {
187
+ vi.useRealTimers();
188
+ await scope.join();
215
189
  }
216
- finally {
217
- vi.useRealTimers();
218
- await scope.join();
219
- }
220
- });
221
- test('held real handler reports a finite drain stall, retains ownership and permits cleanup only after late settlement', async ({ signal, }) => {
190
+ }
191
+ );
192
+ test(
193
+ "held real handler reports a finite drain stall, retains ownership and permits cleanup only after late settlement",
194
+ { tags: ["release"], timeout: 3e4 },
195
+ async ({ signal }) => {
222
196
  const scope = runtimeScope();
223
197
  scope.forward(signal);
224
198
  const f = scope.acquire();
225
199
  let release;
226
200
  let entered;
227
201
  const held = new Promise((resolve) => {
228
- release = resolve;
202
+ release = resolve;
229
203
  });
230
204
  const reached = new Promise((resolve) => {
231
- entered = resolve;
205
+ entered = resolve;
232
206
  });
233
207
  const get = f.rest.issues.get;
234
208
  let handlerSettled = false;
235
209
  f.rest.issues.get = async (input) => {
236
- entered();
237
- await held;
238
- handlerSettled = true;
239
- return get(input);
210
+ entered();
211
+ await held;
212
+ handlerSettled = true;
213
+ return get(input);
240
214
  };
241
215
  try {
242
- const c = await f.connect();
243
- const call = c.call('issue_info', { issueNumber: 17 }).catch((error) => error);
244
- await reached;
245
- vi.useFakeTimers();
246
- let outcome;
247
- const joined = scope.join().then(() => {
248
- outcome = 'drained';
249
- }, (error) => {
250
- outcome = error;
251
- });
252
- await vi.advanceTimersByTimeAsync(15_000);
253
- assert.ok(outcome instanceof Error, 'A held handler must produce a finite drain-stall outcome');
254
- assert.match(outcome.message, /drain-stall/u);
255
- assert.equal(handlerSettled, false);
256
- assert.equal(existsSync(f.root), true);
257
- assert.throws(() => inertTarget(signal), /previous fixture must finish disposal/u);
258
- await joined;
259
- release();
260
- await scope.join();
261
- await call;
262
- assert.equal(handlerSettled, true);
263
- assert.equal(existsSync(f.base), false);
264
- const next = inertTarget(signal);
265
- await next.dispose(undefined);
266
- }
267
- finally {
268
- vi.useRealTimers();
269
- release();
270
- await scope.join();
271
- }
272
- }, 30_000);
273
- for (const phase of ['setup', 'asserted body'])
274
- test(`an individual ${phase} stall aborts without dropping unsettled work`, async () => {
275
- const scope = runtimeScope([['controlled', 1_000]]);
276
- let release;
277
- const held = new Promise((resolve) => {
278
- release = resolve;
279
- });
280
- vi.useFakeTimers();
281
- try {
282
- const result = (phase === 'setup'
283
- ? setupStep(scope, 'controlled', () => held)
284
- : scopedPhase(scope, phase, ASSERTED_MS, () => held)).catch((error) => error);
285
- await vi.advanceTimersByTimeAsync(phase === 'setup' ? 1_000 : ASSERTED_MS);
286
- assert.match(String(await result), /deadline exceeded/u);
287
- assert.equal(scope.signal.aborted, true);
288
- assert.equal(scope.pending.size, 1, 'Cancellation must not erase the unsettled operation');
289
- assert.equal(scope.phases[0].outcome, 'deadline');
290
- }
291
- finally {
292
- vi.useRealTimers();
293
- release();
294
- await scope.join();
295
- assert.equal(scope.pending.size, 0);
216
+ const c = await f.connect();
217
+ const call = c.call("issue_info", { issueNumber: 17 }).catch((error) => error);
218
+ await reached;
219
+ vi.useFakeTimers();
220
+ let outcome;
221
+ const joined = scope.join().then(
222
+ () => {
223
+ outcome = "drained";
224
+ },
225
+ (error) => {
226
+ outcome = error;
296
227
  }
228
+ );
229
+ await vi.advanceTimersByTimeAsync(15e3);
230
+ assert.ok(outcome instanceof Error, "A held handler must produce a finite drain-stall outcome");
231
+ assert.match(outcome.message, /drain-stall/u);
232
+ assert.equal(handlerSettled, false);
233
+ assert.equal(existsSync(f.root), true);
234
+ assert.throws(() => inertTarget(signal), /previous fixture must finish disposal/u);
235
+ await joined;
236
+ release();
237
+ await scope.join();
238
+ await call;
239
+ assert.equal(handlerSettled, true);
240
+ assert.equal(existsSync(f.base), false);
241
+ const next = inertTarget(signal);
242
+ await next.dispose(void 0);
243
+ } finally {
244
+ vi.useRealTimers();
245
+ release();
246
+ await scope.join();
247
+ }
248
+ }
249
+ );
250
+ for (const phase of ["setup", "asserted body"])
251
+ test(`an individual ${phase} stall aborts without dropping unsettled work`, { tags: ["release"] }, async () => {
252
+ const scope = runtimeScope([["controlled", 1e3]]);
253
+ let release;
254
+ const held = new Promise((resolve) => {
255
+ release = resolve;
297
256
  });
257
+ vi.useFakeTimers();
258
+ try {
259
+ const result = (phase === "setup" ? setupStep(scope, "controlled", () => held) : scopedPhase(scope, phase, ASSERTED_MS, () => held)).catch((error) => error);
260
+ await vi.advanceTimersByTimeAsync(phase === "setup" ? 1e3 : ASSERTED_MS);
261
+ assert.match(String(await result), /deadline exceeded/u);
262
+ assert.equal(scope.signal.aborted, true);
263
+ assert.equal(scope.pending.size, 1, "Cancellation must not erase the unsettled operation");
264
+ assert.equal(scope.phases[0].outcome, "deadline");
265
+ } finally {
266
+ vi.useRealTimers();
267
+ release();
268
+ await scope.join();
269
+ assert.equal(scope.pending.size, 0);
270
+ }
271
+ });
298
272
  const faultSteps = [
299
- ['fixture', 7 * GIT_MS],
300
- ['connect', REQUEST_MS],
273
+ ["fixture", 7 * GIT_MS],
274
+ ["connect", REQUEST_MS]
301
275
  ];
302
276
  const faultBudget = faultSteps.reduce((sum, [, budget]) => sum + budget, 0) + DRAIN_MS;
303
- const neverReleasedCase = 'never-released real handler fails in a supervised native test process and is reaped before cleanup';
304
- test(neverReleasedCase, async ({ signal }) => {
305
- const recordPath = process.env['AI_DELIVERY_DRAIN_FAULT_RECORD'];
306
- if (recordPath) {
307
- // Only the supervised child enters this fault. It deliberately never releases
308
- // the real handler; an active handle prevents an idle event loop hiding it.
309
- const scope = runtimeScope(faultSteps);
310
- scope.forward(signal);
311
- const f = await setupStep(scope, 'fixture', () => scope.acquire());
312
- const owned = lstatSync(f.base);
313
- let entered;
314
- const reached = new Promise((resolve) => {
315
- entered = resolve;
316
- });
317
- f.rest.issues.get = async () => {
318
- setInterval(() => { }, 1_000);
319
- entered();
320
- await new Promise(() => { });
321
- throw new Error('Never released');
322
- };
323
- const c = await setupStep(scope, 'connect', () => f.connect());
324
- void c.call('issue_info', { issueNumber: 17 }).catch(() => { });
325
- await reached;
326
- try {
327
- await scope.join();
328
- assert.fail('A never-released real handler cannot drain');
329
- }
330
- catch (error) {
331
- assert.match(String(error), /drain-stall/u);
332
- assert.equal(existsSync(f.base), true);
333
- assert.throws(() => inertTarget(signal), /previous fixture must finish disposal/u);
334
- writeFileSync(recordPath, JSON.stringify({
335
- base: f.base,
336
- dev: owned.dev,
337
- ino: owned.ino,
338
- uid: owned.uid,
339
- retainedOwnership: true,
340
- phases: scope.phases,
341
- }), { flag: 'wx', mode: 0o600 });
342
- throw error;
343
- }
344
- }
345
- const checks = (await import(new URL('../scripts/checks.mjs', import.meta.url).href));
346
- const evidence = realpathSync(mkdtempSync(join(tmpdir(), 'ai-delivery-drain-fault-evidence-')));
347
- const temporary = join(evidence, 'temporary');
348
- mkdirSync(temporary);
349
- const record = join(evidence, 'retained-handler.json');
350
- const unrelated = join(evidence, 'unrelated');
351
- writeFileSync(unrelated, 'preserved');
352
- const started = performance.now();
353
- const command = await checks.executeCommand([
354
- process.execPath,
355
- fileURLToPath(new URL('../node_modules/vitest/vitest.mjs', import.meta.url)),
356
- 'run',
357
- fileURLToPath(import.meta.url),
358
- '-t',
359
- neverReleasedCase,
360
- '--reporter=json',
361
- '--outputFile=' + join(evidence, 'vitest.json'),
362
- ], {
363
- cwd: fileURLToPath(new URL('../', import.meta.url)),
364
- env: {
365
- ...checks.safeEnvironment(process.env),
366
- TMPDIR: temporary,
367
- AI_DELIVERY_DRAIN_FAULT_RECORD: record,
368
- },
369
- directory: join(evidence, 'command'),
370
- signal,
371
- timeoutMs: faultBudget,
372
- maxRssBytes: 1024 ** 3,
373
- progress: (partial) => writeFileSync(join(evidence, 'supervision.json'), JSON.stringify(partial)),
374
- });
375
- assert.ok(['failed', 'command-timeout', 'owned-child-remained-after-command'].includes(command.status));
376
- assert.notEqual(command.exitCode, 0);
377
- assert.equal(command.cleanupConfirmed, true);
378
- assert.equal(checks.confirmCommandQuiescence(command).quiescent, true);
379
- assert.ok(performance.now() - started <= faultBudget + 4_000, 'Fault supervision must finish within its declared budget and termination grace');
380
- assert.ok(command.observedProcesses.length > 0);
381
- const retained = JSON.parse(readFileSync(record, 'utf8'));
382
- assert.equal(retained.retainedOwnership, true);
383
- assert.ok(retained.phases.some((phase) => phase.name === 'drain' && phase.outcome === 'drain-stall'));
384
- assert.ok(retained.base.startsWith(temporary + '/ai-delivery-inert-target-'));
385
- const owned = lstatSync(retained.base);
386
- assert.equal(owned.isSymbolicLink(), false);
387
- assert.deepEqual([owned.dev, owned.ino, owned.uid], [retained.dev, retained.ino, retained.uid]);
388
- assert.equal(readFileSync(unrelated, 'utf8'), 'preserved');
389
- // Termination/quiescence is the alternative to actual settlement. Only now may
390
- // this parent's exact child temporary root be removed. Keep original evidence.
391
- rmSync(temporary, { recursive: true });
392
- assert.equal(existsSync(temporary), false);
393
- const receipt = {
394
- elapsedMs: performance.now() - started,
395
- faultBudgetMs: faultBudget,
396
- command,
397
- ownedTemporaryRemoved: true,
398
- unrelatedPreserved: true,
399
- evidence,
400
- };
401
- writeFileSync(join(evidence, 'result.json'), JSON.stringify(receipt, null, 2));
402
- process.stdout.write('DRAIN_FAULT_SUPERVISION_RECEIPT ' + JSON.stringify(receipt) + '\n');
403
- }, faultBudget + 4_000); // Existing supervisor: 3s TERM grace + 1s quiescence confirmation.
404
- function scopedRuntimeCase(name, steps, prepare, observe) {
405
- describe('per-operation runtime preparation (15s asserted work, 15s drain)', () => {
406
- let owned;
407
- beforeEach(async ({ signal }) => {
408
- assert.equal(owned, undefined, 'Previous case must finish owned teardown');
409
- const scope = runtimeScope(steps);
410
- owned = { scope, ready: false };
411
- scope.forward(signal);
412
- owned.prepared = await prepareScope(scope, () => prepare(scope));
413
- owned.ready = true;
414
- }, steps.reduce((sum, [, budget]) => sum + budget, 0) + DRAIN_MS);
415
- afterEach(async () => {
416
- const current = owned;
417
- if (current) {
418
- await current.scope.join();
419
- process.stderr.write('ai-delivery.fixture-phases ' + JSON.stringify(current.scope.phases) + '\n');
420
- owned = undefined;
421
- }
422
- }, ASSERTED_MS + DRAIN_MS);
423
- test(name, async ({ signal }) => {
424
- const current = owned;
425
- assert.ok(current?.ready, 'Real case prerequisites must finish before the asserted body');
426
- assert.ok(current.prepared);
427
- const prepared = current.prepared;
428
- current.scope.forward(signal);
429
- try {
430
- await scopedPhase(current.scope, 'asserted body', ASSERTED_MS, () => observe(prepared));
431
- }
432
- finally {
433
- await current.scope.join();
434
- }
435
- }, ASSERTED_MS + DRAIN_MS);
277
+ const neverReleasedCase = "never-released real handler fails in a supervised native test process and is reaped before cleanup";
278
+ test(neverReleasedCase, { tags: ["release"], timeout: faultBudget + 4e3 }, async ({ signal }) => {
279
+ const recordPath = process.env["AI_DELIVERY_DRAIN_FAULT_RECORD"];
280
+ if (recordPath) {
281
+ const scope = runtimeScope(faultSteps);
282
+ scope.forward(signal);
283
+ const f = await setupStep(scope, "fixture", () => scope.acquire());
284
+ const owned2 = lstatSync(f.base);
285
+ let entered;
286
+ const reached = new Promise((resolve) => {
287
+ entered = resolve;
436
288
  });
437
- }
438
- async function runtimeFixture(f, scope) {
439
- f.signal.throwIfAborted();
440
- const archive = () => {
441
- const packageRoot = join(f.base, 'archive', 'package');
442
- const lifecycleSentinel = join(f.base, 'lifecycle-executed');
443
- const files = {
444
- 'package.json': JSON.stringify({
445
- name: '@aviaratech/ai-delivery',
446
- version: '0.3.5',
447
- type: 'module',
448
- bin: { 'ai-delivery': './dist/cli.js' },
449
- scripts: { preinstall: 'node lifecycle.cjs', postinstall: 'node lifecycle.cjs' },
450
- }),
451
- 'lifecycle.cjs': `require('node:fs').appendFileSync(${JSON.stringify(lifecycleSentinel)},'executed\\n');\n`,
452
- 'dist/cli.js': "#!/usr/bin/env node\nconsole.log('0.3.5');\n",
453
- 'dist/agent.js': 'export const fictional = true;\n',
454
- 'plugins/ai-delivery/dist/mcp-launcher.js': '/* Owned inert launcher bytes. */\n',
455
- 'plugins/ai-delivery/.claude-plugin/plugin.json': JSON.stringify({
456
- name: 'ai-delivery',
457
- packageVersion: '0.3.5',
458
- deliveryCapabilityVersion: 2,
459
- }),
460
- };
461
- for (const [path, bytes] of Object.entries(files)) {
462
- const file = join(packageRoot, path);
463
- mkdirSync(dirname(file), { recursive: true });
464
- writeFileSync(file, bytes);
465
- }
466
- const archivePath = join(f.base, 'inert.tgz');
467
- execFileSync('tar', ['-czf', archivePath, '-C', dirname(packageRoot), 'package'], {
468
- timeout: 5_000,
469
- maxBuffer: 64 * 1024,
470
- });
471
- return { archivePath, lifecycleSentinel };
289
+ f.rest.issues.get = async () => {
290
+ setInterval(() => {
291
+ }, 1e3);
292
+ entered();
293
+ await new Promise(() => {
294
+ });
295
+ throw new Error("Never released");
472
296
  };
473
- const { archivePath, lifecycleSentinel } = scope ? await setupStep(scope, 'archive', archive) : archive();
474
- const config = () => loadDeliveryConfig(f.root, {
475
- repository: 'example/widget',
476
- signal: f.signal,
477
- clients: { graphql: f.graphql },
297
+ const c = await setupStep(scope, "connect", () => f.connect());
298
+ void c.call("issue_info", { issueNumber: 17 }).catch(() => {
478
299
  });
479
- const loaded = scope ? await setupStep(scope, 'config', config) : await config();
480
- const runtimeDirectory = join(f.base, 'runtime');
481
- const common = { expectedSourceCommit: f.head, expectedConfigDigest: loaded.configDigest, runtimeDirectory };
482
- return {
483
- archivePath,
484
- lifecycleSentinel,
485
- common,
486
- stage: {
487
- ...common,
488
- authority: 'runtime:stage',
489
- archivePath,
490
- expectedArchiveSha256: digestBytes(readFileSync(archivePath)),
491
- packageVersion: '0.3.5',
492
- resourceBounds: {
493
- maxAggregateRssBytes: 384 * 1024 ** 2,
494
- minFreeDiskBytes: 8 * 1024 ** 2,
495
- maxNewOutputBytes: 8 * 1024 ** 2,
496
- maxCapturedOutputBytes: 64 * 1024,
497
- },
498
- },
499
- cli: join(runtimeDirectory, 'node_modules/@aviaratech/ai-delivery/dist/cli.js'),
500
- };
501
- }
300
+ await reached;
301
+ try {
302
+ await scope.join();
303
+ assert.fail("A never-released real handler cannot drain");
304
+ } catch (error) {
305
+ assert.match(String(error), /drain-stall/u);
306
+ assert.equal(existsSync(f.base), true);
307
+ assert.throws(() => inertTarget(signal), /previous fixture must finish disposal/u);
308
+ writeFileSync(
309
+ recordPath,
310
+ JSON.stringify({
311
+ base: f.base,
312
+ dev: owned2.dev,
313
+ ino: owned2.ino,
314
+ uid: owned2.uid,
315
+ retainedOwnership: true,
316
+ phases: scope.phases
317
+ }),
318
+ { flag: "wx", mode: 384 }
319
+ );
320
+ throw error;
321
+ }
322
+ }
323
+ const checks = await import(new URL("../scripts/checks.mjs", import.meta.url).href);
324
+ const evidence = realpathSync(mkdtempSync(join(tmpdir(), "ai-delivery-drain-fault-evidence-")));
325
+ const temporary = join(evidence, "temporary");
326
+ mkdirSync(temporary);
327
+ const record = join(evidence, "retained-handler.json");
328
+ const unrelated = join(evidence, "unrelated");
329
+ writeFileSync(unrelated, "preserved");
330
+ const started = performance.now();
331
+ const command = await checks.executeCommand(
332
+ [
333
+ process.execPath,
334
+ fileURLToPath(new URL("../node_modules/vitest/vitest.mjs", import.meta.url)),
335
+ "run",
336
+ "--mode=compiled",
337
+ fileURLToPath(import.meta.url),
338
+ "-t",
339
+ neverReleasedCase,
340
+ "--reporter=json",
341
+ "--outputFile=" + join(evidence, "vitest.json")
342
+ ],
343
+ {
344
+ cwd: fileURLToPath(new URL("../", import.meta.url)),
345
+ env: {
346
+ ...checks.safeEnvironment(process.env),
347
+ TMPDIR: temporary,
348
+ AI_DELIVERY_DRAIN_FAULT_RECORD: record
349
+ },
350
+ directory: join(evidence, "command"),
351
+ signal,
352
+ timeoutMs: faultBudget,
353
+ maxRssBytes: 1024 ** 3,
354
+ progress: (partial) => writeFileSync(join(evidence, "supervision.json"), JSON.stringify(partial))
355
+ }
356
+ );
357
+ assert.ok(["failed", "command-timeout", "owned-child-remained-after-command"].includes(command.status));
358
+ assert.notEqual(command.exitCode, 0);
359
+ assert.equal(command.cleanupConfirmed, true);
360
+ assert.equal(checks.confirmCommandQuiescence(command).quiescent, true);
361
+ assert.ok(
362
+ performance.now() - started <= faultBudget + 4e3,
363
+ "Fault supervision must finish within its declared budget and termination grace"
364
+ );
365
+ assert.ok(command.observedProcesses.length > 0);
366
+ const retained = JSON.parse(readFileSync(record, "utf8"));
367
+ assert.equal(retained.retainedOwnership, true);
368
+ assert.ok(retained.phases.some((phase) => phase.name === "drain" && phase.outcome === "drain-stall"));
369
+ assert.ok(retained.base.startsWith(temporary + "/ai-delivery-inert-target-"));
370
+ const owned = lstatSync(retained.base);
371
+ assert.equal(owned.isSymbolicLink(), false);
372
+ assert.deepEqual([owned.dev, owned.ino, owned.uid], [retained.dev, retained.ino, retained.uid]);
373
+ assert.equal(readFileSync(unrelated, "utf8"), "preserved");
374
+ rmSync(temporary, { recursive: true });
375
+ assert.equal(existsSync(temporary), false);
376
+ const receipt = {
377
+ elapsedMs: performance.now() - started,
378
+ faultBudgetMs: faultBudget,
379
+ command,
380
+ ownedTemporaryRemoved: true,
381
+ unrelatedPreserved: true,
382
+ evidence
383
+ };
384
+ writeFileSync(join(evidence, "result.json"), JSON.stringify(receipt, null, 2));
385
+ process.stdout.write("DRAIN_FAULT_SUPERVISION_RECEIPT " + JSON.stringify(receipt) + "\n");
386
+ });
502
387
  const cancellationSteps = [
503
- ['fixture', 7 * GIT_MS],
504
- ['policy', 4 * GIT_MS],
505
- ['connect', REQUEST_MS],
388
+ ["fixture", 7 * GIT_MS],
389
+ ["policy", 4 * GIT_MS],
390
+ ["connect", REQUEST_MS]
506
391
  ];
507
- for (const preparationDelayMs of [0, 3_000])
508
- test(preparationDelayMs === 0
509
- ? 'fixture cancellation drains the real MCP handler before releasing global ownership'
510
- : 'fixture cancellation and reuse keep bounded preparation outside asserted-work budgets', async ({ signal }) => {
511
- const first = runtimeScope(cancellationSteps);
512
- const reuse = runtimeScope(cancellationSteps);
513
- first.forward(signal);
514
- reuse.forward(signal);
515
- const cancellation = new AbortController();
516
- let release;
517
- let entered;
518
- const held = new Promise((resolve) => {
519
- release = resolve;
392
+ for (const preparationDelayMs of [0, 3e3])
393
+ test(
394
+ preparationDelayMs === 0 ? "fixture cancellation drains the real MCP handler before releasing global ownership" : "fixture cancellation and reuse keep bounded preparation outside asserted-work budgets",
395
+ {
396
+ tags: ["release"],
397
+ timeout: 2 * (cancellationSteps.reduce((sum, [, budget]) => sum + budget, 0) + ASSERTED_MS + 2 * DRAIN_MS)
398
+ },
399
+ async ({ signal }) => {
400
+ const first = runtimeScope(cancellationSteps);
401
+ const reuse = runtimeScope(cancellationSteps);
402
+ first.forward(signal);
403
+ reuse.forward(signal);
404
+ const cancellation = new AbortController();
405
+ let release;
406
+ let entered;
407
+ const held = new Promise((resolve) => {
408
+ release = resolve;
409
+ });
410
+ const reached = new Promise((resolve) => {
411
+ entered = resolve;
412
+ });
413
+ const prepare = (scope, fixtureCancellation) => prepareScope(scope, async () => {
414
+ const f = await setupStep(scope, "fixture", async () => {
415
+ if (preparationDelayMs) await new Promise((resolve) => setTimeout(resolve, preparationDelayMs));
416
+ return scope.acquire(fixtureCancellation);
520
417
  });
521
- const reached = new Promise((resolve) => {
522
- entered = resolve;
418
+ await setupStep(scope, "policy", () => f.policy("tracked"));
419
+ const connection = await setupStep(scope, "connect", () => f.connect());
420
+ return { f, connection };
421
+ });
422
+ try {
423
+ const { f, connection } = await prepare(first, cancellation.signal);
424
+ const get = f.rest.issues.get;
425
+ let portSettled = false;
426
+ f.rest.issues.get = async (input) => {
427
+ entered();
428
+ await held;
429
+ portSettled = true;
430
+ return get(input);
431
+ };
432
+ await scopedPhase(first, "asserted cancellation", ASSERTED_MS, async () => {
433
+ const pending = connection.call("issue_info", { issueNumber: 17 });
434
+ const rejected = assert.rejects(pending, /Controlled fixture cancellation/u);
435
+ void rejected.catch(() => {
436
+ });
437
+ await Promise.race([
438
+ reached,
439
+ pending.then(() => {
440
+ throw new Error("Controlled real handler was not reached");
441
+ })
442
+ ]);
443
+ cancellation.abort(new Error("Controlled fixture cancellation"));
444
+ const disposal = f.dispose(connection);
445
+ assert.equal(f.dispose(connection), disposal, "All disposal callers must join the same promise");
446
+ let disposed = false;
447
+ void disposal.then(
448
+ () => {
449
+ disposed = true;
450
+ },
451
+ () => {
452
+ }
453
+ );
454
+ await rejected;
455
+ assert.equal(portSettled, false);
456
+ assert.equal(disposed, false, "Transport cancellation must not be treated as handler settlement");
457
+ assert.equal(existsSync(f.root), true, "Files remain owned until the handler settles");
458
+ assert.throws(() => inertTarget(signal), /previous fixture must finish disposal/u);
459
+ release();
523
460
  });
524
- const prepare = (scope, fixtureCancellation) => prepareScope(scope, async () => {
525
- const f = await setupStep(scope, 'fixture', async () => {
526
- if (preparationDelayMs)
527
- await new Promise((resolve) => setTimeout(resolve, preparationDelayMs));
528
- return scope.acquire(fixtureCancellation);
529
- });
530
- await setupStep(scope, 'policy', () => f.policy('tracked'));
531
- const connection = await setupStep(scope, 'connect', () => f.connect());
532
- return { f, connection };
461
+ await first.join();
462
+ assert.equal(portSettled, true);
463
+ assert.equal(existsSync(f.base), false);
464
+ const next = await prepare(reuse);
465
+ if (preparationDelayMs) {
466
+ const setupElapsed = [first, reuse].flatMap(
467
+ (scope) => scope.phases.filter((phase) => phase.name.startsWith("setup:"))
468
+ );
469
+ assert.ok(
470
+ setupElapsed.reduce((sum, phase) => sum + phase.elapsedMs, 0) > 5e3,
471
+ "Two bounded preparations must exceed the former aggregate five-second fuse"
472
+ );
473
+ }
474
+ await scopedPhase(reuse, "asserted reuse", ASSERTED_MS, async () => {
475
+ await f.dispose(connection);
476
+ const result = await next.connection.call("issue_info", { issueNumber: 17 });
477
+ assert.notEqual(result.response.isError, true, result.text);
478
+ assert.ok(next.f.calls.some((call) => call.name === "issues.get"));
533
479
  });
480
+ } finally {
481
+ release();
534
482
  try {
535
- const { f, connection } = await prepare(first, cancellation.signal);
536
- const get = f.rest.issues.get;
537
- let portSettled = false;
538
- f.rest.issues.get = async (input) => {
539
- entered();
540
- await held;
541
- portSettled = true;
542
- return get(input);
543
- };
544
- await scopedPhase(first, 'asserted cancellation', ASSERTED_MS, async () => {
545
- const pending = connection.call('issue_info', { issueNumber: 17 });
546
- const rejected = assert.rejects(pending, /Controlled fixture cancellation/u);
547
- // Observe immediately, then join below; an early transport failure must
548
- // also release the wait for real handler entry rather than strand it.
549
- void rejected.catch(() => { });
550
- await Promise.race([
551
- reached,
552
- pending.then(() => {
553
- throw new Error('Controlled real handler was not reached');
554
- }),
555
- ]);
556
- cancellation.abort(new Error('Controlled fixture cancellation'));
557
- const disposal = f.dispose(connection);
558
- assert.equal(f.dispose(connection), disposal, 'All disposal callers must join the same promise');
559
- let disposed = false;
560
- void disposal.then(() => {
561
- disposed = true;
562
- }, () => { });
563
- await rejected;
564
- assert.equal(portSettled, false);
565
- assert.equal(disposed, false, 'Transport cancellation must not be treated as handler settlement');
566
- assert.equal(existsSync(f.root), true, 'Files remain owned until the handler settles');
567
- assert.throws(() => inertTarget(signal), /previous fixture must finish disposal/u);
568
- release();
569
- });
570
- await first.join();
571
- assert.equal(portSettled, true);
572
- assert.equal(existsSync(f.base), false);
573
- const next = await prepare(reuse);
574
- if (preparationDelayMs) {
575
- const setupElapsed = [first, reuse].flatMap((scope) => scope.phases.filter((phase) => phase.name.startsWith('setup:')));
576
- assert.ok(setupElapsed.reduce((sum, phase) => sum + phase.elapsedMs, 0) > 5_000, 'Two bounded preparations must exceed the former aggregate five-second fuse');
577
- }
578
- await scopedPhase(reuse, 'asserted reuse', ASSERTED_MS, async () => {
579
- await f.dispose(connection);
580
- const result = await next.connection.call('issue_info', { issueNumber: 17 });
581
- assert.notEqual(result.response.isError, true, result.text);
582
- assert.ok(next.f.calls.some((call) => call.name === 'issues.get'));
583
- });
483
+ await first.join();
484
+ } finally {
485
+ await reuse.join();
486
+ process.stderr.write(
487
+ "CANCELLATION_SCOPE_PHASES " + JSON.stringify({ preparationDelayMs, first: first.phases, reuse: reuse.phases }) + "\n"
488
+ );
584
489
  }
585
- finally {
586
- release();
587
- try {
588
- await first.join();
589
- }
590
- finally {
591
- await reuse.join();
592
- process.stderr.write('CANCELLATION_SCOPE_PHASES ' +
593
- JSON.stringify({ preparationDelayMs, first: first.phases, reuse: reuse.phases }) +
594
- '\n');
595
- }
596
- }
597
- },
598
- // Each owner has finite setup/assertion limits and a distinct drain-stall
599
- // bound; this framework guard includes failure-path and final cleanup joins.
600
- 2 * (cancellationSteps.reduce((sum, [, budget]) => sum + budget, 0) + ASSERTED_MS + 2 * DRAIN_MS));
601
- test('fixture disposal closes a cancelled MCP connection', async ({ signal }) => {
490
+ }
491
+ }
492
+ );
493
+ test(
494
+ "fixture disposal closes a cancelled MCP connection",
495
+ { tags: ["release"], timeout: 5e3 },
496
+ async ({ signal }) => {
602
497
  const f = inertTarget(signal);
603
498
  const cancellation = new AbortController();
604
- cancellation.abort(new Error('Controlled connection cancellation'));
499
+ cancellation.abort(new Error("Controlled connection cancellation"));
605
500
  try {
606
- await assert.rejects(f.connect({ signal: cancellation.signal }), /Controlled connection cancellation/u);
607
- }
608
- finally {
609
- await f.dispose(undefined);
501
+ await assert.rejects(f.connect({ signal: cancellation.signal }), /Controlled connection cancellation/u);
502
+ } finally {
503
+ await f.dispose(void 0);
610
504
  }
611
505
  assert.equal(existsSync(f.base), false);
612
506
  const next = inertTarget(signal);
613
507
  try {
614
- const loaded = await loadDeliveryConfig(next.root, {
615
- repository: 'example/widget',
616
- clients: { graphql: next.graphql },
617
- });
618
- assert.ok(loaded.configDigest);
508
+ const loaded = await loadDeliveryConfig(next.root, {
509
+ repository: "example/widget",
510
+ clients: { graphql: next.graphql }
511
+ });
512
+ assert.ok(loaded.configDigest);
513
+ } finally {
514
+ await next.dispose(void 0);
619
515
  }
620
- finally {
621
- await next.dispose(undefined);
622
- }
623
- }, 5_000);
624
- async function stageAndAdmit(f, c, scope) {
625
- const runtime = await runtimeFixture(f, scope);
626
- const staged = await setupStep(scope, 'runtime_stage', () => c.call('runtime_stage', runtime.stage));
627
- assert.notEqual(staged.response.isError, true, staged.text);
628
- const admitted = await setupStep(scope, 'runtime_admit', () => c.call('runtime_admit', {
629
- ...runtime.common,
630
- authority: 'runtime:admit',
631
- stageId: staged.value.stageId,
632
- expectedPriorAdmissionSha256: null,
633
- }));
634
- assert.notEqual(admitted.response.isError, true, admitted.text);
635
- return { ...runtime, stageId: staged.value.stageId, admission: admitted.value.admission };
636
- }
637
- for (const cancellation of ['hook signal', 'owned setup deadline']) {
638
- test(`scoped runtime setup ${cancellation} aborts and drains a real handler before releasing globals`, async ({ signal, }) => {
639
- const scope = runtimeScope();
640
- const hook = new AbortController();
641
- scope.forward(signal);
642
- scope.forward(hook.signal);
643
- const f = scope.acquire();
644
- let release;
645
- let entered;
646
- const held = new Promise((resolve) => {
647
- release = resolve;
648
- });
649
- const reached = new Promise((resolve) => {
650
- entered = resolve;
516
+ }
517
+ );
518
+ for (const cancellation of ["hook signal", "owned setup deadline"]) {
519
+ test(
520
+ `scoped runtime setup ${cancellation} aborts and drains a real handler before releasing globals`,
521
+ { tags: ["release"], timeout: 5e3 },
522
+ async ({ signal }) => {
523
+ const scope = runtimeScope();
524
+ const hook = new AbortController();
525
+ scope.forward(signal);
526
+ scope.forward(hook.signal);
527
+ const f = scope.acquire();
528
+ let release;
529
+ let entered;
530
+ const held = new Promise((resolve) => {
531
+ release = resolve;
532
+ });
533
+ const reached = new Promise((resolve) => {
534
+ entered = resolve;
535
+ });
536
+ const get = f.rest.issues.get;
537
+ let handlerSettled = false;
538
+ f.rest.issues.get = async (input) => {
539
+ entered();
540
+ await held;
541
+ handlerSettled = true;
542
+ return get(input);
543
+ };
544
+ try {
545
+ f.policy("tracked");
546
+ const c = await f.connect();
547
+ let callOutcome;
548
+ const setup = prepareScope(
549
+ scope,
550
+ () => scopedPhase(scope, "setup", cancellation === "owned setup deadline" ? 1e3 : REQUEST_MS, async () => {
551
+ const call = c.call("issue_info", { issueNumber: 17 });
552
+ callOutcome = call.then(
553
+ () => void 0,
554
+ (error) => error
555
+ );
556
+ return call;
557
+ })
558
+ );
559
+ const setupOutcome = setup.then(
560
+ () => void 0,
561
+ (error) => error
562
+ );
563
+ let setupSettled = false;
564
+ void setupOutcome.then(() => {
565
+ setupSettled = true;
651
566
  });
652
- const get = f.rest.issues.get;
653
- let handlerSettled = false;
654
- f.rest.issues.get = async (input) => {
655
- entered();
656
- await held;
657
- handlerSettled = true;
658
- return get(input);
659
- };
567
+ await reached;
568
+ if (cancellation === "hook signal") hook.abort(new Error("Controlled hook cancellation"));
569
+ assert.match(String(await callOutcome), /Controlled hook cancellation|Owned setup deadline exceeded/u);
570
+ assert.equal(handlerSettled, false);
571
+ assert.equal(setupSettled, false, "Rejected transport is not joined setup completion");
572
+ const disposal = scope.join();
573
+ assert.equal(scope.join(), disposal, "All cleanup paths join one owned disposal");
574
+ let disposed = false;
575
+ void disposal.then(
576
+ () => {
577
+ disposed = true;
578
+ },
579
+ () => {
580
+ }
581
+ );
582
+ await Promise.resolve();
583
+ assert.equal(disposed, false);
584
+ assert.equal(existsSync(f.root), true);
585
+ assert.throws(() => inertTarget(signal), /previous fixture must finish disposal/u);
586
+ release();
587
+ assert.match(String(await setupOutcome), /Controlled hook cancellation|Owned setup deadline exceeded/u);
588
+ await disposal;
589
+ assert.equal(handlerSettled, true);
590
+ assert.equal(existsSync(f.base), false);
591
+ const next = inertTarget(signal);
660
592
  try {
661
- f.policy('tracked');
662
- const c = await f.connect();
663
- let callOutcome;
664
- const setup = prepareScope(scope, () => scopedPhase(scope, 'setup', cancellation === 'owned setup deadline' ? 1_000 : REQUEST_MS, async () => {
665
- const call = c.call('issue_info', { issueNumber: 17 });
666
- callOutcome = call.then(() => undefined, (error) => error);
667
- return call;
668
- }));
669
- // Observe both outcomes immediately; failures before release must not create
670
- // an unhandled assertion promise while the held real handler is drained.
671
- const setupOutcome = setup.then(() => undefined, (error) => error);
672
- let setupSettled = false;
673
- void setupOutcome.then(() => {
674
- setupSettled = true;
675
- });
676
- await reached;
677
- if (cancellation === 'hook signal')
678
- hook.abort(new Error('Controlled hook cancellation'));
679
- assert.match(String(await callOutcome), /Controlled hook cancellation|Owned setup deadline exceeded/u);
680
- assert.equal(handlerSettled, false);
681
- assert.equal(setupSettled, false, 'Rejected transport is not joined setup completion');
682
- const disposal = scope.join();
683
- assert.equal(scope.join(), disposal, 'All cleanup paths join one owned disposal');
684
- let disposed = false;
685
- void disposal.then(() => {
686
- disposed = true;
687
- }, () => { });
688
- await Promise.resolve();
689
- assert.equal(disposed, false);
690
- assert.equal(existsSync(f.root), true);
691
- assert.throws(() => inertTarget(signal), /previous fixture must finish disposal/u);
692
- release();
693
- assert.match(String(await setupOutcome), /Controlled hook cancellation|Owned setup deadline exceeded/u);
694
- await disposal;
695
- assert.equal(handlerSettled, true);
696
- assert.equal(existsSync(f.base), false);
697
- const next = inertTarget(signal);
698
- try {
699
- next.policy('tracked');
700
- const nextConnection = await next.connect();
701
- const result = await nextConnection.call('issue_info', { issueNumber: 17 });
702
- assert.notEqual(result.response.isError, true, result.text);
703
- }
704
- finally {
705
- await next.dispose(undefined);
706
- }
707
- }
708
- finally {
709
- release();
710
- await scope.join();
593
+ next.policy("tracked");
594
+ const nextConnection = await next.connect();
595
+ const result = await nextConnection.call("issue_info", { issueNumber: 17 });
596
+ assert.notEqual(result.response.isError, true, result.text);
597
+ } finally {
598
+ await next.dispose(void 0);
711
599
  }
712
- }, 5_000);
600
+ } finally {
601
+ release();
602
+ await scope.join();
603
+ }
604
+ }
605
+ );
713
606
  }
714
- test('scoped runtime setup failure after connection acquisition drains and restores only owned globals', async ({ signal, }) => {
607
+ test(
608
+ "scoped runtime setup failure after connection acquisition drains and restores only owned globals",
609
+ { tags: ["release"], timeout: 5e3 },
610
+ async ({ signal }) => {
715
611
  const scope = runtimeScope();
716
612
  scope.forward(signal);
717
613
  let f;
718
614
  try {
719
- await assert.rejects(prepareScope(scope, async () => {
720
- f = scope.acquire();
721
- f.policy('tracked');
722
- const c = await f.connect();
723
- const result = await c.call('issue_info', { issueNumber: 17 });
724
- assert.notEqual(result.response.isError, true, result.text);
725
- throw new Error('Controlled failure after owned connection');
726
- }), /Controlled failure after owned connection/u);
727
- assert.ok(f);
728
- assert.equal(existsSync(f.base), false);
729
- const next = inertTarget(signal);
730
- try {
731
- next.policy('tracked');
732
- const c = await next.connect();
733
- await scope.join();
734
- const result = await c.call('issue_info', { issueNumber: 17 });
735
- assert.notEqual(result.response.isError, true, result.text);
736
- }
737
- finally {
738
- await next.dispose(undefined);
739
- }
740
- }
741
- finally {
615
+ await assert.rejects(
616
+ prepareScope(scope, async () => {
617
+ f = scope.acquire();
618
+ f.policy("tracked");
619
+ const c = await f.connect();
620
+ const result = await c.call("issue_info", { issueNumber: 17 });
621
+ assert.notEqual(result.response.isError, true, result.text);
622
+ throw new Error("Controlled failure after owned connection");
623
+ }),
624
+ /Controlled failure after owned connection/u
625
+ );
626
+ assert.ok(f);
627
+ assert.equal(existsSync(f.base), false);
628
+ const next = inertTarget(signal);
629
+ try {
630
+ next.policy("tracked");
631
+ const c = await next.connect();
742
632
  await scope.join();
633
+ const result = await c.call("issue_info", { issueNumber: 17 });
634
+ assert.notEqual(result.response.isError, true, result.text);
635
+ } finally {
636
+ await next.dispose(void 0);
637
+ }
638
+ } finally {
639
+ await scope.join();
743
640
  }
744
- }, 5_000);
745
- async function lifecycleControl(f, runtime) {
746
- // Same archive, real npm and same environment; explicitly enabled scripts establish the lifecycle control.
747
- f.signal.throwIfAborted();
748
- execFileSync('npm', [
749
- 'install',
750
- '--prefix',
751
- join(f.base, 'control-install'),
752
- '--omit=dev',
753
- '--ignore-scripts=false',
754
- '--offline',
755
- '--no-audit',
756
- '--no-fund',
757
- '--package-lock=false',
758
- '--cache',
759
- join(f.base, 'control-cache'),
760
- '--userconfig',
761
- '/dev/null',
762
- '--globalconfig',
763
- join(f.base, 'fictional-global.npmrc'),
764
- runtime.archivePath,
765
- ], { env: process.env, cwd: f.base, timeout: 10_000, maxBuffer: 64 * 1024 });
766
- assert.match(readFileSync(runtime.lifecycleSentinel, 'utf8'), /executed/u);
767
- }
768
- async function prepareStage(scope) {
769
- const f = await setupStep(scope, 'fixture', () => scope.acquire());
770
- const runtime = await runtimeFixture(f, scope);
771
- await setupStep(scope, 'policy', () => f.policy('tracked'));
772
- const c = await setupStep(scope, 'connect', () => f.connect());
773
- const staged = await setupStep(scope, 'runtime_stage', () => c.call('runtime_stage', runtime.stage));
774
- assert.notEqual(staged.response.isError, true, staged.text);
775
- assert.ok(existsSync(runtime.cli));
776
- assert.equal(existsSync(runtime.lifecycleSentinel), false);
777
- assert.equal(existsSync(join(f.root, '.git/ai-delivery/runtime-admission.json')), false, 'Staging must not admit');
778
- return { f, c, runtime, staged };
779
- }
780
- // The edited-policy refusal has the same real staged prerequisites, then one
781
- // separately bounded tracked-to-edited transition (three Git calls, two controls).
782
- const editedAdmitSteps = [...stageSteps, ['edited policy', 5 * GIT_MS]];
783
- async function prepareEditedAdmit(scope) {
784
- const prepared = await prepareStage(scope);
785
- await setupStep(scope, 'edited policy', () => prepared.f.policy('edited'));
786
- return prepared;
787
- }
788
- async function observeEditedAdmit({ f, c, runtime, staged }) {
789
- const admitted = await c.call('runtime_admit', {
790
- ...runtime.common,
791
- authority: 'runtime:admit',
792
- stageId: staged.value.stageId,
793
- expectedPriorAdmissionSha256: null,
794
- });
795
- assert.equal(admitted.response.isError, true);
796
- assert.match(admitted.text, /Delivery requires an exact clean worktree\./u);
797
- assert.equal(existsSync(join(f.root, '.git/ai-delivery/runtime-admission.json')), false);
798
- assert.equal(existsSync(runtime.lifecycleSentinel), false);
799
- }
800
- for (const cancellation of ['operation deadline', 'forwarded cancellation'])
801
- test(`edited runtime_admit preparation ${cancellation} retains its real stage handler through drain stall and late settlement`, async ({ signal }) => {
802
- const scope = runtimeScope(editedAdmitSteps.map(([name, budget]) => [name, name === 'runtime_stage' ? 3_000 : budget]));
803
- const hook = new AbortController();
804
- scope.forward(signal);
805
- scope.forward(hook.signal);
806
- let release;
807
- let entered;
808
- const held = new Promise((resolve) => {
809
- release = resolve;
810
- });
811
- const reached = new Promise((resolve) => {
812
- entered = resolve;
813
- });
814
- const acquire = scope.acquire.bind(scope);
815
- let handlerSettled = false;
816
- scope.acquire = () => {
817
- const f = acquire();
818
- const get = f.rest.repos.get;
819
- f.rest.repos.get = async (input) => {
820
- entered();
821
- await held;
822
- handlerSettled = true;
823
- return get(input);
824
- };
825
- return f;
826
- };
827
- try {
828
- const preparing = prepareScope(scope, () => prepareEditedAdmit(scope)).then(() => new Error('Controlled stage handler was not held'), (error) => error);
829
- await Promise.race([
830
- reached,
831
- preparing.then((result) => {
832
- throw result;
833
- }),
834
- ]);
835
- const f = scope.fixture;
836
- process.stderr.write('EDITED_REFUSAL_HELD ' + JSON.stringify({ cancellation, phases: scope.phases }) + '\n');
837
- // This actual stage owns native supervision too: keep real timers while
838
- // its held handler reaches the shortened fault-only operation deadline.
839
- if (cancellation === 'forwarded cancellation')
840
- hook.abort(new Error('Controlled edited-refusal setup cancellation'));
841
- assert.match(String(await preparing), /drain-stall/u);
842
- assert.equal(handlerSettled, false, 'Rejected transport cannot establish handler settlement');
843
- assert.equal(scope.signal.aborted, true);
844
- assert.equal(existsSync(f.base), true, 'Stalled handler must retain fixture and globals');
845
- assert.throws(() => inertTarget(signal), /previous fixture must finish disposal/u);
846
- assert.ok(scope.phases.some((phase) => phase.name === 'setup:runtime_stage' &&
847
- phase.outcome === (cancellation === 'operation deadline' ? 'deadline' : 'cancelled')));
848
- assert.ok(scope.phases.some((phase) => phase.name === 'drain' && phase.outcome === 'drain-stall'));
849
- assert.equal(scope.phases.some((phase) => phase.name === 'setup:edited policy'), false);
850
- release();
851
- await scope.join();
852
- assert.equal(handlerSettled, true);
853
- assert.equal(scope.pending.size, 0);
854
- assert.equal(existsSync(f.base), false);
855
- process.stderr.write('EDITED_REFUSAL_OWNERSHIP ' +
856
- JSON.stringify({ cancellation, phases: scope.phases, rootRemoved: true }) +
857
- '\n');
858
- const next = inertTarget(signal);
859
- await next.dispose(undefined);
860
- }
861
- finally {
862
- release();
863
- await scope.join();
864
- }
865
- }, editedAdmitSteps.reduce((sum, [, budget]) => sum + budget, 0) + 2 * DRAIN_MS);
866
- async function prepareTransition(scope) {
867
- const f = await setupStep(scope, 'fixture', () => scope.acquire());
868
- await setupStep(scope, 'worktree', () => f.worktree());
869
- let c = await setupStep(scope, 'connect', () => f.connect());
870
- const runtime = await stageAndAdmit(f, c, scope);
871
- await setupStep(scope, 'close', () => c.close());
872
- c = await setupStep(scope, 'reconnect', () => f.connect({ runtimeEntryPath: runtime.cli }));
873
- return { f, c, runtime };
874
- }
875
- async function observeTransition(f, c, runtime, kind) {
876
- const row = {
877
- branch: 'issue/17',
878
- path: f.target,
879
- issueNumber: 17,
880
- identity: 'author',
881
- type: 'issue',
882
- status: 'active',
883
- createdAt: '2026-01-01',
884
- updatedAt: '2026-01-01',
885
- };
886
- writeFileSync(join(f.root, '.issue-cli/worktrees.json'), JSON.stringify({ worktrees: [row] }));
887
- f.policy(kind, f.target);
888
- const digest = digestValue('Owned synthetic closure placeholder; not operational attestation.');
889
- const content = {
890
- schemaVersion: 'ai-delivery.worktree-transition-plan@1',
891
- repository: 'example/widget',
892
- repoRoot: f.root,
893
- row,
894
- purpose: 'active-resume',
895
- disposition: 'retain',
896
- terminalPrNumber: null,
897
- head: { sha: f.head, tree: f.tree },
898
- lineage: [],
899
- remoteRefs: null,
900
- retainedHoldCommentIds: [],
901
- holdEvidence: [],
902
- inventory: [],
903
- inventoryId: digestValue([]),
904
- historicalProducer: 'UNKNOWN',
905
- closure: {
906
- family: 'public-ai-delivery-0.3.5-posix@1',
907
- admissionPath: join(f.base, 'retained-admission.json'),
908
- archivePath: runtime.archivePath,
909
- admission: runtime.admission,
910
- admissionBytesDigest: digest,
911
- producerDigest: digest,
912
- runManifestIds: [digest],
913
- },
914
- currentRuntime: runtime.admission,
915
- policyDigest: digestBytes(readFileSync(join(f.root, 'ai-delivery.policy.mjs'))),
916
- operator: { actorLogin: 'operator', credentialIdentity: 'user:42' },
917
- reviewerActor: 'reviewer[bot]',
918
- };
919
- const plan = WorktreeTransitionPlanSchema.parse({ ...content, planId: digestValue(content) });
920
- const planPath = join(f.base, 'transition.json');
921
- writeFileSync(planPath, JSON.stringify(plan), { mode: 0o600 });
922
- const result = await c.call('issue_worktree_transition_apply', {
923
- authority: 'worktree:transition',
924
- planPath,
925
- expectedPlanId: plan.planId,
926
- relinquishmentCommentId: 201,
927
- acceptanceCommentId: 202,
928
- });
929
- assert.equal(result.response.isError, true);
930
- assert.match(result.text, /Historical repository configuration binding is unsupported/u);
931
- assert.equal(existsSync(f.target), true);
932
- assert.equal(existsSync(join(f.root, '.git/ai-delivery/worktree-transitions', plan.planId.slice(7), 'intent.json')), false);
933
- assert.equal(existsSync(runtime.lifecycleSentinel), false);
934
- }
935
- for (const kind of ['tracked', 'edited']) {
936
- if (kind === 'tracked') {
937
- scopedRuntimeCase('public MCP runtime_stage asserts bounded first install and exact reuse/lifecycle control with tracked policy inert', stageSteps, prepareStage, async ({ f, c, runtime, staged }) => {
938
- const reused = await c.call('runtime_stage', runtime.stage);
939
- assert.notEqual(reused.response.isError, true, reused.text);
940
- assert.equal(reused.value.stageId, staged.value.stageId);
941
- assert.equal(reused.value.reused, true);
942
- await lifecycleControl(f, runtime);
943
- });
944
- scopedRuntimeCase('public MCP runtime_admit binds and reuses exact stage bytes after bounded real stage setup and leaves tracked policy inert', stageSteps, prepareStage, async ({ f, c, runtime, staged }) => {
945
- const args = {
946
- ...runtime.common,
947
- authority: 'runtime:admit',
948
- stageId: staged.value.stageId,
949
- expectedPriorAdmissionSha256: null,
950
- };
951
- const admitted = await c.call('runtime_admit', args);
952
- assert.notEqual(admitted.response.isError, true, admitted.text);
953
- const disk = JSON.parse(readFileSync(join(f.root, '.git/ai-delivery/runtime-admission.json'), 'utf8'));
954
- assert.deepEqual(disk, admitted.value.admission);
955
- const reused = await c.call('runtime_admit', args);
956
- assert.notEqual(reused.response.isError, true, reused.text);
957
- assert.equal(reused.value.reused, true);
958
- assert.deepEqual(reused.value.admission, disk);
959
- assert.equal(existsSync(runtime.lifecycleSentinel), false);
960
- });
961
- }
962
- else {
963
- test('public MCP runtime_stage refuses primary source edits and leaves edited policy inert', async ({ signal }) => {
964
- const f = inertTarget(signal);
965
- let c;
966
- try {
967
- const runtime = await runtimeFixture(f);
968
- f.policy('edited');
969
- c = await f.connect();
970
- const result = await c.call('runtime_stage', runtime.stage);
971
- assert.equal(result.response.isError, true);
972
- assert.match(result.text, /Delivery requires an exact clean worktree\./u);
973
- assert.equal(existsSync(runtime.common.runtimeDirectory), false);
974
- }
975
- finally {
976
- await f.dispose(c);
977
- }
978
- }, 15_000);
979
- scopedRuntimeCase('public MCP runtime_admit refuses primary source edits and leaves edited policy inert', editedAdmitSteps, prepareEditedAdmit, observeEditedAdmit);
980
- scopedRuntimeCase('edited runtime_admit refusal keeps bounded preparation outside its asserted-work budget', [['controlled before fixture', 10_000], ...editedAdmitSteps, ['controlled after staging', 10_000]], async (scope) => {
981
- const started = performance.now();
982
- await setupStep(scope, 'controlled before fixture', () => new Promise((resolve) => setTimeout(resolve, 8_000)));
983
- const prepared = await prepareEditedAdmit(scope);
984
- await setupStep(scope, 'controlled after staging', () => new Promise((resolve) => setTimeout(resolve, 8_000)));
985
- assert.ok(performance.now() - started > ASSERTED_MS, 'Preparation must exceed the original aggregate fuse');
986
- return prepared;
987
- }, observeEditedAdmit);
988
- }
989
- test(`public MCP investigation start ${kind === 'tracked' ? 'registers exact selected source' : 'refuses selected worktree edits'} with ${kind} policy`, async ({ signal, }) => {
990
- const f = inertTarget(signal);
991
- let c;
992
- try {
993
- f.worktree();
994
- f.policy(kind, f.target);
995
- assert.equal(fixtureGit(f.root, 'status', '--porcelain'), '');
996
- c = await f.connect();
997
- const args = { issueNumber: 17, investigationWorktree: f.target, expectedHeadSha: f.head };
998
- const result = await c.call('issue_start', args);
999
- if (kind === 'edited') {
1000
- assert.equal(result.response.isError, true);
1001
- assert.match(result.text, /Delivery requires an exact clean worktree\./u);
1002
- assert.equal(readInvestigationPreparation(f.root, 17), undefined);
1003
- }
1004
- else {
1005
- assert.notEqual(result.response.isError, true, result.text);
1006
- const preparation = readInvestigationPreparation(f.root, 17);
1007
- assert.equal(preparation.head.sha, f.head);
1008
- assert.equal(preparation.row.path, f.target);
1009
- assert.equal(f.comments.length, 1);
1010
- const again = await c.call('issue_start', args);
1011
- assert.notEqual(again.response.isError, true, again.text);
1012
- assert.equal(f.comments.length, 1);
1013
- assert.deepEqual(again.value.preparation, result.value.preparation);
1014
- }
1015
- }
1016
- finally {
1017
- await f.dispose(c);
1018
- }
1019
- }, 15_000);
1020
- test(`public MCP investigation finish ${kind === 'tracked' ? 'removes only acknowledged selected custody' : 'refuses selected worktree edits'} with ${kind} policy`, async ({ signal, }) => {
1021
- const f = inertTarget(signal);
1022
- let c;
1023
- try {
1024
- f.worktree();
1025
- f.policy('tracked', f.target);
1026
- c = await f.connect();
1027
- const start = await c.call('issue_start', {
1028
- issueNumber: 17,
1029
- investigationWorktree: f.target,
1030
- expectedHeadSha: f.head,
1031
- });
1032
- assert.notEqual(start.response.isError, true, start.text);
1033
- const preparation = readInvestigationPreparation(f.root, 17);
1034
- const resultPath = join(f.base, 'durable-result.txt');
1035
- writeFileSync(resultPath, 'Fictional result: unchanged source; all producers stopped.\n', { mode: 0o600 });
1036
- const resultDigest = digestBytes(readFileSync(resultPath));
1037
- f.state.issueState = 'closed';
1038
- f.addComment(201, investigationAuthorityBody(preparation, resultDigest));
1039
- f.addComment(202, investigationAcceptanceBody(preparation, resultDigest, 201), true);
1040
- if (kind === 'edited')
1041
- f.policy('edited', f.target);
1042
- assert.equal(fixtureGit(f.root, 'status', '--porcelain'), '');
1043
- const args = {
1044
- issueNumber: 17,
1045
- investigation: true,
1046
- resultPath,
1047
- authorityCommentId: 201,
1048
- acceptanceCommentId: 202,
1049
- };
1050
- const result = await c.call('issue_finish', args);
1051
- if (kind === 'edited') {
1052
- assert.equal(result.response.isError, true);
1053
- assert.match(result.text, /Delivery requires an exact clean worktree\./u);
1054
- assert.equal(existsSync(f.target), true);
1055
- }
1056
- else {
1057
- assert.notEqual(result.response.isError, true, result.text);
1058
- assert.equal(result.value.completed, true);
1059
- assert.equal(existsSync(f.target), false);
1060
- assert.equal(fixtureGit(f.root, 'rev-parse', 'refs/heads/issue/17'), f.head);
1061
- assert.equal(existsSync(resultPath), true);
1062
- const replay = await c.call('issue_finish', args);
1063
- assert.notEqual(replay.response.isError, true, replay.text);
1064
- assert.equal(replay.value.replayed, true);
1065
- }
1066
- assert.equal(f.state.closedCount, 0);
1067
- assert.equal(f.calls.some((value) => value.name === 'pulls.merge'), false);
1068
- }
1069
- finally {
1070
- await f.dispose(c);
1071
- }
1072
- }, 15_000);
1073
- test(`public MCP transition inspect inventories legacy custody and names reached guard with ${kind} policy`, async ({ signal, }) => {
1074
- const f = inertTarget(signal);
1075
- let c;
1076
- try {
1077
- f.worktree();
1078
- const row = {
1079
- branch: 'issue/17',
1080
- path: f.target,
1081
- issueNumber: 17,
1082
- identity: 'author',
1083
- type: 'issue',
1084
- status: 'active',
1085
- createdAt: '2026-01-01',
1086
- updatedAt: '2026-01-01',
1087
- };
1088
- writeFileSync(join(f.root, '.issue-cli/worktrees.json'), JSON.stringify({ worktrees: [row] }));
1089
- mkdirSync(join(f.root, '.issue-cli/issues/17'), { recursive: true });
1090
- writeFileSync(join(f.root, '.issue-cli/issues/17', 'fictional.txt'), 'Preserved original evidence.\n');
1091
- f.policy(kind, f.target);
1092
- c = await f.connect();
1093
- const result = await c.call('issue_worktree_transition_inspect', {
1094
- issueNumber: 17,
1095
- purpose: 'active-resume',
1096
- disposition: 'retain',
1097
- });
1098
- assert.notEqual(result.response.isError, true, result.text);
1099
- assert.equal(result.value.ready, false);
1100
- assert.equal(result.value.plan, null);
1101
- assert.ok(result.value.inventory.length > 0, 'Inventory owner must be reached');
1102
- assert.match(JSON.stringify(result.value.blockers), kind === 'tracked'
1103
- ? /Missing retained supported public producer admission\/archive/u
1104
- : /Delivery requires an exact clean worktree\./u);
1105
- assert.equal(existsSync(f.target), true);
1106
- assert.equal(readFileSync(join(f.root, '.issue-cli/issues/17/fictional.txt'), 'utf8'), 'Preserved original evidence.\n');
1107
- }
1108
- finally {
1109
- await f.dispose(c);
1110
- }
1111
- }, 15_000);
1112
- scopedRuntimeCase(`public MCP transition apply reaches unsupported historical binding after bounded stage/admit/reconnect without loading ${kind} policy`, transitionSteps, prepareTransition, async ({ f, c, runtime }) => observeTransition(f, c, runtime, kind));
1113
- }
1114
- //# sourceMappingURL=targetPolicyLocal.test.js.map
641
+ }
642
+ );
643
+ //# sourceMappingURL=targetPolicyLocal.test.js.map