@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,712 +1,828 @@
1
- import assert from 'node:assert/strict';
2
- import { chmodSync, mkdtempSync, mkdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
3
- import { tmpdir } from 'node:os';
4
- import { delimiter, join } from 'node:path';
5
- import { afterEach, beforeEach, test, vi } from 'vitest';
6
- import { createDeliveryGitHubClients, hasBranchProtectionAbsence, retainMachineAuthorForConfiguration, withAuthorGitToken, } from './client.js';
7
- import { resolveRepoFromRemote } from './repo.js';
8
- import { machineAuthorEligible, withMachineAuthorCredential } from './machineAuth.js';
9
- import { syntheticDiscoveryConfig, syntheticDiscoveryClients } from '../fixtures/discovery.js';
10
- import { contextFor } from '../dispatch.js';
11
- import { printCommandError } from '../cliResult.js';
12
- import { getMachineRequestDiagnostics } from '../errors.js';
13
- // This executable and all account/token/HTTP responses are fictional. No real
14
- // gh binary, home, configuration, keyring, GitHub session or network is used.
15
- let home = '';
16
- let binary = '';
1
+ import assert from "node:assert/strict";
2
+ import { chmodSync, mkdtempSync, mkdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { delimiter, join } from "node:path";
5
+ import { afterEach, beforeEach, test, vi } from "vitest";
6
+ import {
7
+ createDeliveryGitHubClients,
8
+ hasBranchProtectionAbsence,
9
+ retainMachineAuthorForConfiguration,
10
+ withAuthorGitToken
11
+ } from "./client.js";
12
+ import { resolveRepoFromRemote } from "./repo.js";
13
+ import { machineAuthorEligible, withMachineAuthorCredential } from "./machineAuth.js";
14
+ import { syntheticDiscoveryConfig, syntheticDiscoveryClients } from "../fixtures/discovery.js";
15
+ import { contextFor } from "../dispatch.js";
16
+ import { printCommandError } from "../cliResult.js";
17
+ import { getMachineRequestDiagnostics } from "../errors.js";
18
+ let home = "";
19
+ let binary = "";
17
20
  let env;
18
- const token = 'fictional_machine_token_not_a_real_credential';
19
- const account = { host: 'github.com', active: true, state: 'success', login: 'fixture-user' };
21
+ const token = "fictional_machine_token_not_a_real_credential";
22
+ const account = { host: "github.com", active: true, state: "success", login: "fixture-user" };
20
23
  const config = {
21
- roles: {
22
- author: { authSource: 'personal', identity: 'fixture-author', credentialEnv: { token: 'GH_TOKEN' } },
23
- reviewer: {
24
- identity: 'fixture-reviewer',
25
- credentialEnv: {
26
- appId: 'FIXTURE_REVIEW_APP_ID',
27
- installationId: 'FIXTURE_REVIEW_INSTALLATION_ID',
28
- privateKeyPath: 'FIXTURE_REVIEW_KEY_PATH',
29
- },
30
- },
31
- },
24
+ roles: {
25
+ author: { authSource: "personal", identity: "fixture-author", credentialEnv: { token: "GH_TOKEN" } },
26
+ reviewer: {
27
+ identity: "fixture-reviewer",
28
+ credentialEnv: {
29
+ appId: "FIXTURE_REVIEW_APP_ID",
30
+ installationId: "FIXTURE_REVIEW_INSTALLATION_ID",
31
+ privateKeyPath: "FIXTURE_REVIEW_KEY_PATH"
32
+ }
33
+ }
34
+ }
32
35
  };
33
36
  const appConfig = {
34
- roles: {
35
- ...config.roles,
36
- author: {
37
- identity: 'fixture-app-author',
38
- credentialEnv: {
39
- appId: 'FIXTURE_AUTHOR_APP_ID',
40
- installationId: 'FIXTURE_AUTHOR_INSTALLATION_ID',
41
- privateKeyPath: 'FIXTURE_AUTHOR_KEY_PATH',
42
- },
43
- },
44
- },
37
+ roles: {
38
+ ...config.roles,
39
+ author: {
40
+ identity: "fixture-app-author",
41
+ credentialEnv: {
42
+ appId: "FIXTURE_AUTHOR_APP_ID",
43
+ installationId: "FIXTURE_AUTHOR_INSTALLATION_ID",
44
+ privateKeyPath: "FIXTURE_AUTHOR_KEY_PATH"
45
+ }
46
+ }
47
+ }
45
48
  };
46
49
  function stub(input = {}) {
47
- writeFileSync(binary, `#!${process.execPath}
50
+ writeFileSync(
51
+ binary,
52
+ `#!${process.execPath}
48
53
  import { appendFileSync } from 'node:fs';
49
54
  const args=process.argv.slice(2);
50
- appendFileSync(${JSON.stringify(join(home, 'calls.jsonl'))},JSON.stringify({args,environmentNames:Object.keys(process.env).sort(),containsFictionalCredential:Object.values(process.env).includes(${JSON.stringify(token)}),coverageMatchesParent:process.env.NODE_V8_COVERAGE===${JSON.stringify(process.env.NODE_V8_COVERAGE)}})+'\\n');
55
+ appendFileSync(${JSON.stringify(join(home, "calls.jsonl"))},JSON.stringify({args,environmentNames:Object.keys(process.env).sort(),containsFictionalCredential:Object.values(process.env).includes(${JSON.stringify(token)}),coverageMatchesParent:process.env.NODE_V8_COVERAGE===${JSON.stringify(process.env.NODE_V8_COVERAGE)}})+'\\n');
51
56
  if(args[0]!=='auth')process.exit(91);
52
- if(args[1]===${JSON.stringify(input.fail ?? '')}){process.stderr.write('fictional_error_token_private_key_path_header');process.exit(1);}
57
+ if(args[1]===${JSON.stringify(input.fail ?? "")}){process.stderr.write('fictional_error_token_private_key_path_header');process.exit(1);}
53
58
  if(args[1]==='status'){
54
59
  if(JSON.stringify(args)!==JSON.stringify(['auth','status','--hostname','github.com','--active','--json','hosts']))process.exit(92);
55
- process.stdout.write(${JSON.stringify(input.statusRaw ?? JSON.stringify({ hosts: input.hosts ?? { 'github.com': [account] } }))});
60
+ process.stdout.write(${JSON.stringify(input.statusRaw ?? JSON.stringify({ hosts: input.hosts ?? { "github.com": [account] } }))});
56
61
  }else if(args[1]==='token'){
57
62
  if(JSON.stringify(args)!==JSON.stringify(['auth','token','--hostname','github.com','--user','fixture-user']))process.exit(93);
58
63
  process.stdout.write(${JSON.stringify(input.token ?? token)}+'\\n');
59
64
  }else process.exit(94);
60
- `, { mode: 0o755 });
65
+ `,
66
+ { mode: 493 }
67
+ );
61
68
  }
62
69
  function calls() {
63
- try {
64
- return readFileSync(join(home, 'calls.jsonl'), 'utf8')
65
- .trim()
66
- .split('\n')
67
- .map((line) => JSON.parse(line));
68
- }
69
- catch {
70
- return [];
71
- }
70
+ try {
71
+ return readFileSync(join(home, "calls.jsonl"), "utf8").trim().split("\n").map(
72
+ (line) => JSON.parse(line)
73
+ );
74
+ } catch {
75
+ return [];
76
+ }
72
77
  }
73
- function identity(status = 200, login = 'fixture-user', type = 'User') {
74
- vi.stubGlobal('fetch', async (input, init) => {
75
- const url = input instanceof Request ? input.url : String(input);
76
- assert.equal(url, 'https://api.github.com/user');
77
- assert.equal(init?.method ?? 'GET', 'GET');
78
- return new Response(JSON.stringify(status === 200 ? { id: 42, login, type } : { message: token }), {
79
- status,
80
- headers: { 'content-type': 'application/json', 'x-fictional-header': token },
81
- });
78
+ function identity(status = 200, login = "fixture-user", type = "User") {
79
+ vi.stubGlobal("fetch", async (input, init) => {
80
+ const url = input instanceof Request ? input.url : String(input);
81
+ assert.equal(url, "https://api.github.com/user");
82
+ assert.equal(init?.method ?? "GET", "GET");
83
+ return new Response(JSON.stringify(status === 200 ? { id: 42, login, type } : { message: token }), {
84
+ status,
85
+ headers: { "content-type": "application/json", "x-fictional-header": token }
82
86
  });
87
+ });
83
88
  }
84
89
  function author(selectedEnv = env) {
85
- return createDeliveryGitHubClients({ config, env: selectedEnv, role: 'author', identity: 'fixture-author' });
90
+ return createDeliveryGitHubClients({ config, env: selectedEnv, role: "author", identity: "fixture-author" });
86
91
  }
87
92
  async function safeFailure(operation, expected) {
88
- await assert.rejects(operation, (error) => {
89
- assert.ok(error instanceof Error);
90
- assert.match(error.message, expected);
91
- assert.ok(!JSON.stringify(error).includes(token));
92
- assert.ok(!error.message.includes('fictional_error_token_private_key_path_header'));
93
- assert.equal(error.cause, undefined);
94
- return true;
95
- });
93
+ await assert.rejects(operation, (error) => {
94
+ assert.ok(error instanceof Error);
95
+ assert.match(error.message, expected);
96
+ assert.ok(!JSON.stringify(error).includes(token));
97
+ assert.ok(!error.message.includes("fictional_error_token_private_key_path_header"));
98
+ assert.equal(error.cause, void 0);
99
+ return true;
100
+ });
96
101
  }
97
102
  function renderFailure(error) {
98
- const stderr = [];
99
- const stdout = [];
100
- const exitCode = process.exitCode;
101
- const err = vi.spyOn(process.stderr, 'write').mockImplementation((value) => {
102
- stderr.push(String(value));
103
- return true;
104
- });
105
- const out = vi.spyOn(process.stdout, 'write').mockImplementation((value) => {
106
- stdout.push(String(value));
107
- return true;
108
- });
109
- try {
110
- printCommandError(error);
111
- assert.equal(process.exitCode, 1);
112
- assert.deepEqual(stdout, []);
113
- return stderr.join('');
114
- }
115
- finally {
116
- err.mockRestore();
117
- out.mockRestore();
118
- process.exitCode = exitCode;
119
- }
103
+ const stderr = [];
104
+ const stdout = [];
105
+ const exitCode = process.exitCode;
106
+ const err = vi.spyOn(process.stderr, "write").mockImplementation((value) => {
107
+ stderr.push(String(value));
108
+ return true;
109
+ });
110
+ const out = vi.spyOn(process.stdout, "write").mockImplementation((value) => {
111
+ stdout.push(String(value));
112
+ return true;
113
+ });
114
+ try {
115
+ printCommandError(error);
116
+ assert.equal(process.exitCode, 1);
117
+ assert.deepEqual(stdout, []);
118
+ return stderr.join("");
119
+ } finally {
120
+ err.mockRestore();
121
+ out.mockRestore();
122
+ process.exitCode = exitCode;
123
+ }
120
124
  }
121
125
  beforeEach(() => {
122
- home = realpathSync(mkdtempSync(join(tmpdir(), 'ai-delivery-machine-session-')));
123
- const bin = join(home, 'bin');
124
- mkdirSync(bin);
125
- binary = join(bin, 'gh');
126
- env = { HOME: home, PATH: bin };
127
- stub();
128
- vi.stubGlobal('fetch', () => {
129
- throw new Error('Unexpected network in synthetic machine-session fixture.');
130
- });
126
+ home = realpathSync(mkdtempSync(join(tmpdir(), "ai-delivery-machine-session-")));
127
+ const bin = join(home, "bin");
128
+ mkdirSync(bin);
129
+ binary = join(bin, "gh");
130
+ env = { HOME: home, PATH: bin };
131
+ stub();
132
+ vi.stubGlobal("fetch", () => {
133
+ throw new Error("Unexpected network in synthetic machine-session fixture.");
134
+ });
131
135
  });
132
136
  afterEach(() => {
133
- vi.unstubAllGlobals();
134
- vi.unstubAllEnvs();
135
- rmSync(home, { recursive: true, force: true });
136
- });
137
- test('the absent conventional reference selects a pinned healthy account and proves its actual user', async () => {
138
- identity();
139
- const clients = await author();
140
- assert.equal(clients.authSource, 'personal');
141
- assert.equal(clients.credentialSource, `gh:github.com:${binary}`);
142
- assert.deepEqual(await clients.authenticatedAuthor(), { actorLogin: 'fixture-user', credentialIdentity: 'user:42' });
143
- assert.equal(await withAuthorGitToken(clients, (value) => value === token), true);
144
- assert.deepEqual(calls().map((x) => x.args), [
145
- ['auth', 'status', '--hostname', 'github.com', '--active', '--json', 'hosts'],
146
- ['auth', 'token', '--hostname', 'github.com', '--user', 'fixture-user'],
147
- ]);
148
- });
149
- test('inactive bad accounts do not invalidate or replace the healthy selected user', async () => {
150
- stub({
151
- hosts: { 'github.com': [account, { ...account, active: false, state: 'error', login: 'fixture-bot[bot]' }] },
152
- });
153
- identity();
154
- await author();
155
- assert.equal(calls().length, 2);
137
+ vi.unstubAllGlobals();
138
+ vi.unstubAllEnvs();
139
+ rmSync(home, { recursive: true, force: true });
140
+ });
141
+ test("the absent conventional reference selects a pinned healthy account and proves its actual user", async () => {
142
+ identity();
143
+ const clients = await author();
144
+ assert.equal(clients.authSource, "personal");
145
+ assert.equal(clients.credentialSource, `gh:github.com:${binary}`);
146
+ assert.deepEqual(await clients.authenticatedAuthor(), { actorLogin: "fixture-user", credentialIdentity: "user:42" });
147
+ assert.equal(await withAuthorGitToken(clients, (value) => value === token), true);
148
+ assert.deepEqual(
149
+ calls().map((x) => x.args),
150
+ [
151
+ ["auth", "status", "--hostname", "github.com", "--active", "--json", "hosts"],
152
+ ["auth", "token", "--hostname", "github.com", "--user", "fixture-user"]
153
+ ]
154
+ );
155
+ });
156
+ test("inactive bad accounts do not invalidate or replace the healthy selected user", async () => {
157
+ stub({
158
+ hosts: { "github.com": [account, { ...account, active: false, state: "error", login: "fixture-bot[bot]" }] }
159
+ });
160
+ identity();
161
+ await author();
162
+ assert.equal(calls().length, 2);
156
163
  });
157
164
  test.each([
158
- ['missing', {}],
159
- ['expired', { 'github.com': [{ ...account, state: 'error' }] }],
160
- ['timeout', { 'github.com': [{ ...account, state: 'timeout' }] }],
161
- ['no active', { 'github.com': [{ ...account, active: false }] }],
162
- ['ambiguous', { 'github.com': [account, { ...account, login: 'other-user' }] }],
163
- ['wrong host', { 'enterprise.example': [{ ...account, host: 'enterprise.example' }] }],
164
- ['mismatched entry host', { 'github.com': [{ ...account, host: 'enterprise.example' }] }],
165
- ['active bot', { 'github.com': [{ ...account, login: 'fixture-bot[bot]' }] }],
166
- ])('%s status is refused even though JSON status exits zero', async (_label, hosts) => {
167
- stub({ hosts });
168
- await safeFailure(author(), /no unambiguous healthy active/u);
169
- assert.equal(calls().length, 1);
170
- });
171
- test('malformed status never reaches token acquisition', async () => {
172
- stub({ statusRaw: '{invalid fictional token body' });
173
- await safeFailure(author(), /no unambiguous healthy active/u);
174
- assert.equal(calls().length, 1);
175
- });
176
- test.each(['status', 'token'])('%s failure with opaque stderr remains secret-safe', async (fail) => {
177
- stub({ fail });
178
- await safeFailure(author(), /Machine GitHub session/u);
179
- });
180
- test('empty token output is refused without user lookup', async () => {
181
- stub({ token: '' });
182
- await safeFailure(author(), /token is unavailable or invalid/u);
183
- });
184
- test('explicit token precedence does not call gh or preempt authentication readback', async () => {
185
- const clients = await author({ ...env, GH_TOKEN: 'fictional_explicit_token', GITHUB_TOKEN: token });
186
- assert.equal(clients.credentialSource, 'env:GH_TOKEN');
187
- assert.deepEqual(calls(), []);
188
- identity(401);
189
- await safeFailure(clients.authenticatedAuthor(), /Configured personal author token is invalid or expired/u);
190
- assert.deepEqual(calls(), []);
191
- });
192
- test.each(['', ' ', 'malformed token\nvalue'])('present invalid explicit input %j never falls back', async (value) => {
165
+ ["missing", {}],
166
+ ["expired", { "github.com": [{ ...account, state: "error" }] }],
167
+ ["timeout", { "github.com": [{ ...account, state: "timeout" }] }],
168
+ ["no active", { "github.com": [{ ...account, active: false }] }],
169
+ ["ambiguous", { "github.com": [account, { ...account, login: "other-user" }] }],
170
+ ["wrong host", { "enterprise.example": [{ ...account, host: "enterprise.example" }] }],
171
+ ["mismatched entry host", { "github.com": [{ ...account, host: "enterprise.example" }] }],
172
+ ["active bot", { "github.com": [{ ...account, login: "fixture-bot[bot]" }] }]
173
+ ])("%s status is refused even though JSON status exits zero", async (_label, hosts) => {
174
+ stub({ hosts });
175
+ await safeFailure(author(), /no unambiguous healthy active/u);
176
+ assert.equal(calls().length, 1);
177
+ });
178
+ test("malformed status never reaches token acquisition", async () => {
179
+ stub({ statusRaw: "{invalid fictional token body" });
180
+ await safeFailure(author(), /no unambiguous healthy active/u);
181
+ assert.equal(calls().length, 1);
182
+ });
183
+ test.each(["status", "token"])("%s failure with opaque stderr remains secret-safe", async (fail) => {
184
+ stub({ fail });
185
+ await safeFailure(author(), /Machine GitHub session/u);
186
+ });
187
+ test("empty token output is refused without user lookup", async () => {
188
+ stub({ token: "" });
189
+ await safeFailure(author(), /token is unavailable or invalid/u);
190
+ });
191
+ test("explicit token precedence does not call gh or preempt authentication readback", async () => {
192
+ const clients = await author({ ...env, GH_TOKEN: "fictional_explicit_token", GITHUB_TOKEN: token });
193
+ assert.equal(clients.credentialSource, "env:GH_TOKEN");
194
+ assert.deepEqual(calls(), []);
195
+ identity(401);
196
+ await safeFailure(clients.authenticatedAuthor(), /Configured personal author token is invalid or expired/u);
197
+ assert.deepEqual(calls(), []);
198
+ });
199
+ test.each(["", " ", "malformed token\nvalue"])(
200
+ "present invalid explicit input %j never falls back",
201
+ async (value) => {
193
202
  await safeFailure(author({ ...env, GH_TOKEN: value }), /Missing personal author token|malformed/u);
194
203
  assert.deepEqual(calls(), []);
195
- });
196
- test('an intentionally configured alternate reference does not use gh or unrelated tokens', async () => {
197
- await safeFailure(createDeliveryGitHubClients({
198
- config: {
199
- roles: {
200
- ...config.roles,
201
- author: { ...config.roles.author, credentialEnv: { token: 'ALTERNATE_AUTHOR_TOKEN' } },
202
- },
203
- },
204
- env: { ...env, GITHUB_TOKEN: token },
205
- identity: 'fixture-author',
206
- role: 'author',
207
- }), /Missing personal author token in ALTERNATE_AUTHOR_TOKEN/u);
208
- assert.deepEqual(calls(), []);
209
- });
210
- test('a missing explicit personal override for an App role refuses machine fallback', async () => {
211
- await safeFailure(createDeliveryGitHubClients({
212
- config: appConfig,
213
- env,
214
- role: 'author',
215
- identity: 'personal',
216
- personalAuth: { enabled: true },
217
- }), /no token was supplied/u);
218
- assert.deepEqual(calls(), []);
219
- });
220
- test('empty highest-precedence explicit override does not silently select a lower token', async () => {
221
- await safeFailure(createDeliveryGitHubClients({
222
- config: appConfig,
223
- env: { ...env, GH_TOKEN: token },
224
- role: 'author',
225
- identity: 'personal',
226
- personalAuth: { enabled: true, token: '' },
227
- }), /no token was supplied/u);
228
- assert.deepEqual(calls(), []);
204
+ }
205
+ );
206
+ test("an intentionally configured alternate reference does not use gh or unrelated tokens", async () => {
207
+ await safeFailure(
208
+ createDeliveryGitHubClients({
209
+ config: {
210
+ roles: {
211
+ ...config.roles,
212
+ author: { ...config.roles.author, credentialEnv: { token: "ALTERNATE_AUTHOR_TOKEN" } }
213
+ }
214
+ },
215
+ env: { ...env, GITHUB_TOKEN: token },
216
+ identity: "fixture-author",
217
+ role: "author"
218
+ }),
219
+ /Missing personal author token in ALTERNATE_AUTHOR_TOKEN/u
220
+ );
221
+ assert.deepEqual(calls(), []);
222
+ });
223
+ test("a missing explicit personal override for an App role refuses machine fallback", async () => {
224
+ await safeFailure(
225
+ createDeliveryGitHubClients({
226
+ config: appConfig,
227
+ env,
228
+ role: "author",
229
+ identity: "personal",
230
+ personalAuth: { enabled: true }
231
+ }),
232
+ /no token was supplied/u
233
+ );
234
+ assert.deepEqual(calls(), []);
235
+ });
236
+ test("empty highest-precedence explicit override does not silently select a lower token", async () => {
237
+ await safeFailure(
238
+ createDeliveryGitHubClients({
239
+ config: appConfig,
240
+ env: { ...env, GH_TOKEN: token },
241
+ role: "author",
242
+ identity: "personal",
243
+ personalAuth: { enabled: true, token: "" }
244
+ }),
245
+ /no token was supplied/u
246
+ );
247
+ assert.deepEqual(calls(), []);
229
248
  });
230
249
  test.each([
231
- ['other-user', 'User'],
232
- ['fixture-user', 'Bot'],
233
- ])('user %s/%s mismatch refuses before repository use', async (login, type) => {
234
- identity(200, login, type);
235
- await safeFailure(author(), /identity does not match/u);
236
- });
237
- test('expired selected machine token never switches to another session', async () => {
238
- identity(401);
239
- await safeFailure(author(), /Machine GitHub session is invalid or expired/u);
240
- assert.equal(calls().length, 2);
241
- });
242
- test('unsupported explicit enterprise host is refused before launching gh, even with a token', async () => {
243
- for (const selected of [env, { ...env, GH_TOKEN: token }])
244
- await safeFailure(author({ ...selected, GH_HOST: 'enterprise.example' }), /supports github.com only/u);
245
- assert.deepEqual(calls(), []);
246
- assert.throws(() => resolveRepoFromRemote(home, 'origin'), /remote/u);
247
- });
248
- test('GUI-style missing PATH and non-executable gh are actionable without shell fallback', async () => {
249
- await safeFailure(author({ HOME: home, PATH: `.${delimiter}${join(home, 'missing')}` }), /gh is unavailable/u);
250
- chmodSync(binary, 0o600);
251
- await safeFailure(author(), /gh is unavailable/u);
252
- assert.deepEqual(calls(), []);
253
- });
254
- test('explicit unavailable configuration/home selectors are not replaced by another profile', async () => {
255
- for (const name of ['HOME', 'GH_CONFIG_DIR', 'XDG_CONFIG_HOME'])
256
- await safeFailure(author({ ...env, [name]: join(home, 'absent') }), /selector is unavailable or invalid/u);
257
- assert.deepEqual(calls(), []);
258
- });
259
- test('only non-secret supported selectors reach gh; ambient tokens, injection and debugging are excluded', async () => {
260
- identity();
261
- await author({
262
- ...env,
263
- GITHUB_TOKEN: token,
264
- GH_ENTERPRISE_TOKEN: token,
265
- GITHUB_ENTERPRISE_TOKEN: token,
266
- UNRELATED_TOKEN: token,
267
- NODE_OPTIONS: token,
268
- NODE_V8_COVERAGE: token,
269
- GH_DEBUG: 'api',
270
- DEBUG: '1',
271
- GH_REPO: 'enterprise.example/other/repo',
272
- });
273
- for (const call of calls()) {
274
- assert.equal(call.containsFictionalCredential, false);
275
- assert.equal(call.coverageMatchesParent, true);
276
- // Node propagates its parent's coverage selector even with an explicit
277
- // child environment. Preserve canonical instrumentation, while proving
278
- // the supplied fictional selector/credential never reaches the child.
279
- // Darwin's additional platform name remains observed but unattributed.
280
- assert.deepEqual(call.environmentNames.filter((name) => !(process.platform === 'darwin' && name === '__CF_USER_TEXT_ENCODING') &&
281
- !(process.env.NODE_V8_COVERAGE !== undefined && name === 'NODE_V8_COVERAGE')), [
282
- 'GH_HOST',
283
- 'GH_NO_EXTENSION_UPDATE_NOTIFIER',
284
- 'GH_NO_UPDATE_NOTIFIER',
285
- 'GH_PROMPT_DISABLED',
286
- 'GH_TELEMETRY',
287
- 'HOME',
288
- 'PATH',
289
- ]);
250
+ ["other-user", "User"],
251
+ ["fixture-user", "Bot"]
252
+ ])("user %s/%s mismatch refuses before repository use", async (login, type) => {
253
+ identity(200, login, type);
254
+ await safeFailure(author(), /identity does not match/u);
255
+ });
256
+ test("expired selected machine token never switches to another session", async () => {
257
+ identity(401);
258
+ await safeFailure(author(), /Machine GitHub session is invalid or expired/u);
259
+ assert.equal(calls().length, 2);
260
+ });
261
+ test("unsupported explicit enterprise host is refused before launching gh, even with a token", async () => {
262
+ for (const selected of [env, { ...env, GH_TOKEN: token }])
263
+ await safeFailure(author({ ...selected, GH_HOST: "enterprise.example" }), /supports github.com only/u);
264
+ assert.deepEqual(calls(), []);
265
+ assert.throws(() => resolveRepoFromRemote(home, "origin"), /remote/u);
266
+ });
267
+ test("GUI-style missing PATH and non-executable gh are actionable without shell fallback", async () => {
268
+ await safeFailure(author({ HOME: home, PATH: `.${delimiter}${join(home, "missing")}` }), /gh is unavailable/u);
269
+ chmodSync(binary, 384);
270
+ await safeFailure(author(), /gh is unavailable/u);
271
+ assert.deepEqual(calls(), []);
272
+ });
273
+ test("explicit unavailable configuration/home selectors are not replaced by another profile", async () => {
274
+ for (const name of ["HOME", "GH_CONFIG_DIR", "XDG_CONFIG_HOME"])
275
+ await safeFailure(author({ ...env, [name]: join(home, "absent") }), /selector is unavailable or invalid/u);
276
+ assert.deepEqual(calls(), []);
277
+ });
278
+ test("only non-secret supported selectors reach gh; ambient tokens, injection and debugging are excluded", async () => {
279
+ identity();
280
+ await author({
281
+ ...env,
282
+ GITHUB_TOKEN: token,
283
+ GH_ENTERPRISE_TOKEN: token,
284
+ GITHUB_ENTERPRISE_TOKEN: token,
285
+ UNRELATED_TOKEN: token,
286
+ NODE_OPTIONS: token,
287
+ NODE_V8_COVERAGE: token,
288
+ GH_DEBUG: "api",
289
+ DEBUG: "1",
290
+ GH_REPO: "enterprise.example/other/repo"
291
+ });
292
+ for (const call of calls()) {
293
+ assert.equal(call.containsFictionalCredential, false);
294
+ assert.equal(call.coverageMatchesParent, true);
295
+ assert.deepEqual(
296
+ call.environmentNames.filter(
297
+ (name) => !(process.platform === "darwin" && name === "__CF_USER_TEXT_ENCODING") && !(process.env.NODE_V8_COVERAGE !== void 0 && name === "NODE_V8_COVERAGE")
298
+ ),
299
+ [
300
+ "GH_HOST",
301
+ "GH_NO_EXTENSION_UPDATE_NOTIFIER",
302
+ "GH_NO_UPDATE_NOTIFIER",
303
+ "GH_PROMPT_DISABLED",
304
+ "GH_TELEMETRY",
305
+ "HOME",
306
+ "PATH"
307
+ ]
308
+ );
309
+ }
310
+ });
311
+ test("repository read and simulated write permission refusal preserve status and never switch actors or leak upstream data", async () => {
312
+ identity();
313
+ const clients = await author();
314
+ vi.stubGlobal(
315
+ "fetch",
316
+ async () => new Response(JSON.stringify({ message: token }), {
317
+ status: 403,
318
+ headers: { "content-type": "application/json", "x-fictional-credential": token }
319
+ })
320
+ );
321
+ await safeFailure(
322
+ clients.rest.repos.get({ owner: "example", repo: "widget" }),
323
+ /cannot access the selected repository or operation/u
324
+ );
325
+ await safeFailure(
326
+ clients.rest.issues.create({ owner: "example", repo: "widget", title: "fictional denied operation" }),
327
+ /cannot access/u
328
+ );
329
+ await safeFailure(clients.graphql('query { repository(owner:"example",name:"widget") { id } }'), /cannot access/u);
330
+ assert.equal(calls().length, 2);
331
+ });
332
+ test("machine REST request diagnostics reach the real CLI renderer without private response data", async () => {
333
+ identity();
334
+ const clients = await author();
335
+ vi.stubGlobal(
336
+ "fetch",
337
+ async () => new Response(JSON.stringify({ message: token, private: "fictional_private_body" }), {
338
+ status: 500,
339
+ headers: {
340
+ "content-type": "application/json",
341
+ "x-github-request-id": "ABCD:1234:5678:9ABC:DEF0",
342
+ "x-private-header": token
343
+ }
344
+ })
345
+ );
346
+ await assert.rejects(
347
+ clients.rest.pulls.merge({ owner: "example", repo: "widget", pull_number: 17, sha: "a".repeat(40) }),
348
+ (error) => {
349
+ const output = renderFailure(error);
350
+ assert.equal(
351
+ output,
352
+ "ai-delivery: request phase=rest.request; endpoint=pulls.merge; status=500; code=UNKNOWN; requestId=ABCD:1234:5678:9ABC:DEF0\nai-delivery: Machine GitHub request failed; verify the selected account and repository access.\n"
353
+ );
354
+ assert.equal(output.includes(token), false);
355
+ assert.equal(output.includes("fictional_private"), false);
356
+ assert.equal(JSON.stringify(error).includes(token), false);
357
+ return true;
290
358
  }
359
+ );
360
+ assert.equal(calls().length, 2);
291
361
  });
292
- test('repository read and simulated write permission refusal preserve status and never switch actors or leak upstream data', async () => {
362
+ test.each(["rest", "graphql", "graphql200"])(
363
+ "numeric %s rate limits remain observable after a caller wraps the failure",
364
+ async (kind) => {
293
365
  identity();
294
366
  const clients = await author();
295
- vi.stubGlobal('fetch', async () => new Response(JSON.stringify({ message: token }), {
296
- status: 403,
297
- headers: { 'content-type': 'application/json', 'x-fictional-credential': token },
298
- }));
299
- await safeFailure(clients.rest.repos.get({ owner: 'example', repo: 'widget' }), /cannot access the selected repository or operation/u);
300
- // Fake HTTP refusal only: the stub has no issue/project/Git state or network.
301
- await safeFailure(clients.rest.issues.create({ owner: 'example', repo: 'widget', title: 'fictional denied operation' }), /cannot access/u);
302
- await safeFailure(clients.graphql('query { repository(owner:"example",name:"widget") { id } }'), /cannot access/u);
303
- assert.equal(calls().length, 2);
304
- });
305
- test('machine REST request diagnostics reach the real CLI renderer without private response data', async () => {
306
- identity();
307
- const clients = await author();
308
- vi.stubGlobal('fetch', async () => new Response(JSON.stringify({ message: token, private: 'fictional_private_body' }), {
309
- status: 500,
367
+ vi.stubGlobal(
368
+ "fetch",
369
+ async () => new Response(JSON.stringify({ message: token, errors: [{ message: token }] }), {
370
+ status: kind === "graphql200" ? 200 : 429,
310
371
  headers: {
311
- 'content-type': 'application/json',
312
- 'x-github-request-id': 'ABCD:1234:5678:9ABC:DEF0',
313
- 'x-private-header': token,
314
- },
315
- }));
316
- await assert.rejects(clients.rest.pulls.merge({ owner: 'example', repo: 'widget', pull_number: 17, sha: 'a'.repeat(40) }), (error) => {
317
- const output = renderFailure(error);
318
- assert.equal(output, 'ai-delivery: request phase=rest.request; endpoint=pulls.merge; status=500; code=UNKNOWN; requestId=ABCD:1234:5678:9ABC:DEF0\nai-delivery: Machine GitHub request failed; verify the selected account and repository access.\n');
319
- assert.equal(output.includes(token), false);
320
- assert.equal(output.includes('fictional_private'), false);
321
- assert.equal(JSON.stringify(error).includes(token), false);
322
- return true;
323
- });
324
- assert.equal(calls().length, 2);
325
- });
326
- test.each(['rest', 'graphql', 'graphql200'])('numeric %s rate limits remain observable after a caller wraps the failure', async (kind) => {
327
- identity();
328
- const clients = await author();
329
- vi.stubGlobal('fetch', async () => new Response(JSON.stringify({ message: token, errors: [{ message: token }] }), {
330
- status: kind === 'graphql200' ? 200 : 429,
331
- headers: {
332
- 'content-type': 'application/json',
333
- 'retry-after': '30',
334
- 'x-ratelimit-remaining': '0',
335
- 'x-ratelimit-reset': '1900000000',
336
- 'x-private-header': token,
337
- },
338
- }));
339
- await assert.rejects(kind === 'rest'
340
- ? clients.rest.issues.get({ owner: 'example', repo: 'widget', issue_number: 17 })
341
- : clients.graphql('query { viewer { login } }'));
372
+ "content-type": "application/json",
373
+ "retry-after": "30",
374
+ "x-ratelimit-remaining": "0",
375
+ "x-ratelimit-reset": "1900000000",
376
+ "x-private-header": token
377
+ }
378
+ })
379
+ );
380
+ await assert.rejects(
381
+ kind === "rest" ? clients.rest.issues.get({ owner: "example", repo: "widget", issue_number: 17 }) : clients.graphql("query { viewer { login } }")
382
+ );
342
383
  const retained = clients.rateLimitObservation?.();
343
- assert.deepEqual(retained, { retryAfterSeconds: 30, resetAtSeconds: 1900000000, remaining: 0 });
384
+ assert.deepEqual(retained, { retryAfterSeconds: 30, resetAtSeconds: 19e8, remaining: 0 });
344
385
  assert.doesNotMatch(JSON.stringify(retained), /fictional_|private|header/u);
345
- });
346
- test('only the original real machine protection failure proves absence for its selected client and target', async () => {
347
- identity();
348
- const clients = await author();
349
- const other = await author();
350
- vi.stubGlobal('fetch', async (input) => {
351
- const response = new Response(JSON.stringify({ message: 'Branch not protected', private: token }), {
352
- status: 404,
353
- headers: { 'content-type': 'application/json', 'x-private-header': token },
354
- });
355
- Object.defineProperty(response, 'url', { value: input instanceof Request ? input.url : String(input) });
356
- return response;
386
+ }
387
+ );
388
+ test("only the original real machine protection failure proves absence for its selected client and target", async () => {
389
+ identity();
390
+ const clients = await author();
391
+ const other = await author();
392
+ vi.stubGlobal("fetch", async (input) => {
393
+ const response = new Response(JSON.stringify({ message: "Branch not protected", private: token }), {
394
+ status: 404,
395
+ headers: { "content-type": "application/json", "x-private-header": token }
357
396
  });
358
- let absence;
359
- await assert.rejects(clients.rest.request('GET /repos/{owner}/{repo}/branches/{branch}/protection', {
360
- owner: 'example',
361
- repo: 'widget',
362
- branch: 'release/next',
363
- }), (error) => {
364
- absence = error;
365
- assert.equal(hasBranchProtectionAbsence(error, clients, { owner: 'example', repo: 'widget' }, 'release/next'), true);
366
- assert.equal(hasBranchProtectionAbsence(error, other, { owner: 'example', repo: 'widget' }, 'release/next'), false);
367
- assert.equal(hasBranchProtectionAbsence(error, clients, { owner: 'other', repo: 'widget' }, 'release/next'), false);
368
- assert.equal(hasBranchProtectionAbsence(error, clients, { owner: 'example', repo: 'other' }, 'release/next'), false);
369
- assert.equal(hasBranchProtectionAbsence(error, clients, { owner: 'example', repo: 'widget' }, 'main'), false);
370
- assert.equal(getMachineRequestDiagnostics(error)?.endpoint, 'UNKNOWN');
371
- assert.equal(renderFailure(error).includes(token), false);
372
- assert.equal(renderFailure(error).includes('Branch not protected'), false);
373
- assert.equal(JSON.stringify(error).includes(token), false);
374
- assert.equal(Object.hasOwn(error, 'response'), false);
375
- assert.equal(Object.hasOwn(error, 'cause'), false);
376
- return true;
377
- });
378
- const forged = {
379
- ...absence,
380
- status: 404,
381
- response: { status: 404, data: { message: 'Branch not protected' } },
382
- };
383
- assert.equal(hasBranchProtectionAbsence(forged, clients, { owner: 'example', repo: 'widget' }, 'release/next'), false);
384
- assert.equal(hasBranchProtectionAbsence(new Proxy(absence, {}), clients, { owner: 'example', repo: 'widget' }, 'release/next'), false);
385
- });
386
- test('machine absence classification rejects hostile and foreign request metadata without invoking accessors', async () => {
387
- identity();
388
- const clients = await author();
389
- const options = clients.rest.request.endpoint.merge('GET /repos/{owner}/{repo}/branches/{branch}/protection', {
390
- owner: 'example',
391
- repo: 'widget',
392
- branch: 'main',
393
- });
394
- const raw = {
395
- status: 404,
396
- response: {
397
- status: 404,
398
- url: 'https://api.github.com/repos/example/widget/branches/main/protection',
399
- data: { message: 'Branch not protected', private: token },
400
- },
401
- };
402
- let reads = 0;
403
- const getter = (source, key) => Object.defineProperty({ ...source }, key, {
404
- get() {
397
+ Object.defineProperty(response, "url", { value: input instanceof Request ? input.url : String(input) });
398
+ return response;
399
+ });
400
+ let absence;
401
+ await assert.rejects(
402
+ clients.rest.request("GET /repos/{owner}/{repo}/branches/{branch}/protection", {
403
+ owner: "example",
404
+ repo: "widget",
405
+ branch: "release/next"
406
+ }),
407
+ (error) => {
408
+ absence = error;
409
+ assert.equal(
410
+ hasBranchProtectionAbsence(error, clients, { owner: "example", repo: "widget" }, "release/next"),
411
+ true
412
+ );
413
+ assert.equal(
414
+ hasBranchProtectionAbsence(error, other, { owner: "example", repo: "widget" }, "release/next"),
415
+ false
416
+ );
417
+ assert.equal(
418
+ hasBranchProtectionAbsence(error, clients, { owner: "other", repo: "widget" }, "release/next"),
419
+ false
420
+ );
421
+ assert.equal(
422
+ hasBranchProtectionAbsence(error, clients, { owner: "example", repo: "other" }, "release/next"),
423
+ false
424
+ );
425
+ assert.equal(hasBranchProtectionAbsence(error, clients, { owner: "example", repo: "widget" }, "main"), false);
426
+ assert.equal(getMachineRequestDiagnostics(error)?.endpoint, "UNKNOWN");
427
+ assert.equal(renderFailure(error).includes(token), false);
428
+ assert.equal(renderFailure(error).includes("Branch not protected"), false);
429
+ assert.equal(JSON.stringify(error).includes(token), false);
430
+ assert.equal(Object.hasOwn(error, "response"), false);
431
+ assert.equal(Object.hasOwn(error, "cause"), false);
432
+ return true;
433
+ }
434
+ );
435
+ const forged = {
436
+ ...absence,
437
+ status: 404,
438
+ response: { status: 404, data: { message: "Branch not protected" } }
439
+ };
440
+ assert.equal(
441
+ hasBranchProtectionAbsence(forged, clients, { owner: "example", repo: "widget" }, "release/next"),
442
+ false
443
+ );
444
+ assert.equal(
445
+ hasBranchProtectionAbsence(
446
+ new Proxy(absence, {}),
447
+ clients,
448
+ { owner: "example", repo: "widget" },
449
+ "release/next"
450
+ ),
451
+ false
452
+ );
453
+ });
454
+ test("machine absence classification rejects hostile and foreign request metadata without invoking accessors", async () => {
455
+ identity();
456
+ const clients = await author();
457
+ const options = clients.rest.request.endpoint.merge("GET /repos/{owner}/{repo}/branches/{branch}/protection", {
458
+ owner: "example",
459
+ repo: "widget",
460
+ branch: "main"
461
+ });
462
+ const raw = {
463
+ status: 404,
464
+ response: {
465
+ status: 404,
466
+ url: "https://api.github.com/repos/example/widget/branches/main/protection",
467
+ data: { message: "Branch not protected", private: token }
468
+ }
469
+ };
470
+ let reads = 0;
471
+ const getter = (source, key) => Object.defineProperty({ ...source }, key, {
472
+ get() {
473
+ reads++;
474
+ throw new Error(token);
475
+ }
476
+ });
477
+ const cases = [
478
+ [{ status: 404, response: { status: 404, data: { message: "Not Found" } } }, options],
479
+ [{ ...raw, status: 403 }, options],
480
+ [{ ...raw, response: { ...raw.response, status: 403 } }, options],
481
+ [getter(raw, "status"), options],
482
+ [getter(raw, "response"), options],
483
+ [{ ...raw, response: getter(raw.response, "status") }, options],
484
+ [{ ...raw, response: { ...raw.response, data: getter(raw.response.data, "message") } }, options],
485
+ [new Proxy(raw, {}), options],
486
+ [{ ...raw, response: new Proxy(raw.response, {}) }, options],
487
+ [{ ...raw, response: getter(raw.response, "url") }, options],
488
+ [
489
+ {
490
+ ...raw,
491
+ response: { ...raw.response, url: "https://foreign.invalid/repos/example/widget/branches/main/protection" }
492
+ },
493
+ options
494
+ ],
495
+ [
496
+ {
497
+ ...raw,
498
+ response: { ...raw.response, url: "https://api.github.com/repos/other/widget/branches/main/protection" }
499
+ },
500
+ options
501
+ ],
502
+ [
503
+ {
504
+ ...raw,
505
+ response: { ...raw.response, url: "https://api.github.com/repos/example/widget/branches/other/protection" }
506
+ },
507
+ options
508
+ ],
509
+ [raw, { ...options, method: "POST" }],
510
+ [raw, { ...options, url: "/repos/example/widget/issues/17" }],
511
+ [raw, { ...options, baseUrl: "https://foreign.invalid" }],
512
+ [raw, { ...options, url: "https://foreign.invalid/repos/example/widget/branches/main/protection" }],
513
+ [raw, { ...options, url: "https://private@api.github.com/repos/example/widget/branches/main/protection" }],
514
+ [raw, { ...options, url: "/repos/example/widget/branches/main/protection?private=value" }],
515
+ [raw, getter(options, "url")],
516
+ [raw, getter(options, "branch")],
517
+ [
518
+ raw,
519
+ {
520
+ ...options,
521
+ branch: {
522
+ toString() {
405
523
  reads++;
406
- throw new Error(token);
524
+ return "main";
525
+ }
526
+ }
527
+ }
528
+ ]
529
+ ];
530
+ for (const [error, metadata] of cases) {
531
+ const request = { ...options };
532
+ await assert.rejects(
533
+ clients.rest.hook(
534
+ "request",
535
+ async () => {
536
+ Object.defineProperties(request, Object.getOwnPropertyDescriptors(metadata));
537
+ throw error;
407
538
  },
408
- });
409
- const cases = [
410
- [{ status: 404, response: { status: 404, data: { message: 'Not Found' } } }, options],
411
- [{ ...raw, status: 403 }, options],
412
- [{ ...raw, response: { ...raw.response, status: 403 } }, options],
413
- [getter(raw, 'status'), options],
414
- [getter(raw, 'response'), options],
415
- [{ ...raw, response: getter(raw.response, 'status') }, options],
416
- [{ ...raw, response: { ...raw.response, data: getter(raw.response.data, 'message') } }, options],
417
- [new Proxy(raw, {}), options],
418
- [{ ...raw, response: new Proxy(raw.response, {}) }, options],
419
- [{ ...raw, response: getter(raw.response, 'url') }, options],
420
- [
421
- {
422
- ...raw,
423
- response: { ...raw.response, url: 'https://foreign.invalid/repos/example/widget/branches/main/protection' },
424
- },
425
- options,
426
- ],
427
- [
428
- {
429
- ...raw,
430
- response: { ...raw.response, url: 'https://api.github.com/repos/other/widget/branches/main/protection' },
431
- },
432
- options,
433
- ],
434
- [
435
- {
436
- ...raw,
437
- response: { ...raw.response, url: 'https://api.github.com/repos/example/widget/branches/other/protection' },
438
- },
439
- options,
440
- ],
441
- [raw, { ...options, method: 'POST' }],
442
- [raw, { ...options, url: '/repos/example/widget/issues/17' }],
443
- [raw, { ...options, baseUrl: 'https://foreign.invalid' }],
444
- [raw, { ...options, url: 'https://foreign.invalid/repos/example/widget/branches/main/protection' }],
445
- [raw, { ...options, url: 'https://private@api.github.com/repos/example/widget/branches/main/protection' }],
446
- [raw, { ...options, url: '/repos/example/widget/branches/main/protection?private=value' }],
447
- [raw, getter(options, 'url')],
448
- [raw, getter(options, 'branch')],
449
- [
450
- raw,
451
- {
452
- ...options,
453
- branch: {
454
- toString() {
455
- reads++;
456
- return 'main';
457
- },
458
- },
459
- },
460
- ],
461
- ];
462
- for (const [error, metadata] of cases) {
463
- const request = { ...options };
464
- await assert.rejects(clients.rest.hook('request', async () => {
465
- // Introduce hostile metadata at the external request failure boundary,
466
- // after the SDK has prepared auth from the ordinary request options.
467
- Object.defineProperties(request, Object.getOwnPropertyDescriptors(metadata));
468
- throw error;
469
- }, request), (safe) => {
470
- assert.equal(hasBranchProtectionAbsence(safe, clients, { owner: 'example', repo: 'widget' }, 'main'), false);
471
- assert.equal(renderFailure(safe).includes(token), false);
472
- assert.equal(JSON.stringify(safe).includes(token), false);
473
- return true;
474
- });
475
- }
476
- assert.equal(reads, 0);
477
- });
478
- test.each([500, 200])('machine GraphQL status %s diagnostics reach the real CLI renderer without query or data errors', async (status) => {
539
+ request
540
+ ),
541
+ (safe) => {
542
+ assert.equal(hasBranchProtectionAbsence(safe, clients, { owner: "example", repo: "widget" }, "main"), false);
543
+ assert.equal(renderFailure(safe).includes(token), false);
544
+ assert.equal(JSON.stringify(safe).includes(token), false);
545
+ return true;
546
+ }
547
+ );
548
+ }
549
+ assert.equal(reads, 0);
550
+ });
551
+ test.each([500, 200])(
552
+ "machine GraphQL status %s diagnostics reach the real CLI renderer without query or data errors",
553
+ async (status) => {
479
554
  identity();
480
555
  const clients = await author();
481
- vi.stubGlobal('fetch', async () => new Response(JSON.stringify({
482
- errors: [{ message: token, extensions: { private: 'fictional_private_data' } }],
483
- data: { private: token },
484
- }), {
485
- status,
486
- headers: {
487
- 'content-type': 'application/json',
488
- 'x-github-request-id': 'ABCD:1234:5678:9ABC:DEF0',
489
- 'x-private-header': token,
490
- },
491
- }));
492
- await assert.rejects(clients.graphql('query FictionalPrivate($value:String!){ repository(owner:$value,name:"widget"){id} }', {
493
- value: 'fictional_private_variables',
494
- }), (error) => {
556
+ vi.stubGlobal(
557
+ "fetch",
558
+ async () => new Response(
559
+ JSON.stringify({
560
+ errors: [{ message: token, extensions: { private: "fictional_private_data" } }],
561
+ data: { private: token }
562
+ }),
563
+ {
564
+ status,
565
+ headers: {
566
+ "content-type": "application/json",
567
+ "x-github-request-id": "ABCD:1234:5678:9ABC:DEF0",
568
+ "x-private-header": token
569
+ }
570
+ }
571
+ )
572
+ );
573
+ await assert.rejects(
574
+ clients.graphql('query FictionalPrivate($value:String!){ repository(owner:$value,name:"widget"){id} }', {
575
+ value: "fictional_private_variables"
576
+ }),
577
+ (error) => {
495
578
  const output = renderFailure(error);
496
- assert.equal(output, `ai-delivery: request phase=graphql.request; endpoint=graphql; status=${status === 500 ? '500' : 'UNKNOWN'}; code=UNKNOWN; requestId=ABCD:1234:5678:9ABC:DEF0\nai-delivery: Machine GitHub request failed; verify the selected account and repository access.\n`);
579
+ assert.equal(
580
+ output,
581
+ `ai-delivery: request phase=graphql.request; endpoint=graphql; status=${status === 500 ? "500" : "UNKNOWN"}; code=UNKNOWN; requestId=ABCD:1234:5678:9ABC:DEF0
582
+ ai-delivery: Machine GitHub request failed; verify the selected account and repository access.
583
+ `
584
+ );
497
585
  assert.equal(output.includes(token), false);
498
- assert.equal(output.includes('fictional_private'), false);
499
- assert.equal(output.includes('FictionalPrivate'), false);
586
+ assert.equal(output.includes("fictional_private"), false);
587
+ assert.equal(output.includes("FictionalPrivate"), false);
500
588
  assert.equal(JSON.stringify(error).includes(token), false);
501
589
  return true;
502
- });
503
- assert.equal(calls().length, 2);
504
- });
505
- test('real machine REST failures classify only the finite guarded-delivery endpoints', async () => {
506
- identity();
507
- const clients = await author();
508
- vi.stubGlobal('fetch', async () => new Response(JSON.stringify({ message: token }), {
509
- status: 500,
510
- headers: { 'content-type': 'application/json' },
511
- }));
512
- const operations = [
513
- ['pulls.merge', () => clients.rest.pulls.merge({ owner: 'example', repo: 'widget', pull_number: 17 })],
514
- ['pulls.get', () => clients.rest.pulls.get({ owner: 'example', repo: 'widget', pull_number: 17 })],
515
- ['pulls.listReviews', () => clients.rest.pulls.listReviews({ owner: 'example', repo: 'widget', pull_number: 17 })],
516
- [
517
- 'pulls.getReview',
518
- () => clients.rest.pulls.getReview({ owner: 'example', repo: 'widget', pull_number: 17, review_id: 42 }),
519
- ],
520
- [
521
- 'git.getCommit',
522
- () => clients.rest.git.getCommit({ owner: 'example', repo: 'widget', commit_sha: 'a'.repeat(40) }),
523
- ],
524
- ['git.getRef', () => clients.rest.git.getRef({ owner: 'example', repo: 'widget', ref: 'heads/issue/17' })],
525
- ['issues.get', () => clients.rest.issues.get({ owner: 'example', repo: 'widget', issue_number: 17 })],
526
- [
527
- 'issues.update',
528
- () => clients.rest.issues.update({ owner: 'example', repo: 'widget', issue_number: 17, title: 'fictional title' }),
529
- ],
530
- ];
531
- for (const [endpoint, operation] of operations)
532
- await assert.rejects(operation(), (error) => {
533
- assert.equal(getMachineRequestDiagnostics(error)?.endpoint, endpoint);
534
- assert.equal(getMachineRequestDiagnostics(error)?.requestId, 'UNKNOWN');
535
- assert.equal(renderFailure(error).includes(token), false);
536
- return true;
537
- });
590
+ }
591
+ );
538
592
  assert.equal(calls().length, 2);
593
+ }
594
+ );
595
+ test("real machine REST failures classify only the finite guarded-delivery endpoints", async () => {
596
+ identity();
597
+ const clients = await author();
598
+ vi.stubGlobal(
599
+ "fetch",
600
+ async () => new Response(JSON.stringify({ message: token }), {
601
+ status: 500,
602
+ headers: { "content-type": "application/json" }
603
+ })
604
+ );
605
+ const operations = [
606
+ ["pulls.merge", () => clients.rest.pulls.merge({ owner: "example", repo: "widget", pull_number: 17 })],
607
+ ["pulls.get", () => clients.rest.pulls.get({ owner: "example", repo: "widget", pull_number: 17 })],
608
+ ["pulls.listReviews", () => clients.rest.pulls.listReviews({ owner: "example", repo: "widget", pull_number: 17 })],
609
+ [
610
+ "pulls.getReview",
611
+ () => clients.rest.pulls.getReview({ owner: "example", repo: "widget", pull_number: 17, review_id: 42 })
612
+ ],
613
+ [
614
+ "git.getCommit",
615
+ () => clients.rest.git.getCommit({ owner: "example", repo: "widget", commit_sha: "a".repeat(40) })
616
+ ],
617
+ ["git.getRef", () => clients.rest.git.getRef({ owner: "example", repo: "widget", ref: "heads/issue/17" })],
618
+ ["issues.get", () => clients.rest.issues.get({ owner: "example", repo: "widget", issue_number: 17 })],
619
+ [
620
+ "issues.update",
621
+ () => clients.rest.issues.update({ owner: "example", repo: "widget", issue_number: 17, title: "fictional title" })
622
+ ]
623
+ ];
624
+ for (const [endpoint, operation] of operations)
625
+ await assert.rejects(operation(), (error) => {
626
+ assert.equal(getMachineRequestDiagnostics(error)?.endpoint, endpoint);
627
+ assert.equal(getMachineRequestDiagnostics(error)?.requestId, "UNKNOWN");
628
+ assert.equal(renderFailure(error).includes(token), false);
629
+ return true;
630
+ });
631
+ assert.equal(calls().length, 2);
539
632
  });
540
- test.each([401, 403, 404])('machine status %s preserves exact refusal and legacy status through the real renderer', async (status) => {
633
+ test.each([401, 403, 404])(
634
+ "machine status %s preserves exact refusal and legacy status through the real renderer",
635
+ async (status) => {
541
636
  identity();
542
637
  const clients = await author();
543
- vi.stubGlobal('fetch', async () => new Response(JSON.stringify({ message: token }), { status, headers: { 'content-type': 'application/json' } }));
544
- await assert.rejects(clients.rest.pulls.get({ owner: 'example', repo: 'widget', pull_number: 17 }), (error) => {
638
+ vi.stubGlobal(
639
+ "fetch",
640
+ async () => new Response(JSON.stringify({ message: token }), { status, headers: { "content-type": "application/json" } })
641
+ );
642
+ await assert.rejects(
643
+ clients.rest.pulls.get({ owner: "example", repo: "widget", pull_number: 17 }),
644
+ (error) => {
545
645
  assert.ok(error instanceof Error);
546
- assert.equal(Reflect.get(error, 'status'), status);
547
- const message = status === 401
548
- ? 'Machine GitHub session is invalid or expired; verify the selected github.com account.'
549
- : 'Machine GitHub session cannot access the selected repository or operation; verify its existing permissions.';
646
+ assert.equal(Reflect.get(error, "status"), status);
647
+ const message = status === 401 ? "Machine GitHub session is invalid or expired; verify the selected github.com account." : "Machine GitHub session cannot access the selected repository or operation; verify its existing permissions.";
550
648
  assert.equal(error.message, message);
551
- assert.equal(renderFailure(error).trimEnd().split('\n').at(-1), `ai-delivery: ${message}`);
649
+ assert.equal(renderFailure(error).trimEnd().split("\n").at(-1), `ai-delivery: ${message}`);
552
650
  return true;
553
- });
651
+ }
652
+ );
554
653
  assert.equal(calls().length, 2);
555
- });
654
+ }
655
+ );
556
656
  test.each([
557
- 'GET https://private.invalid/fictional_private_path',
558
- 'DELETE /repos/example/widget/pulls/17/merge',
559
- 'GET /repos/example/widget/pulls/17/unknown',
560
- ])('unknown request %s remains UNKNOWN and withholds arbitrary metadata', async (route) => {
561
- identity();
562
- const clients = await author();
563
- vi.stubGlobal('fetch', async () => new Response(JSON.stringify({ message: token, code: 'ENOTFOUND', cause: token }), {
564
- status: 500,
565
- headers: { 'content-type': 'application/json', 'x-github-request-id': token, 'x-private-header': token },
566
- }));
567
- await assert.rejects(clients.rest.request(route), (error) => {
568
- assert.deepEqual(getMachineRequestDiagnostics(error), {
569
- phase: 'rest.request',
570
- endpoint: 'UNKNOWN',
571
- status: 500,
572
- code: 'UNKNOWN',
573
- requestId: 'UNKNOWN',
574
- });
575
- const output = renderFailure(error);
576
- assert.equal(output.includes(token), false);
577
- assert.equal(output.includes('fictional_private_path'), false);
578
- assert.equal(output.includes('ENOTFOUND'), false);
579
- return true;
657
+ "GET https://private.invalid/fictional_private_path",
658
+ "DELETE /repos/example/widget/pulls/17/merge",
659
+ "GET /repos/example/widget/pulls/17/unknown"
660
+ ])("unknown request %s remains UNKNOWN and withholds arbitrary metadata", async (route) => {
661
+ identity();
662
+ const clients = await author();
663
+ vi.stubGlobal(
664
+ "fetch",
665
+ async () => new Response(JSON.stringify({ message: token, code: "ENOTFOUND", cause: token }), {
666
+ status: 500,
667
+ headers: { "content-type": "application/json", "x-github-request-id": token, "x-private-header": token }
668
+ })
669
+ );
670
+ await assert.rejects(clients.rest.request(route), (error) => {
671
+ assert.deepEqual(getMachineRequestDiagnostics(error), {
672
+ phase: "rest.request",
673
+ endpoint: "UNKNOWN",
674
+ status: 500,
675
+ code: "UNKNOWN",
676
+ requestId: "UNKNOWN"
580
677
  });
581
- });
582
- test('repository discovery and subsequent command construction retain one selected machine account', async () => {
583
- identity();
584
- const clients = await author();
585
- const original = process.env;
586
- process.env = env;
587
- try {
588
- retainMachineAuthorForConfiguration(config, clients);
589
- stub({ hosts: { 'github.com': [{ ...account, login: 'other-user' }] } });
590
- assert.equal(await createDeliveryGitHubClients({ config, identity: 'fixture-author', role: 'author' }), clients);
591
- assert.equal(calls().length, 2);
592
- const explicit = await createDeliveryGitHubClients({
593
- config: structuredClone(config),
594
- identity: 'fixture-author',
595
- role: 'author',
596
- env: { GH_TOKEN: 'fictional_override' },
597
- });
598
- assert.equal(explicit.credentialSource, 'env:GH_TOKEN');
599
- }
600
- finally {
601
- process.env = original;
602
- }
603
- });
604
- test('the existing delivery context uses one central machine account across actual configuration discovery and operation', async () => {
605
- const settingsPath = join(home, 'user.json');
606
- writeFileSync(settingsPath, JSON.stringify({
607
- schemaVersion: 'ai-delivery.user@1',
608
- roles: config.roles,
609
- project: 1,
610
- checkoutRoots: [],
611
- pointsField: 'Estimate',
612
- priorityField: 'Urgency',
613
- statusField: 'Flow',
614
- statuses: syntheticDiscoveryConfig.native.project.statuses,
615
- }));
616
- const requests = [];
617
- vi.stubGlobal('fetch', async (input, init) => {
618
- const url = input instanceof Request ? input.url : String(input);
619
- requests.push(url);
620
- if (url === 'https://api.github.com/user')
621
- return new Response(JSON.stringify({ id: 42, login: 'fixture-user', type: 'User' }), {
622
- headers: { 'content-type': 'application/json' },
623
- });
624
- assert.equal(url, 'https://api.github.com/graphql');
625
- assert.equal(typeof init?.body, 'string');
626
- const body = JSON.parse(init.body);
627
- assert.ok(!body.query.includes('mutation'));
628
- // A later active-account change cannot silently rebind this command.
629
- stub({ hosts: { 'github.com': [{ ...account, login: 'other-user' }] } });
630
- return new Response(JSON.stringify({ data: await syntheticDiscoveryClients().graphql(body.query) }), {
631
- headers: { 'content-type': 'application/json' },
632
- });
678
+ const output = renderFailure(error);
679
+ assert.equal(output.includes(token), false);
680
+ assert.equal(output.includes("fictional_private_path"), false);
681
+ assert.equal(output.includes("ENOTFOUND"), false);
682
+ return true;
683
+ });
684
+ });
685
+ test("repository discovery and subsequent command construction retain one selected machine account", async () => {
686
+ identity();
687
+ const clients = await author();
688
+ const original = process.env;
689
+ process.env = env;
690
+ try {
691
+ retainMachineAuthorForConfiguration(config, clients);
692
+ stub({ hosts: { "github.com": [{ ...account, login: "other-user" }] } });
693
+ assert.equal(await createDeliveryGitHubClients({ config, identity: "fixture-author", role: "author" }), clients);
694
+ assert.equal(calls().length, 2);
695
+ const explicit = await createDeliveryGitHubClients({
696
+ config: structuredClone(config),
697
+ identity: "fixture-author",
698
+ role: "author",
699
+ env: { GH_TOKEN: "fictional_override" }
633
700
  });
634
- const original = process.env;
635
- process.env = { ...env, AI_DELIVERY_CONFIG: settingsPath };
636
- try {
637
- const context = await contextFor({ repoRoot: home, repo: 'example/widget' }, 'config:resolve');
638
- assert.equal(context.config.repository, 'example/widget');
639
- assert.equal(context.clients.credentialSource, `gh:github.com:${binary}`);
640
- assert.deepEqual(await context.clients.authenticatedAuthor(), {
641
- actorLogin: 'fixture-user',
642
- credentialIdentity: 'user:42',
643
- });
644
- assert.equal(calls().length, 2);
645
- assert.ok(requests.includes('https://api.github.com/graphql'));
646
- }
647
- finally {
648
- process.env = original;
649
- }
650
- });
651
- test.each(['GH_TOKEN', 'GH_CONFIG_DIR'])('a %s change during actual repository discovery cannot replace the selected machine author', async (selector) => {
652
- const settingsPath = join(home, 'user.json');
653
- const alternateProfile = join(home, 'alternate-profile');
701
+ assert.equal(explicit.credentialSource, "env:GH_TOKEN");
702
+ } finally {
703
+ process.env = original;
704
+ }
705
+ });
706
+ test("the existing delivery context uses one central machine account across actual configuration discovery and operation", async () => {
707
+ const settingsPath = join(home, "user.json");
708
+ writeFileSync(
709
+ settingsPath,
710
+ JSON.stringify({
711
+ schemaVersion: "ai-delivery.user@1",
712
+ roles: config.roles,
713
+ project: 1,
714
+ checkoutRoots: [],
715
+ pointsField: "Estimate",
716
+ priorityField: "Urgency",
717
+ statusField: "Flow",
718
+ statuses: syntheticDiscoveryConfig.native.project.statuses
719
+ })
720
+ );
721
+ const requests = [];
722
+ vi.stubGlobal("fetch", async (input, init) => {
723
+ const url = input instanceof Request ? input.url : String(input);
724
+ requests.push(url);
725
+ if (url === "https://api.github.com/user")
726
+ return new Response(JSON.stringify({ id: 42, login: "fixture-user", type: "User" }), {
727
+ headers: { "content-type": "application/json" }
728
+ });
729
+ assert.equal(url, "https://api.github.com/graphql");
730
+ assert.equal(typeof init?.body, "string");
731
+ const body = JSON.parse(init.body);
732
+ assert.ok(!body.query.includes("mutation"));
733
+ stub({ hosts: { "github.com": [{ ...account, login: "other-user" }] } });
734
+ return new Response(JSON.stringify({ data: await syntheticDiscoveryClients().graphql(body.query) }), {
735
+ headers: { "content-type": "application/json" }
736
+ });
737
+ });
738
+ const original = process.env;
739
+ process.env = { ...env, AI_DELIVERY_CONFIG: settingsPath };
740
+ try {
741
+ const context = await contextFor({ repoRoot: home, repo: "example/widget" }, "config:resolve");
742
+ assert.equal(context.config.repository, "example/widget");
743
+ assert.equal(context.clients.credentialSource, `gh:github.com:${binary}`);
744
+ assert.deepEqual(await context.clients.authenticatedAuthor(), {
745
+ actorLogin: "fixture-user",
746
+ credentialIdentity: "user:42"
747
+ });
748
+ assert.equal(calls().length, 2);
749
+ assert.ok(requests.includes("https://api.github.com/graphql"));
750
+ } finally {
751
+ process.env = original;
752
+ }
753
+ });
754
+ test.each(["GH_TOKEN", "GH_CONFIG_DIR"])(
755
+ "a %s change during actual repository discovery cannot replace the selected machine author",
756
+ async (selector) => {
757
+ const settingsPath = join(home, "user.json");
758
+ const alternateProfile = join(home, "alternate-profile");
654
759
  mkdirSync(alternateProfile);
655
- writeFileSync(settingsPath, JSON.stringify({
656
- schemaVersion: 'ai-delivery.user@1',
760
+ writeFileSync(
761
+ settingsPath,
762
+ JSON.stringify({
763
+ schemaVersion: "ai-delivery.user@1",
657
764
  roles: config.roles,
658
765
  project: 1,
659
766
  checkoutRoots: [],
660
- pointsField: 'Estimate',
661
- priorityField: 'Urgency',
662
- statusField: 'Flow',
663
- statuses: syntheticDiscoveryConfig.native.project.statuses,
664
- }));
767
+ pointsField: "Estimate",
768
+ priorityField: "Urgency",
769
+ statusField: "Flow",
770
+ statuses: syntheticDiscoveryConfig.native.project.statuses
771
+ })
772
+ );
665
773
  const requests = [];
666
- vi.stubGlobal('fetch', async (input, init) => {
667
- const url = input instanceof Request ? input.url : String(input);
668
- requests.push(url);
669
- if (url === 'https://api.github.com/user')
670
- return new Response(JSON.stringify({ id: 42, login: 'fixture-user', type: 'User' }), {
671
- headers: { 'content-type': 'application/json' },
672
- });
673
- assert.equal(url, 'https://api.github.com/graphql');
674
- assert.equal(typeof init?.body, 'string');
675
- const body = JSON.parse(init.body);
676
- assert.ok(!body.query.includes('mutation'));
677
- process.env[selector] = selector === 'GH_TOKEN' ? 'fictional_alternate_author_token' : alternateProfile;
678
- return new Response(JSON.stringify({ data: await syntheticDiscoveryClients().graphql(body.query) }), {
679
- headers: { 'content-type': 'application/json' },
774
+ vi.stubGlobal("fetch", async (input, init) => {
775
+ const url = input instanceof Request ? input.url : String(input);
776
+ requests.push(url);
777
+ if (url === "https://api.github.com/user")
778
+ return new Response(JSON.stringify({ id: 42, login: "fixture-user", type: "User" }), {
779
+ headers: { "content-type": "application/json" }
680
780
  });
781
+ assert.equal(url, "https://api.github.com/graphql");
782
+ assert.equal(typeof init?.body, "string");
783
+ const body = JSON.parse(init.body);
784
+ assert.ok(!body.query.includes("mutation"));
785
+ process.env[selector] = selector === "GH_TOKEN" ? "fictional_alternate_author_token" : alternateProfile;
786
+ return new Response(JSON.stringify({ data: await syntheticDiscoveryClients().graphql(body.query) }), {
787
+ headers: { "content-type": "application/json" }
788
+ });
681
789
  });
682
790
  const original = process.env;
683
791
  process.env = { ...env, AI_DELIVERY_CONFIG: settingsPath };
684
792
  try {
685
- await safeFailure(contextFor({ repoRoot: home, repo: 'example/widget' }, 'config:resolve'), /environment changed after repository selection/u);
686
- assert.equal(requests.filter((url) => url === 'https://api.github.com/user').length, 1);
687
- assert.ok(requests.includes('https://api.github.com/graphql'));
688
- assert.equal(calls().length, 2);
689
- }
690
- finally {
691
- process.env = original;
793
+ await safeFailure(
794
+ contextFor({ repoRoot: home, repo: "example/widget" }, "config:resolve"),
795
+ /environment changed after repository selection/u
796
+ );
797
+ assert.equal(requests.filter((url) => url === "https://api.github.com/user").length, 1);
798
+ assert.ok(requests.includes("https://api.github.com/graphql"));
799
+ assert.equal(calls().length, 2);
800
+ } finally {
801
+ process.env = original;
692
802
  }
693
- });
694
- test('reviewer and App author missing credentials never inherit the personal session', async () => {
695
- for (const role of ['author', 'reviewer'])
696
- await safeFailure(createDeliveryGitHubClients({ config: appConfig, env, identity: appConfig.roles[role].identity, role }), /Missing GitHub App credentials/u);
697
- assert.deepEqual(calls(), []);
698
- });
699
- test('helper cancellation does not deliver an account/token to its recipient', async () => {
700
- const controller = new AbortController();
701
- controller.abort();
702
- await assert.rejects(withMachineAuthorCredential(env, controller.signal, async () => {
703
- throw new Error('Recipient must not run.');
704
- }));
705
- assert.deepEqual(calls(), []);
706
- });
707
- test('only an absent conventional reference is eligible, independent of unrelated values', () => {
708
- assert.equal(machineAuthorEligible('GH_TOKEN', {}), true);
709
- assert.equal(machineAuthorEligible('GH_TOKEN', { GH_TOKEN: '' }), false);
710
- assert.equal(machineAuthorEligible('ALTERNATE_AUTHOR_TOKEN', {}), false);
711
- });
712
- //# sourceMappingURL=machineAuth.test.js.map
803
+ }
804
+ );
805
+ test("reviewer and App author missing credentials never inherit the personal session", async () => {
806
+ for (const role of ["author", "reviewer"])
807
+ await safeFailure(
808
+ createDeliveryGitHubClients({ config: appConfig, env, identity: appConfig.roles[role].identity, role }),
809
+ /Missing GitHub App credentials/u
810
+ );
811
+ assert.deepEqual(calls(), []);
812
+ });
813
+ test("helper cancellation does not deliver an account/token to its recipient", async () => {
814
+ const controller = new AbortController();
815
+ controller.abort();
816
+ await assert.rejects(
817
+ withMachineAuthorCredential(env, controller.signal, async () => {
818
+ throw new Error("Recipient must not run.");
819
+ })
820
+ );
821
+ assert.deepEqual(calls(), []);
822
+ });
823
+ test("only an absent conventional reference is eligible, independent of unrelated values", () => {
824
+ assert.equal(machineAuthorEligible("GH_TOKEN", {}), true);
825
+ assert.equal(machineAuthorEligible("GH_TOKEN", { GH_TOKEN: "" }), false);
826
+ assert.equal(machineAuthorEligible("ALTERNATE_AUTHOR_TOKEN", {}), false);
827
+ });
828
+ //# sourceMappingURL=machineAuth.test.js.map