@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
@@ -0,0 +1,747 @@
1
+ import assert from "node:assert/strict";
2
+ import {
3
+ chmodSync,
4
+ cpSync,
5
+ existsSync,
6
+ mkdirSync,
7
+ mkdtempSync,
8
+ readFileSync,
9
+ rmSync,
10
+ symlinkSync,
11
+ writeFileSync
12
+ } from "node:fs";
13
+ import { spawnSync } from "node:child_process";
14
+ import { createHash, generateKeyPairSync } from "node:crypto";
15
+ import { tmpdir } from "node:os";
16
+ import { join } from "node:path";
17
+ import { pathToFileURL } from "node:url";
18
+ import { test, vi } from "vitest";
19
+ import * as reviews from "./review.js";
20
+ import { createDeliveryGitHubClients } from "./github/client.js";
21
+ import { processSnapshot } from "./verification.js";
22
+ vi.mock("node:child_process", { spy: true });
23
+ import { loadDeliverySettings } from "./config/deliveryConfig.js";
24
+ const sha = "a".repeat(40);
25
+ const tree = "b".repeat(40);
26
+ function verdict() {
27
+ return {
28
+ schemaVersion: "ai-delivery.review-verdict@1",
29
+ verdict: "approve",
30
+ summary: "Reviewed the complete change independently.",
31
+ issueNumber: 17,
32
+ scope: { headSha: sha, headTree: tree, changedPaths: ["change.ts"] },
33
+ verificationReproduced: ["Reproduced the focused regression; integration remains unexecuted."],
34
+ requestedModel: "gpt-6-astra",
35
+ requestedEffort: "xhigh",
36
+ effectiveModel: "gpt-6-astra",
37
+ effectiveEffort: "xhigh",
38
+ elapsedMs: 100,
39
+ findings: [],
40
+ readOnly: true
41
+ };
42
+ }
43
+ function parser() {
44
+ const parse = Reflect.get(reviews, "parseReviewVerdict");
45
+ assert.equal(typeof parse, "function", "The verdict boundary must validate before authentication.");
46
+ return parse;
47
+ }
48
+ test("verdict validation reports missing metadata and rejects scope expansion inputs", () => {
49
+ const parse = parser();
50
+ assert.deepEqual(parse(JSON.stringify(verdict())), verdict());
51
+ for (const key of [
52
+ "verdict",
53
+ "scope",
54
+ "verificationReproduced",
55
+ "requestedModel",
56
+ "effectiveModel",
57
+ "elapsedMs",
58
+ "findings"
59
+ ]) {
60
+ const input = verdict();
61
+ delete input[key];
62
+ assert.throws(() => parse(input), new RegExp(key, "u"));
63
+ }
64
+ for (const input of [
65
+ { ...verdict(), elapsedMs: -1 },
66
+ { ...verdict(), summary: " " },
67
+ { ...verdict(), effectiveEffort: "unknown" },
68
+ { ...verdict(), unexpected: true }
69
+ ])
70
+ assert.throws(() => parse(input));
71
+ assert.throws(() => parse("{"), /JSON/u);
72
+ assert.deepEqual(
73
+ parse({ ...verdict(), scope: { ...verdict().scope, changedPaths: ["change.ts", "change.ts"] } }).scope.changedPaths,
74
+ ["change.ts"]
75
+ );
76
+ });
77
+ function commandFixture() {
78
+ const root = mkdtempSync(join(tmpdir(), "review-submit-cli-"));
79
+ const pkg = join(root, "package");
80
+ const bin = join(root, "bin");
81
+ mkdirSync(bin);
82
+ mkdirSync(pkg);
83
+ cpSync(join(process.cwd(), "dist"), join(pkg, "dist"), { recursive: true });
84
+ cpSync(join(process.cwd(), "package.json"), join(pkg, "package.json"));
85
+ symlinkSync(join(process.cwd(), "node_modules"), join(pkg, "node_modules"));
86
+ chmodSync(join(pkg, "dist", "cli.js"), 493);
87
+ symlinkSync(join(pkg, "dist", "cli.js"), join(bin, "ai-delivery"));
88
+ symlinkSync(process.execPath, join(bin, "node"));
89
+ const key = join(root, "fixture.pem");
90
+ writeFileSync(
91
+ key,
92
+ generateKeyPairSync("rsa", {
93
+ modulusLength: 2048,
94
+ privateKeyEncoding: { type: "pkcs8", format: "pem" },
95
+ publicKeyEncoding: { type: "spki", format: "pem" }
96
+ }).privateKey,
97
+ { mode: 384 }
98
+ );
99
+ const settings = join(root, "settings.json");
100
+ const helperCalls = join(root, "helper-calls.jsonl");
101
+ const helperScenario = join(root, "helper-scenario");
102
+ const helper = join(bin, "credential-helper");
103
+ const profile = (identity, appId, installationId, provider) => ({
104
+ authSource: "app",
105
+ identity,
106
+ appId,
107
+ installationId,
108
+ actorLogin: `fixture-${provider === "openai" ? "gpt" : "claude"}-reviewer[bot]`,
109
+ provider,
110
+ credentialSource: { type: "command", argv: [helper, identity], encoding: "base64", env: ["FIXTURE_HELPER_AUTH"] }
111
+ });
112
+ writeFileSync(
113
+ settings,
114
+ JSON.stringify({
115
+ schemaVersion: "ai-delivery.user@1",
116
+ project: 1,
117
+ checkoutRoots: [],
118
+ roles: {
119
+ author: { authSource: "personal", identity: "host-author", credentialEnv: { token: "AUTHOR_TOKEN" } },
120
+ reviewer: profile("gpt-reviewer", 101, 201, "openai")
121
+ },
122
+ reviewerProfiles: {
123
+ "claude-reviewer": profile("claude-reviewer", 102, 202, "anthropic"),
124
+ "custom-checker": profile("custom-checker", 101, 201, "openai")
125
+ },
126
+ pointsField: "Estimate",
127
+ priorityField: "Urgency",
128
+ statusField: "Flow",
129
+ statuses: { blocked: "Waiting", done: "Shipped", inProgress: "Active", todo: "Queued" },
130
+ issueTypes: ["Task"]
131
+ })
132
+ );
133
+ writeFileSync(
134
+ helper,
135
+ `#!${process.execPath}
136
+ const {readFileSync,appendFileSync}=require('node:fs');
137
+ appendFileSync(${JSON.stringify(helperCalls)},JSON.stringify({args:process.argv.slice(2),names:Object.keys(process.env)})+'\\n');
138
+ const scenario=readFileSync(${JSON.stringify(helperScenario)},'utf8');
139
+ if(scenario==='command-denied'){process.stderr.write('FICTIONAL_PRIVATE_HELPER_ERROR');process.exit(1);}
140
+ if(scenario==='command-malformed'){process.stdout.write('FICTIONAL_PRIVATE_HELPER_ERROR');process.exit(0);}
141
+ if(scenario==='command-overflow'){process.stdout.write('x'.repeat(70*1024));process.exit(0);}
142
+ if(scenario==='command-empty')process.exit(0);
143
+ if(scenario==='command-pem'){process.stdout.write(readFileSync(${JSON.stringify(key)},'utf8'));process.exit(0);}
144
+ process.stdout.write(readFileSync(${JSON.stringify(key)}).toString('base64')+'\\n');
145
+ `,
146
+ { mode: 493 }
147
+ );
148
+ const input = join(root, "verdict.json");
149
+ const preload = join(root, "transport.mjs");
150
+ const history = join(root, "history.json");
151
+ const calls = join(root, "calls.jsonl");
152
+ function run(options = {}) {
153
+ const provider = options.provider ?? "gpt";
154
+ const id = provider === "gpt" ? 101 : 102;
155
+ const identity = options.identity ?? `${provider}-reviewer`;
156
+ if (!options.repeat) {
157
+ rmSync(history, { force: true });
158
+ rmSync(calls, { force: true });
159
+ rmSync(helperCalls, { force: true });
160
+ }
161
+ writeFileSync(helperScenario, options.scenario ?? "normal");
162
+ writeFileSync(
163
+ input,
164
+ " \n" + JSON.stringify({
165
+ ...verdict(),
166
+ verdict: options.verdict ?? "approve",
167
+ requestedModel: provider === "gpt" ? "gpt-6-astra" : "claude-opus-4-6",
168
+ effectiveModel: provider === "gpt" ? "gpt-6-astra" : "claude-opus-4-6",
169
+ ...options.patch
170
+ }) + "\n"
171
+ );
172
+ writeFileSync(
173
+ preload,
174
+ `
175
+ import { appendFileSync, existsSync, readFileSync, writeFileSync } from 'node:fs';
176
+ import { syntheticDiscoveryClients } from ${JSON.stringify(pathToFileURL(join(pkg, "dist", "fixtures", "discovery.js")).href)};
177
+ const scenario=${JSON.stringify(options.scenario ?? "normal")};
178
+ const historyPath=${JSON.stringify(history)},calls=${JSON.stringify(calls)};
179
+ const reviews=existsSync(historyPath)?JSON.parse(readFileSync(historyPath,'utf8')):[];
180
+ let reads=0;
181
+ const response=(data,status=200)=>new Response(JSON.stringify(data),{status,headers:{'content-type':'application/json'}});
182
+ globalThis.fetch=async(input,init={})=>{
183
+ const url=new URL(input instanceof Request?input.url:String(input));
184
+ const method=init.method??'GET';
185
+ const body=typeof init.body==='string'?JSON.parse(init.body):{};
186
+ appendFileSync(calls,JSON.stringify({path:url.pathname,method,event:body.event})+'\\n');
187
+ if(url.hostname!=='api.github.com')throw new Error('Unexpected fixture destination');
188
+ if(url.pathname==='/graphql'){
189
+ const query=body.query;
190
+ if(query.includes('DeliveryClosingIssues'))return response({data:{repository:{nameWithOwner:'example/widget',pullRequest:{number:19,closingIssuesReferences:{nodes:[{number:17,repository:{nameWithOwner:'example/widget'}}],pageInfo:{hasNextPage:false,endCursor:null}}}}}});
191
+ if(query.includes('DeliveryReviewDecision'))return response({data:{repository:{pullRequest:{headRefOid:'${sha}',reviewDecision:scenario==='still-required'?'REVIEW_REQUIRED':reviews.at(-1)?.state==='CHANGES_REQUESTED'?'CHANGES_REQUESTED':'APPROVED'}}}});
192
+ if(query.includes('DeliveryReviewAccess'))return response({data:{repository:{pullRequest:{reviews:{nodes:reviews.map(r=>({fullDatabaseId:r.id,author:{login:r.user.login},authorCanPushToRepository:true,commit:{oid:r.commit_id},state:r.state}))}}}}});
193
+ return response({data:await syntheticDiscoveryClients().graphql(query,body.variables)});
194
+ }
195
+ if(url.pathname==='/user')return response({id:42,login:'fixture-author',type:'User'});
196
+ if(url.pathname.includes('/access_tokens'))return response({token:'ghs_fixture_${provider}',expires_at:'2999-01-01T00:00:00Z',permissions:{contents:'read',pull_requests:'write'}});
197
+ if(url.pathname==='/app')return response({id:scenario==='foreign-app'?999:${id},slug:scenario==='wrong-actor'?'other-app':'fixture-${provider}-reviewer'});
198
+ if(decodeURIComponent(url.pathname).endsWith('/git/ref/heads/issue/17'))return response({ref:'refs/heads/issue/17',object:{type:'commit',sha:scenario==='head-moved'?'${"f".repeat(40)}':'${sha}'}});
199
+ if(url.pathname.endsWith('/git/commits/${sha}'))return response({sha:'${sha}',tree:{sha:'${tree}'}});
200
+ if(url.pathname.includes('/compare/'))return response({merge_base_commit:{sha:'${"c".repeat(40)}'}});
201
+ if(url.pathname.endsWith('/pulls/19/files'))return response([{filename:scenario==='scope-mismatch'?'other.ts':'change.ts'}]);
202
+ if(url.pathname.endsWith('/pulls/19')){
203
+ reads++;
204
+ const moved=scenario==='head-moved'||scenario==='mid-head-moved'&&reads>=3||scenario==='post-head-moved'&&reviews.length>0;
205
+ return response({number:19,changed_files:1,state:'open',merged:false,draft:false,user:{login:scenario==='self-review'?'fixture-${provider}-reviewer[bot]':'fixture-author'},head:{sha:moved?'${"f".repeat(40)}':'${sha}',ref:'issue/17',repo:{full_name:'example/widget'}},base:{sha:'${"c".repeat(40)}',ref:'main',repo:{full_name:'example/widget'}}});
206
+ }
207
+ if(url.pathname.endsWith('/pulls/19/reviews')&&method==='GET')return response(reviews);
208
+ if(url.pathname.endsWith('/pulls/19/reviews')&&method==='POST'){
209
+ const review={id:41,state:body.event==='APPROVE'?'APPROVED':'CHANGES_REQUESTED',commit_id:body.commit_id,user:{login:'fixture-${provider}-reviewer[bot]'},html_url:'https://github.com/example/widget/pull/19#pullrequestreview-41',body:body.body};
210
+ reviews.push(review);writeFileSync(historyPath,JSON.stringify(reviews));
211
+ if(scenario==='ack-lost')throw new Error('Fictional acknowledgement loss');
212
+ return response(review,201);
213
+ }
214
+ if(url.pathname.endsWith('/pulls/19/reviews/41')){
215
+ if(scenario==='readback-failed')throw new Error('Fictional readback loss');
216
+ return response(reviews[0]);
217
+ }
218
+ throw new Error('Unexpected fixture request '+method+' '+url.pathname);
219
+ };
220
+ `
221
+ );
222
+ const env = {
223
+ HOME: root,
224
+ PATH: bin,
225
+ AI_DELIVERY_CONFIG: settings,
226
+ AUTHOR_TOKEN: "fixture_author",
227
+ LOGNAME: "fixture-user",
228
+ FIXTURE_HELPER_AUTH: "fixture_helper_auth",
229
+ UNUSED_APP_KEY: "FICTIONAL_UNUSED_PRIVATE_KEY",
230
+ SELECTED_KEY: readFileSync(key, "utf8"),
231
+ GH_PRIVATE_KEY_GPT_REVIEWER: readFileSync(key, "utf8"),
232
+ NODE_OPTIONS: `--import=${pathToFileURL(preload).href}`
233
+ };
234
+ const result = spawnSync(
235
+ "ai-delivery",
236
+ options.doctor ? ["review", "doctor", "--identity", identity] : [
237
+ "review",
238
+ "submit",
239
+ "--pr",
240
+ "19",
241
+ "--head",
242
+ sha,
243
+ "--identity",
244
+ identity,
245
+ "--verdict",
246
+ input,
247
+ "--repo",
248
+ "example/widget"
249
+ ],
250
+ { cwd: root, env, encoding: "utf8", maxBuffer: 256 * 1024 }
251
+ );
252
+ const requests = existsSync(calls) ? readFileSync(calls, "utf8").trim().split("\n").map((line) => JSON.parse(line)) : [];
253
+ const resolutions = existsSync(helperCalls) ? readFileSync(helperCalls, "utf8").trim().split("\n").map((line) => JSON.parse(line)) : [];
254
+ return {
255
+ ...result,
256
+ requests,
257
+ resolutions,
258
+ posts: requests.filter((r) => r.method === "POST" && r.path.endsWith("/reviews"))
259
+ };
260
+ }
261
+ return {
262
+ run,
263
+ root,
264
+ input,
265
+ history,
266
+ settings,
267
+ key,
268
+ helper,
269
+ setSource(source) {
270
+ const data = JSON.parse(readFileSync(settings, "utf8"));
271
+ if (source === void 0) delete data.roles.reviewer.credentialSource;
272
+ else data.roles.reviewer.credentialSource = source;
273
+ writeFileSync(settings, JSON.stringify(data));
274
+ },
275
+ cleanup: () => rmSync(root, { recursive: true, force: true })
276
+ };
277
+ }
278
+ test(
279
+ "stable package bin submits both provider verdicts with clean PATH and refreshes counted status",
280
+ { tags: ["release"] },
281
+ () => {
282
+ const fixture = commandFixture();
283
+ try {
284
+ for (const provider of ["gpt", "claude"])
285
+ for (const decision of ["approve", "request-changes"]) {
286
+ const result = fixture.run({ provider, verdict: decision });
287
+ assert.equal(result.status, 0, result.stderr);
288
+ const receipt = JSON.parse(result.stdout);
289
+ assert.equal(receipt.state, decision === "approve" ? "APPROVED" : "CHANGES_REQUESTED");
290
+ assert.equal(receipt.login, `fixture-${provider}-reviewer[bot]`);
291
+ assert.equal(receipt.artifact.reviewerIdentity, `${provider}-reviewer`);
292
+ assert.equal(receipt.requiredReview.status, decision === "approve" ? "satisfied" : "changes-requested");
293
+ assert.equal(result.posts.length, 1);
294
+ assert.equal(result.resolutions.length, 1);
295
+ assert.deepEqual(result.resolutions[0].args, [`${provider}-reviewer`]);
296
+ assert.equal(result.resolutions[0].names.includes("AUTHOR_TOKEN"), false);
297
+ assert.equal(result.resolutions[0].names.includes("UNUSED_APP_KEY"), false);
298
+ assert.equal(result.resolutions[0].names.includes("NODE_OPTIONS"), false);
299
+ assert.equal(
300
+ receipt.artifact.verdictFileSha256,
301
+ "sha256:" + createHash("sha256").update(readFileSync(fixture.input)).digest("hex")
302
+ );
303
+ const body = JSON.parse(readFileSync(fixture.history, "utf8"))[0].body;
304
+ for (const text of [
305
+ "Verdict-file SHA256: " + receipt.artifact.verdictFileSha256,
306
+ "Requested model/effort:",
307
+ "Effective model/effort:",
308
+ "Elapsed milliseconds: 100",
309
+ "Findings: none"
310
+ ])
311
+ assert.ok(body.includes(text), text);
312
+ assert.equal(body.includes("PRIVATE KEY"), false);
313
+ assert.equal(result.posts[0].event, decision === "approve" ? "APPROVE" : "REQUEST_CHANGES");
314
+ const retry = fixture.run({ provider, verdict: decision, repeat: true });
315
+ assert.equal(retry.status, 0, retry.stderr);
316
+ assert.equal(retry.posts.length, 1, "Retry must reuse the original review without a second POST.");
317
+ }
318
+ const inherited = fixture.run({ scenario: "still-required" });
319
+ assert.equal(inherited.status, 0, inherited.stderr);
320
+ assert.equal(
321
+ JSON.parse(inherited.stdout).requiredReview.status,
322
+ "still-required"
323
+ );
324
+ } finally {
325
+ fixture.cleanup();
326
+ }
327
+ }
328
+ );
329
+ test(
330
+ "actual command refuses stale scope/head/actor and invalid metadata without a review mutation",
331
+ { tags: ["release"] },
332
+ () => {
333
+ const fixture = commandFixture();
334
+ try {
335
+ for (const scenario of [
336
+ "head-moved",
337
+ "mid-head-moved",
338
+ "scope-mismatch",
339
+ "foreign-app",
340
+ "wrong-actor",
341
+ "self-review"
342
+ ]) {
343
+ const result = fixture.run({ scenario });
344
+ assert.notEqual(result.status, 0, scenario);
345
+ assert.equal(result.posts.length, 0, scenario);
346
+ if (["head-moved", "mid-head-moved", "scope-mismatch"].includes(scenario) && scenario !== "mid-head-moved")
347
+ assert.equal(result.resolutions.length, 0, scenario);
348
+ }
349
+ for (const options of [
350
+ { identity: "builder" },
351
+ { identity: "personal" },
352
+ { identity: "claude-reviewer" },
353
+ { patch: { effectiveModel: "claude-opus-4-6" } },
354
+ { patch: { elapsedMs: -1 } },
355
+ { patch: { requestedEffort: "" } }
356
+ ]) {
357
+ const result = fixture.run(options);
358
+ assert.notEqual(result.status, 0);
359
+ assert.equal(result.requests.length, 0, "Malformed verdict/identity must fail before any authentication.");
360
+ assert.equal(result.resolutions.length, 0);
361
+ }
362
+ } finally {
363
+ fixture.cleanup();
364
+ }
365
+ }
366
+ );
367
+ test(
368
+ "actual command preserves known or ambiguous mutation and reconciles acknowledgement loss",
369
+ { tags: ["release"] },
370
+ () => {
371
+ const fixture = commandFixture();
372
+ try {
373
+ for (const scenario of ["post-head-moved", "readback-failed", "ack-lost"]) {
374
+ const result = fixture.run({ scenario });
375
+ assert.notEqual(result.status, 0, result.stderr);
376
+ const pending = JSON.parse(result.stdout);
377
+ assert.equal(pending.status, "submission-unverified");
378
+ assert.equal(pending.submission.prNumber, 19);
379
+ assert.equal(result.posts.length, 1);
380
+ if (scenario !== "ack-lost") assert.equal(pending.submission.githubReviewId, 41);
381
+ if (scenario === "ack-lost") {
382
+ const retry = fixture.run({ repeat: true });
383
+ assert.equal(retry.status, 0, retry.stderr);
384
+ assert.equal(retry.posts.length, 1);
385
+ }
386
+ }
387
+ } finally {
388
+ fixture.cleanup();
389
+ }
390
+ }
391
+ );
392
+ test("explicit provider binding supports consumer names and rejects mismatched models or heads before auth", () => {
393
+ const build = Reflect.get(reviews, "buildReviewArtifact");
394
+ assert.equal(typeof build, "function");
395
+ const create = build;
396
+ const input = {
397
+ verdictFileSha256: "sha256:" + "d".repeat(64),
398
+ verdict: parser()(verdict()),
399
+ identity: "custom-checker",
400
+ provider: "openai",
401
+ expectedHead: sha,
402
+ prNumber: 19,
403
+ authorIdentity: "host-author"
404
+ };
405
+ assert.equal(create(input).reviewerIdentity, "custom-checker");
406
+ for (const patch of [
407
+ { identity: "host-author" },
408
+ { provider: "anthropic" },
409
+ { expectedHead: "c".repeat(40) },
410
+ { verdict: { ...verdict(), effectiveModel: "claude-opus-4-6" } },
411
+ { verdict: { ...verdict(), summary: "a".repeat(3e4) } }
412
+ ])
413
+ assert.throws(() => create({ ...input, ...patch }));
414
+ assert.equal(
415
+ create({
416
+ ...input,
417
+ provider: "anthropic",
418
+ verdict: {
419
+ ...verdict(),
420
+ verdict: "request-changes",
421
+ requestedModel: "claude-opus-4-6",
422
+ effectiveModel: "claude-opus-4-6",
423
+ requestedEffort: "high",
424
+ effectiveEffort: "high"
425
+ }
426
+ }).verdict,
427
+ "request-changes"
428
+ );
429
+ });
430
+ test("selected profile environment preserves machine selectors and excludes unused keys without secret fetch", async () => {
431
+ const root = mkdtempSync(join(tmpdir(), "review-source-settings-"));
432
+ const config = join(root, "settings.json");
433
+ const profile = (identity, id) => ({
434
+ authSource: "app",
435
+ identity,
436
+ appId: id,
437
+ installationId: id + 100,
438
+ actorLogin: `fixture-${identity}[bot]`,
439
+ provider: "openai",
440
+ credentialSource: { type: "env", variable: identity === "default-checker" ? "DEFAULT_KEY" : "SELECTED_KEY" }
441
+ });
442
+ writeFileSync(
443
+ config,
444
+ JSON.stringify({
445
+ schemaVersion: "ai-delivery.user@1",
446
+ project: 1,
447
+ checkoutRoots: [],
448
+ roles: {
449
+ author: { authSource: "personal", identity: "host-author", credentialEnv: { token: "GH_TOKEN" } },
450
+ reviewer: profile("default-checker", 101)
451
+ },
452
+ reviewerProfiles: { "custom-checker": profile("custom-checker", 102) }
453
+ })
454
+ );
455
+ vi.stubEnv("AI_DELIVERY_CONFIG", config);
456
+ const inherited = {
457
+ AI_DELIVERY_CONFIG: config,
458
+ HOME: root,
459
+ PATH: "/fixture/bin",
460
+ GH_HOST: "github.com",
461
+ GH_CONFIG_DIR: root,
462
+ UNUSED_KEY: "FICTIONAL_UNUSED_KEY",
463
+ DEFAULT_KEY: "FICTIONAL_DEFAULT_KEY",
464
+ SELECTED_KEY: "FICTIONAL_SELECTED_KEY",
465
+ NODE_OPTIONS: "--invalid"
466
+ };
467
+ try {
468
+ const selected = await Reflect.apply(loadDeliverySettings, void 0, [
469
+ void 0,
470
+ { reviewerIdentity: "custom-checker", env: inherited, prepareEnvironment: true }
471
+ ]);
472
+ assert.equal(selected.roles.reviewer.identity, "custom-checker");
473
+ for (const name of ["HOME", "PATH", "GH_HOST", "GH_CONFIG_DIR"])
474
+ assert.equal(selected.environment[name], inherited[name]);
475
+ assert.equal(selected.environment.SELECTED_KEY, "FICTIONAL_SELECTED_KEY");
476
+ for (const name of ["UNUSED_KEY", "DEFAULT_KEY", "NODE_OPTIONS"])
477
+ assert.equal(selected.environment[name], void 0);
478
+ assert.equal(inherited.UNUSED_KEY, "FICTIONAL_UNUSED_KEY");
479
+ const changed = JSON.parse(readFileSync(config, "utf8"));
480
+ changed.roles.reviewer.credentialSource.variable = "NEW_DEFAULT_KEY";
481
+ writeFileSync(config, JSON.stringify(changed));
482
+ const next = await loadDeliverySettings(void 0, {
483
+ reviewerIdentity: "custom-checker",
484
+ env: inherited,
485
+ prepareEnvironment: true
486
+ });
487
+ assert.notEqual(
488
+ next.sourceDigest,
489
+ selected.sourceDigest,
490
+ "The source digest must bind unselected key references too."
491
+ );
492
+ } finally {
493
+ vi.unstubAllEnvs();
494
+ rmSync(root, { recursive: true, force: true });
495
+ }
496
+ });
497
+ test(
498
+ "command denial, malformed output and overflow refuse without output leakage or writes",
499
+ { tags: ["release"] },
500
+ () => {
501
+ const fixture = commandFixture();
502
+ try {
503
+ for (const scenario of ["command-denied", "command-malformed", "command-overflow", "command-empty"]) {
504
+ const result = fixture.run({ scenario });
505
+ assert.notEqual(result.status, 0);
506
+ assert.equal(result.posts.length, 0);
507
+ assert.equal(result.resolutions.length, 1);
508
+ assert.equal((result.stdout + result.stderr).includes("FICTIONAL_PRIVATE_HELPER_ERROR"), false);
509
+ assert.equal((result.stdout + result.stderr).includes("fixture_helper_auth"), false);
510
+ }
511
+ } finally {
512
+ fixture.cleanup();
513
+ }
514
+ }
515
+ );
516
+ test(
517
+ "read-only doctor uses the selected source and actual App actor outside Git without review or project mutations",
518
+ { tags: ["release"] },
519
+ () => {
520
+ const fixture = commandFixture();
521
+ try {
522
+ const result = fixture.run({ identity: "custom-checker", doctor: true });
523
+ assert.equal(result.status, 0, result.stderr);
524
+ const output = JSON.parse(result.stdout);
525
+ assert.equal(output.identity, "custom-checker");
526
+ assert.equal(output.actorLogin, "fixture-gpt-reviewer[bot]");
527
+ assert.equal(result.resolutions.length, 1);
528
+ assert.deepEqual(result.resolutions[0].args, ["custom-checker"]);
529
+ assert.equal(
530
+ result.requests.some((r) => r.path === "/app"),
531
+ true
532
+ );
533
+ assert.equal(
534
+ result.requests.every((r) => r.path === "/app" || r.path.includes("/access_tokens")),
535
+ true
536
+ );
537
+ assert.equal(result.posts.length, 0);
538
+ const submit = fixture.run({ identity: "custom-checker" });
539
+ assert.equal(submit.status, 0, submit.stderr);
540
+ } finally {
541
+ fixture.cleanup();
542
+ }
543
+ }
544
+ );
545
+ test(
546
+ "credential process observation excludes ambient credentials and executable injection selectors",
547
+ { tags: ["release"] },
548
+ async () => {
549
+ const actual = await vi.importActual("node:child_process");
550
+ let observedEnv;
551
+ vi.mocked(spawnSync).mockImplementationOnce((command, args, options) => {
552
+ observedEnv = { ...options?.env };
553
+ return actual.spawnSync(command, args, options);
554
+ });
555
+ vi.stubEnv("GH_PRIVATE_KEY_UNSELECTED", "FICTIONAL_UNUSED_PRIVATE_KEY");
556
+ vi.stubEnv("AUTHOR_TOKEN", "FICTIONAL_AUTHOR_TOKEN");
557
+ try {
558
+ const calls = vi.mocked(spawnSync).mock.calls.length;
559
+ assert.ok(processSnapshot().has(process.pid));
560
+ const observed = vi.mocked(spawnSync).mock.calls.slice(calls);
561
+ assert.equal(observed.length, 1);
562
+ assert.deepEqual(observedEnv, { LC_ALL: "C" });
563
+ } finally {
564
+ vi.unstubAllEnvs();
565
+ }
566
+ }
567
+ );
568
+ test(
569
+ "selected env default, explicit env, protected file and command PEM all use the same stable bin",
570
+ { tags: ["release"] },
571
+ () => {
572
+ const fixture = commandFixture();
573
+ try {
574
+ for (const source of [
575
+ void 0,
576
+ { type: "env", variable: "SELECTED_KEY" },
577
+ { type: "file", path: fixture.key },
578
+ { type: "command", argv: [fixture.helper, "gpt-reviewer"], encoding: "pem" }
579
+ ]) {
580
+ fixture.setSource(source);
581
+ const result = fixture.run({
582
+ scenario: typeof source === "object" && source.type === "command" ? "command-pem" : "normal"
583
+ });
584
+ assert.equal(result.status, 0, result.stderr);
585
+ assert.equal(result.posts.length, 1);
586
+ assert.equal(result.resolutions.length, typeof source === "object" && source.type === "command" ? 1 : 0);
587
+ }
588
+ fixture.setSource({ type: "file", path: fixture.key });
589
+ chmodSync(fixture.key, 420);
590
+ const refused = fixture.run();
591
+ assert.notEqual(refused.status, 0);
592
+ assert.equal(refused.posts.length, 0);
593
+ assert.match(refused.stderr, /0600/u);
594
+ chmodSync(fixture.key, 384);
595
+ const link = join(fixture.root, "linked-key.pem");
596
+ symlinkSync(fixture.key, link);
597
+ fixture.setSource({ type: "file", path: link });
598
+ const symlink = fixture.run();
599
+ assert.notEqual(symlink.status, 0);
600
+ assert.equal(symlink.posts.length, 0);
601
+ fixture.setSource({ type: "command", argv: [join(fixture.root, "missing-helper")] });
602
+ const missing = fixture.run();
603
+ assert.notEqual(missing.status, 0);
604
+ assert.equal(missing.posts.length, 0);
605
+ assert.equal(missing.resolutions.length, 0, "An available env key must not become a fallback.");
606
+ } finally {
607
+ fixture.cleanup();
608
+ }
609
+ }
610
+ );
611
+ test(
612
+ "credential cancellation and response timeout await owned helper and descendant absence",
613
+ { tags: ["release"] },
614
+ async () => {
615
+ const fixture = commandFixture();
616
+ const pidFile = join(fixture.root, "owned-pids.json");
617
+ const helper = join(fixture.root, "blocking-helper.cjs");
618
+ writeFileSync(
619
+ helper,
620
+ `const {spawn}=require('node:child_process');const {writeFileSync}=require('node:fs');const child=spawn(process.execPath,['-e','setInterval(()=>{},1000)'],{stdio:'ignore'});writeFileSync(${JSON.stringify(pidFile)},JSON.stringify([process.pid,child.pid]));setInterval(()=>{},1000);`
621
+ );
622
+ fixture.setSource({ type: "command", argv: [process.execPath, helper] });
623
+ vi.stubEnv("AI_DELIVERY_CONFIG", fixture.settings);
624
+ try {
625
+ for (const cancel of [true, false]) {
626
+ rmSync(pidFile, { force: true });
627
+ const settings = await loadDeliverySettings(void 0, {
628
+ reviewerIdentity: "gpt-reviewer",
629
+ prepareEnvironment: true,
630
+ env: {
631
+ AI_DELIVERY_CONFIG: fixture.settings,
632
+ HOME: fixture.root,
633
+ PATH: "/usr/bin:/bin",
634
+ AUTHOR_TOKEN: "fixture_author",
635
+ LOGNAME: "fixture-user"
636
+ }
637
+ });
638
+ const controller = new AbortController();
639
+ const pending = createDeliveryGitHubClients({
640
+ config: settings,
641
+ identity: "gpt-reviewer",
642
+ role: "reviewer",
643
+ env: settings.environment,
644
+ signal: controller.signal
645
+ });
646
+ const rejected = assert.rejects(pending, cancel ? /cancelled/u : /timed out/u);
647
+ while (!existsSync(pidFile)) await new Promise((resolve) => setTimeout(resolve, 20));
648
+ if (cancel) {
649
+ await new Promise((resolve) => setTimeout(resolve, 1100));
650
+ controller.abort();
651
+ }
652
+ await rejected;
653
+ const snapshot = processSnapshot();
654
+ for (const pid of JSON.parse(readFileSync(pidFile, "utf8")))
655
+ assert.ok(!snapshot.has(pid) || snapshot.get(pid).status.startsWith("Z"), String(pid));
656
+ }
657
+ } finally {
658
+ vi.unstubAllEnvs();
659
+ fixture.cleanup();
660
+ }
661
+ }
662
+ );
663
+ test("ambiguous or reserved reviewer profiles fail closed before source selection", { tags: ["release"] }, async () => {
664
+ const fixture = commandFixture();
665
+ const original = readFileSync(fixture.settings, "utf8");
666
+ try {
667
+ for (const identity of ["gpt-reviewer", "personal-checker"]) {
668
+ const input = JSON.parse(original);
669
+ input.reviewerProfiles[identity] = { ...input.roles.reviewer, identity };
670
+ writeFileSync(fixture.settings, JSON.stringify(input));
671
+ await assert.rejects(
672
+ loadDeliverySettings(void 0, { env: { AI_DELIVERY_CONFIG: fixture.settings } }),
673
+ /distinct|personal|ambiguous/iu
674
+ );
675
+ }
676
+ } finally {
677
+ fixture.cleanup();
678
+ }
679
+ });
680
+ test.each(["unselected-profile-key", "implicit-author-selector"])(
681
+ "credential reference collisions refuse before helper launch: %s",
682
+ { tags: ["release"] },
683
+ (collision) => {
684
+ const fixture = commandFixture();
685
+ try {
686
+ const input = JSON.parse(readFileSync(fixture.settings, "utf8"));
687
+ if (collision === "unselected-profile-key") {
688
+ input.reviewerProfiles["other-key"] = {
689
+ ...input.roles.reviewer,
690
+ identity: "other-key",
691
+ credentialSource: { type: "env", variable: "UNUSED_APP_KEY" }
692
+ };
693
+ input.roles.reviewer.credentialSource = {
694
+ type: "command",
695
+ argv: [fixture.helper, "gpt-reviewer"],
696
+ encoding: "base64",
697
+ env: ["UNUSED_APP_KEY"]
698
+ };
699
+ } else input.roles.author.credentialEnv.token = "LOGNAME";
700
+ writeFileSync(fixture.settings, JSON.stringify(input));
701
+ const result = fixture.run({ doctor: true });
702
+ assert.notEqual(result.status, 0);
703
+ assert.equal(result.resolutions.length, 0);
704
+ assert.equal(result.requests.length, 0);
705
+ assert.equal((result.stdout + result.stderr).includes("FICTIONAL_UNUSED_PRIVATE_KEY"), false);
706
+ } finally {
707
+ fixture.cleanup();
708
+ }
709
+ }
710
+ );
711
+ test("verdict scope preserves valid Git filenames with edge whitespace", async () => {
712
+ const paths = [" change.ts "];
713
+ const parsed = reviews.parseReviewVerdict({ ...verdict(), scope: { ...verdict().scope, changedPaths: paths } });
714
+ assert.deepEqual(parsed.scope.changedPaths, paths);
715
+ const artifact = reviews.buildReviewArtifact({
716
+ verdict: parsed,
717
+ verdictFileSha256: "sha256:" + "d".repeat(64),
718
+ identity: "custom-checker",
719
+ provider: "openai",
720
+ authorIdentity: "host-author",
721
+ expectedHead: sha,
722
+ prNumber: 19
723
+ });
724
+ const context = {
725
+ config: { repository: "example/widget" },
726
+ repo: { owner: "example", repo: "widget" },
727
+ clients: {
728
+ rest: {
729
+ pulls: {
730
+ get: async () => ({
731
+ data: {
732
+ number: 19,
733
+ state: "open",
734
+ head: { sha, repo: { full_name: "example/widget" } },
735
+ base: { repo: { full_name: "example/widget" } },
736
+ changed_files: 1
737
+ }
738
+ }),
739
+ listFiles: async () => ({ data: paths.map((filename) => ({ filename })) })
740
+ },
741
+ git: { getCommit: async () => ({ data: { sha, tree: { sha: tree } } }) }
742
+ }
743
+ }
744
+ };
745
+ await reviews.validateReviewTarget(context, artifact, 19);
746
+ });
747
+ //# sourceMappingURL=reviewSubmit.test.js.map