@aviaratech/ai-delivery 0.3.35 → 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 (297) hide show
  1. package/CONTRIBUTING.md +12 -206
  2. package/README.md +57 -554
  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 +1651 -1590
  9. package/dist/boardReconcile.test.js.map +7 -1
  10. package/dist/build.test.js +130 -0
  11. package/dist/build.test.js.map +7 -0
  12. package/dist/callerErrors.test.js +105 -0
  13. package/dist/callerErrors.test.js.map +7 -0
  14. package/dist/cli.js +402 -515
  15. package/dist/cli.js.map +7 -1
  16. package/dist/cliResult.d.ts +2 -2
  17. package/dist/cliResult.js +42 -45
  18. package/dist/cliResult.js.map +7 -1
  19. package/dist/cliResult.test.js +424 -369
  20. package/dist/cliResult.test.js.map +7 -1
  21. package/dist/config/deliveryConfig.d.ts +288 -14
  22. package/dist/config/deliveryConfig.js +472 -390
  23. package/dist/config/deliveryConfig.js.map +7 -1
  24. package/dist/config/deliveryConfig.test.js +773 -649
  25. package/dist/config/deliveryConfig.test.js.map +7 -1
  26. package/dist/contributorChecks.test.js +1694 -916
  27. package/dist/contributorChecks.test.js.map +7 -1
  28. package/dist/currentConsumer.test.js +819 -737
  29. package/dist/currentConsumer.test.js.map +7 -1
  30. package/dist/currentTrackingScenario.test.js +499 -479
  31. package/dist/currentTrackingScenario.test.js.map +7 -1
  32. package/dist/delivery/common.js +160 -172
  33. package/dist/delivery/common.js.map +7 -1
  34. package/dist/delivery/delivery.test.js +509 -431
  35. package/dist/delivery/delivery.test.js.map +7 -1
  36. package/dist/delivery/evidence.d.ts +2 -2
  37. package/dist/delivery/evidence.js +133 -120
  38. package/dist/delivery/evidence.js.map +7 -1
  39. package/dist/delivery/index.js +7 -2
  40. package/dist/delivery/index.js.map +7 -1
  41. package/dist/delivery/legacy.js +65 -5
  42. package/dist/delivery/legacy.js.map +7 -1
  43. package/dist/delivery/policy.d.ts +10 -10
  44. package/dist/delivery/policy.js +211 -238
  45. package/dist/delivery/policy.js.map +7 -1
  46. package/dist/delivery/stage.d.ts +18 -18
  47. package/dist/delivery/stage.js +220 -235
  48. package/dist/delivery/stage.js.map +7 -1
  49. package/dist/deliveryBoard.d.ts +74 -0
  50. package/dist/deliveryBoard.js +644 -0
  51. package/dist/deliveryBoard.js.map +7 -0
  52. package/dist/deliveryBoard.test.js +649 -0
  53. package/dist/deliveryBoard.test.js.map +7 -0
  54. package/dist/deliveryHealth.test.js +179 -155
  55. package/dist/deliveryHealth.test.js.map +7 -1
  56. package/dist/dependencyCompatibility.test.js +154 -140
  57. package/dist/dependencyCompatibility.test.js.map +7 -1
  58. package/dist/directoryIndependent.test.js +417 -383
  59. package/dist/directoryIndependent.test.js.map +7 -1
  60. package/dist/dispatch.d.ts +16 -11
  61. package/dist/dispatch.js +329 -353
  62. package/dist/dispatch.js.map +7 -1
  63. package/dist/errors.d.ts +3 -3
  64. package/dist/errors.js +103 -96
  65. package/dist/errors.js.map +7 -1
  66. package/dist/fixtures/deliveryBoardReplay.d.ts +56 -0
  67. package/dist/fixtures/deliveryBoardReplay.js +617 -0
  68. package/dist/fixtures/deliveryBoardReplay.js.map +7 -0
  69. package/dist/fixtures/discovery.d.ts +59 -19
  70. package/dist/fixtures/discovery.js +96 -90
  71. package/dist/fixtures/discovery.js.map +7 -1
  72. package/dist/fixtures/inertEntrypointChild.js +57 -56
  73. package/dist/fixtures/inertEntrypointChild.js.map +7 -1
  74. package/dist/fixtures/inertEntrypoints.d.ts +1 -1
  75. package/dist/fixtures/inertEntrypoints.js +321 -276
  76. package/dist/fixtures/inertEntrypoints.js.map +7 -1
  77. package/dist/fixtures/inertTarget.d.ts +78 -7
  78. package/dist/fixtures/inertTarget.js +769 -691
  79. package/dist/fixtures/inertTarget.js.map +7 -1
  80. package/dist/fixtures/issue63.d.ts +4 -3
  81. package/dist/fixtures/issue63.js +260 -274
  82. package/dist/fixtures/issue63.js.map +7 -1
  83. package/dist/fixtures/issueProjectItems.d.ts +20 -0
  84. package/dist/fixtures/issueProjectItems.js +15 -0
  85. package/dist/fixtures/issueProjectItems.js.map +7 -0
  86. package/dist/fixtures/readView.d.ts +120 -0
  87. package/dist/fixtures/readView.js +172 -0
  88. package/dist/fixtures/readView.js.map +7 -0
  89. package/dist/fixtures/recordedGitHubFlows.d.ts +120 -0
  90. package/dist/fixtures/recordedGitHubFlows.js +109 -0
  91. package/dist/fixtures/recordedGitHubFlows.js.map +7 -0
  92. package/dist/genericCompatibility.test.js +64 -55
  93. package/dist/genericCompatibility.test.js.map +7 -1
  94. package/dist/git.js +73 -67
  95. package/dist/git.js.map +7 -1
  96. package/dist/gitProcess.d.ts +1 -1
  97. package/dist/gitProcess.js +58 -53
  98. package/dist/gitProcess.js.map +7 -1
  99. package/dist/github/client.d.ts +2 -2
  100. package/dist/github/client.js +484 -379
  101. package/dist/github/client.js.map +7 -1
  102. package/dist/github/commandIdentityPolicy.js +44 -52
  103. package/dist/github/commandIdentityPolicy.js.map +7 -1
  104. package/dist/github/discovery.d.ts +1 -0
  105. package/dist/github/discovery.js +197 -215
  106. package/dist/github/discovery.js.map +7 -1
  107. package/dist/github/discovery.test.js +223 -177
  108. package/dist/github/discovery.test.js.map +7 -1
  109. package/dist/github/issueHistory.d.ts +2 -2
  110. package/dist/github/issueHistory.js +117 -125
  111. package/dist/github/issueHistory.js.map +7 -1
  112. package/dist/github/machineAuth.d.ts +1 -1
  113. package/dist/github/machineAuth.js +126 -117
  114. package/dist/github/machineAuth.js.map +7 -1
  115. package/dist/github/machineAuth.test.js +755 -639
  116. package/dist/github/machineAuth.test.js.map +7 -1
  117. package/dist/github/nativeIssueMetadata.js +286 -273
  118. package/dist/github/nativeIssueMetadata.js.map +7 -1
  119. package/dist/github/projectDelivery.d.ts +18 -2
  120. package/dist/github/projectDelivery.js +615 -557
  121. package/dist/github/projectDelivery.js.map +7 -1
  122. package/dist/github/relationships.js +433 -389
  123. package/dist/github/relationships.js.map +7 -1
  124. package/dist/github/repo.d.ts +1 -0
  125. package/dist/github/repo.js +123 -96
  126. package/dist/github/repo.js.map +7 -1
  127. package/dist/index.js +3 -3
  128. package/dist/index.js.map +7 -1
  129. package/dist/issue.d.ts +40 -9
  130. package/dist/issue.js +2102 -1742
  131. package/dist/issue.js.map +7 -1
  132. package/dist/issue63History.test.js +40 -42
  133. package/dist/issue63History.test.js.map +7 -1
  134. package/dist/issue63Routes.test.js +154 -143
  135. package/dist/issue63Routes.test.js.map +7 -1
  136. package/dist/issueBatchUpdate.test.js +989 -885
  137. package/dist/issueBatchUpdate.test.js.map +7 -1
  138. package/dist/issueBlockerGuard.test.js +262 -226
  139. package/dist/issueBlockerGuard.test.js.map +7 -1
  140. package/dist/issueContract.d.ts +23 -4
  141. package/dist/issueContract.js +416 -395
  142. package/dist/issueContract.js.map +7 -1
  143. package/dist/issueContract.test.d.ts +4 -3
  144. package/dist/issueContract.test.js +358 -321
  145. package/dist/issueContract.test.js.map +7 -1
  146. package/dist/issueDates.test.js +235 -233
  147. package/dist/issueDates.test.js.map +7 -1
  148. package/dist/issueInfoReadback.test.js +304 -190
  149. package/dist/issueInfoReadback.test.js.map +7 -1
  150. package/dist/issueIntake.test.js +1945 -1732
  151. package/dist/issueIntake.test.js.map +7 -1
  152. package/dist/issueJournal.d.ts +40 -19
  153. package/dist/issueJournal.js +229 -138
  154. package/dist/issueJournal.js.map +7 -1
  155. package/dist/issueJournal.test.js +605 -422
  156. package/dist/issueJournal.test.js.map +7 -1
  157. package/dist/issueRollup.test.d.ts +1 -0
  158. package/dist/issueRollup.test.js +476 -0
  159. package/dist/issueRollup.test.js.map +7 -0
  160. package/dist/issueTracking.test.js +1059 -989
  161. package/dist/issueTracking.test.js.map +7 -1
  162. package/dist/issueWriteRecovery.test.d.ts +1 -0
  163. package/dist/issueWriteRecovery.test.js +260 -0
  164. package/dist/issueWriteRecovery.test.js.map +7 -0
  165. package/dist/lifecycle.test.js +112 -441
  166. package/dist/lifecycle.test.js.map +7 -1
  167. package/dist/logger.js +80 -74
  168. package/dist/logger.js.map +7 -1
  169. package/dist/mcp/index.js +116 -94
  170. package/dist/mcp/index.js.map +7 -1
  171. package/dist/mcp/tools.d.ts +264 -286
  172. package/dist/mcp/tools.js +267 -340
  173. package/dist/mcp/tools.js.map +7 -1
  174. package/dist/pluginAuthProbe.js +63 -52
  175. package/dist/pluginAuthProbe.js.map +7 -1
  176. package/dist/pluginAuthProbe.test.js +85 -62
  177. package/dist/pluginAuthProbe.test.js.map +7 -1
  178. package/dist/pluginCredentials.test.js +282 -259
  179. package/dist/pluginCredentials.test.js.map +7 -1
  180. package/dist/pluginDoctor.test.js +653 -588
  181. package/dist/pluginDoctor.test.js.map +7 -1
  182. package/dist/pluginInstaller.d.ts +7 -5
  183. package/dist/pluginInstaller.js +1173 -1229
  184. package/dist/pluginInstaller.js.map +7 -1
  185. package/dist/pluginInstaller.test.js +1842 -1423
  186. package/dist/pluginInstaller.test.js.map +7 -1
  187. package/dist/pluginPackaging.test.js +460 -409
  188. package/dist/pluginPackaging.test.js.map +7 -1
  189. package/dist/pr.d.ts +132 -94
  190. package/dist/pr.js +1521 -1323
  191. package/dist/pr.js.map +7 -1
  192. package/dist/pr.test.js +1678 -632
  193. package/dist/pr.test.js.map +7 -1
  194. package/dist/prAssociation.test.js +2419 -1788
  195. package/dist/prAssociation.test.js.map +7 -1
  196. package/dist/prDispatch.test.js +150 -89
  197. package/dist/prDispatch.test.js.map +7 -1
  198. package/dist/readView.d.ts +183 -0
  199. package/dist/readView.js +217 -0
  200. package/dist/readView.js.map +7 -0
  201. package/dist/readView.test.d.ts +1 -0
  202. package/dist/readView.test.js +119 -0
  203. package/dist/readView.test.js.map +7 -0
  204. package/dist/releaseReconciliation.test.js +267 -288
  205. package/dist/releaseReconciliation.test.js.map +7 -1
  206. package/dist/releaseWorkflow.test.js +2493 -422
  207. package/dist/releaseWorkflow.test.js.map +7 -1
  208. package/dist/review.d.ts +738 -2
  209. package/dist/review.js +601 -348
  210. package/dist/review.js.map +7 -1
  211. package/dist/review.test.js +1218 -812
  212. package/dist/review.test.js.map +7 -1
  213. package/dist/reviewSubmit.test.d.ts +1 -0
  214. package/dist/reviewSubmit.test.js +747 -0
  215. package/dist/reviewSubmit.test.js.map +7 -0
  216. package/dist/services/agentReadinessService.js +42 -37
  217. package/dist/services/agentReadinessService.js.map +7 -1
  218. package/dist/services/blockerGuardService.js +188 -188
  219. package/dist/services/blockerGuardService.js.map +7 -1
  220. package/dist/services/boardReconcileService.d.ts +125 -125
  221. package/dist/services/boardReconcileService.js +1295 -1421
  222. package/dist/services/boardReconcileService.js.map +7 -1
  223. package/dist/services/deliveryAdmission.js +131 -154
  224. package/dist/services/deliveryAdmission.js.map +7 -1
  225. package/dist/services/deliveryHealthService.js +197 -199
  226. package/dist/services/deliveryHealthService.js.map +7 -1
  227. package/dist/services/legacyIssueMigration.js +263 -277
  228. package/dist/services/legacyIssueMigration.js.map +7 -1
  229. package/dist/services/worktreeRegistry.d.ts +27 -119
  230. package/dist/services/worktreeRegistry.js +765 -1182
  231. package/dist/services/worktreeRegistry.js.map +7 -1
  232. package/dist/stagedChecks.test.js +396 -194
  233. package/dist/stagedChecks.test.js.map +7 -1
  234. package/dist/start.test.js +99 -95
  235. package/dist/start.test.js.map +7 -1
  236. package/dist/stdoutRegression.test.js +353 -352
  237. package/dist/stdoutRegression.test.js.map +7 -1
  238. package/dist/targetPolicyDiscovery.test.js +141 -143
  239. package/dist/targetPolicyDiscovery.test.js.map +7 -1
  240. package/dist/targetPolicyEntrypoints.test.js +308 -269
  241. package/dist/targetPolicyEntrypoints.test.js.map +7 -1
  242. package/dist/targetPolicyLocal.test.js +580 -1051
  243. package/dist/targetPolicyLocal.test.js.map +7 -1
  244. package/dist/targetPolicyRoutes.test.js +305 -281
  245. package/dist/targetPolicyRoutes.test.js.map +7 -1
  246. package/dist/targetRepositoryExecution.test.d.ts +1 -0
  247. package/dist/targetRepositoryExecution.test.js +463 -0
  248. package/dist/targetRepositoryExecution.test.js.map +7 -0
  249. package/dist/terminalMessages.js +41 -35
  250. package/dist/terminalMessages.js.map +7 -1
  251. package/dist/toolOutput.d.ts +2 -0
  252. package/dist/toolOutput.js +36 -0
  253. package/dist/toolOutput.js.map +7 -0
  254. package/dist/toolOutput.test.d.ts +1 -0
  255. package/dist/toolOutput.test.js +240 -0
  256. package/dist/toolOutput.test.js.map +7 -0
  257. package/dist/utils/atomicJson.js +84 -76
  258. package/dist/utils/atomicJson.js.map +7 -1
  259. package/dist/utils/filesystem.js +15 -18
  260. package/dist/utils/filesystem.js.map +7 -1
  261. package/dist/utils/lockfile.js +68 -71
  262. package/dist/utils/lockfile.js.map +7 -1
  263. package/dist/verification.d.ts +1 -19
  264. package/dist/verification.js +1020 -1939
  265. package/dist/verification.js.map +7 -1
  266. package/dist/verificationGate.test.js +127 -117
  267. package/dist/verificationGate.test.js.map +7 -1
  268. package/dist/version.js +23 -24
  269. package/dist/version.js.map +7 -1
  270. package/dist/worktree.d.ts +3 -15
  271. package/dist/worktree.js +97 -177
  272. package/dist/worktree.js.map +7 -1
  273. package/package.json +9 -8
  274. package/plugins/ai-delivery/.claude-plugin/plugin.json +2 -2
  275. package/plugins/ai-delivery/README.md +47 -156
  276. package/plugins/ai-delivery/plugin.json +1 -1
  277. package/plugins/ai-delivery/runtime/dist/THIRD-PARTY-NOTICES.md +238 -44
  278. package/plugins/ai-delivery/runtime/dist/cli.js +358 -115
  279. package/plugins/ai-delivery/runtime/package.json +1 -1
  280. package/plugins/ai-delivery/skills/intake-create/SKILL.md +14 -78
  281. package/plugins/ai-delivery/skills/pr-handoff/SKILL.md +35 -36
  282. package/plugins/ai-delivery/skills/worktree-lifecycle/SKILL.md +14 -15
  283. package/dist/investigationCompletion.test.js +0 -728
  284. package/dist/investigationCompletion.test.js.map +0 -1
  285. package/dist/setup.d.ts +0 -60
  286. package/dist/setup.js +0 -585
  287. package/dist/setup.js.map +0 -1
  288. package/dist/setup.test.js +0 -3329
  289. package/dist/setup.test.js.map +0 -1
  290. package/dist/worktreeTransition.d.ts +0 -211
  291. package/dist/worktreeTransition.js +0 -1037
  292. package/dist/worktreeTransition.js.map +0 -1
  293. package/dist/worktreeTransition.test.js +0 -1191
  294. package/dist/worktreeTransition.test.js.map +0 -1
  295. /package/dist/{investigationCompletion.test.d.ts → build.test.d.ts} +0 -0
  296. /package/dist/{setup.test.d.ts → callerErrors.test.d.ts} +0 -0
  297. /package/dist/{worktreeTransition.test.d.ts → deliveryBoard.test.d.ts} +0 -0
@@ -1,676 +1,800 @@
1
- import { syntheticDiscoveryClients, syntheticOverrides } from '../fixtures/discovery.js';
2
- import assert from 'node:assert/strict';
3
- import { generateKeyPairSync } from 'node:crypto';
4
- import { mkdirSync, mkdtempSync, rmSync, writeFileSync, readFileSync } from 'node:fs';
5
- import { spawnSync } from 'node:child_process';
6
- import { tmpdir } from 'node:os';
7
- import { join } from 'node:path';
8
- import { afterEach, describe, it, vi } from 'vitest';
9
- import { assertDeliveryRolePermissions, createDeliveryGitHubClients, withAuthorGitToken } from '../github/client.js';
10
- import { evaluateCommandIdentityPolicy } from '../github/commandIdentityPolicy.js';
11
- import { discoverDeliveryRouting } from '../github/discovery.js';
12
- import { contextFor } from '../dispatch.js';
13
- import { clearConfiguredNativeIssuePoints, nativeIssueSettingsFromDeliveryConfig, parseConfiguredNativeIssueMetadata, resolveNativeIssueFieldCatalog, setConfiguredNativeIssueMetadata, validateConfiguredNativeTracking, } from '../github/nativeIssueMetadata.js';
14
- import { PROJECT_DELIVERY_STATUSES, projectSettingsFromDeliveryConfig, resolveProjectDeliveryConfiguration, syncIssueProjectStatus, } from '../github/projectDelivery.js';
15
- import { resolveDeliveryRepo } from '../github/repo.js';
16
- import { readDeliveryOverrides, loadDeliveryConfig, loadDeliverySettings, parseDeliveryConfig, resolveDeliveryRoleCredentials, } from './deliveryConfig.js';
1
+ import { syntheticDiscoveryClients, syntheticOverrides } from "../fixtures/discovery.js";
2
+ import assert from "node:assert/strict";
3
+ import { generateKeyPairSync } from "node:crypto";
4
+ import { mkdirSync, mkdtempSync, rmSync, writeFileSync, readFileSync } from "node:fs";
5
+ import { spawnSync } from "node:child_process";
6
+ import { tmpdir } from "node:os";
7
+ import { join } from "node:path";
8
+ import { afterEach, describe, it, vi } from "vitest";
9
+ import { assertDeliveryRolePermissions, createDeliveryGitHubClients, withAuthorGitToken } from "../github/client.js";
10
+ import { evaluateCommandIdentityPolicy } from "../github/commandIdentityPolicy.js";
11
+ import { discoverDeliveryRouting } from "../github/discovery.js";
12
+ import { contextFor } from "../dispatch.js";
13
+ import {
14
+ clearConfiguredNativeIssuePoints,
15
+ nativeIssueSettingsFromDeliveryConfig,
16
+ parseConfiguredNativeIssueMetadata,
17
+ resolveNativeIssueFieldCatalog,
18
+ setConfiguredNativeIssueMetadata,
19
+ validateConfiguredNativeTracking
20
+ } from "../github/nativeIssueMetadata.js";
21
+ import {
22
+ PROJECT_DELIVERY_STATUSES,
23
+ projectSettingsFromDeliveryConfig,
24
+ resolveProjectDeliveryConfiguration,
25
+ syncIssueProjectStatus
26
+ } from "../github/projectDelivery.js";
27
+ import { resolveDeliveryRepo } from "../github/repo.js";
28
+ import {
29
+ readDeliveryOverrides,
30
+ loadDeliveryConfig,
31
+ loadDeliverySettings,
32
+ parseDeliveryConfig,
33
+ resolveDeliveryRoleCredentials
34
+ } from "./deliveryConfig.js";
17
35
  function git(args, options = {}) {
18
- const result = spawnSync('git', args, { ...options, encoding: 'utf8' });
19
- assert.equal(result.status, 0, result.stderr);
36
+ const result = spawnSync("git", args, { ...options, encoding: "utf8" });
37
+ assert.equal(result.status, 0, result.stderr);
20
38
  }
21
39
  function syntheticConfig(input) {
22
- const { owner, projectNumber, repo } = input;
23
- const second = repo === 'service';
24
- return {
25
- commandPolicy: {
26
- checks: { format: 'REQUIRED', gitClean: 'REQUIRED', lint: 'REQUIRED', test: 'REQUIRED', typecheck: 'REQUIRED' },
27
- timeoutsMs: { lint: 60_000, test: 60_000, typecheck: 60_000 },
40
+ const { owner, projectNumber, repo } = input;
41
+ const second = repo === "service";
42
+ return {
43
+ commandPolicy: {
44
+ checks: { format: "REQUIRED", gitClean: "REQUIRED", lint: "REQUIRED", test: "REQUIRED", typecheck: "REQUIRED" },
45
+ timeoutsMs: { lint: 6e4, test: 6e4, typecheck: 6e4 }
46
+ },
47
+ native: {
48
+ issueTypes: ["Task", "Defect"],
49
+ milestones: "repository",
50
+ organization: owner,
51
+ points: second ? { databaseId: "201", name: "Complexity", values: ["1", "3", "6"] } : { databaseId: "101", name: "Estimate", values: ["1", "2", "4"] },
52
+ priority: second ? { databaseId: "202", name: "Severity", values: ["Critical", "Normal"] } : { databaseId: "102", name: "Urgency", values: ["High", "Low"] },
53
+ project: {
54
+ number: projectNumber,
55
+ statuses: second ? { blocked: "Held", done: "Complete", inProgress: "Doing", todo: "Backlog" } : { blocked: "Waiting", done: "Shipped", inProgress: "Active", todo: "Queued" },
56
+ statusField: second ? "Stage" : "Flow",
57
+ title: "Delivery"
58
+ },
59
+ relationships: { blockedBy: "native", parent: "native" }
60
+ },
61
+ policy: { contract: "RepositoryDeliveryPolicy@1", module: "./policy.mjs" },
62
+ repository: `${owner}/${repo}`,
63
+ roles: {
64
+ author: {
65
+ credentialEnv: {
66
+ appId: "AUTHOR_APP_ID",
67
+ installationId: "AUTHOR_INSTALLATION_ID",
68
+ privateKeyPath: "AUTHOR_KEY_PATH"
28
69
  },
29
- native: {
30
- issueTypes: ['Task', 'Defect'],
31
- milestones: 'repository',
32
- organization: owner,
33
- points: second
34
- ? { databaseId: '201', name: 'Complexity', values: ['1', '3', '6'] }
35
- : { databaseId: '101', name: 'Estimate', values: ['1', '2', '4'] },
36
- priority: second
37
- ? { databaseId: '202', name: 'Severity', values: ['Critical', 'Normal'] }
38
- : { databaseId: '102', name: 'Urgency', values: ['High', 'Low'] },
39
- project: {
40
- number: projectNumber,
41
- statuses: second
42
- ? { blocked: 'Held', done: 'Complete', inProgress: 'Doing', todo: 'Backlog' }
43
- : { blocked: 'Waiting', done: 'Shipped', inProgress: 'Active', todo: 'Queued' },
44
- statusField: second ? 'Stage' : 'Flow',
45
- title: 'Delivery',
46
- },
47
- relationships: { blockedBy: 'native', parent: 'native' },
48
- },
49
- policy: { contract: 'RepositoryDeliveryPolicy@1', module: './policy.mjs' },
50
- repository: `${owner}/${repo}`,
51
- roles: {
52
- author: {
53
- credentialEnv: {
54
- appId: 'AUTHOR_APP_ID',
55
- installationId: 'AUTHOR_INSTALLATION_ID',
56
- privateKeyPath: 'AUTHOR_KEY_PATH',
57
- },
58
- identity: 'synthetic-author',
59
- },
60
- reviewer: {
61
- credentialEnv: {
62
- appId: 'REVIEWER_APP_ID',
63
- installationId: 'REVIEWER_INSTALLATION_ID',
64
- privateKeyPath: 'REVIEWER_KEY_PATH',
65
- },
66
- identity: 'synthetic-reviewer',
67
- },
70
+ identity: "synthetic-author"
71
+ },
72
+ reviewer: {
73
+ credentialEnv: {
74
+ appId: "REVIEWER_APP_ID",
75
+ installationId: "REVIEWER_INSTALLATION_ID",
76
+ privateKeyPath: "REVIEWER_KEY_PATH"
68
77
  },
69
- schemaVersion: 'ai-delivery.config@2',
70
- };
78
+ identity: "synthetic-reviewer"
79
+ }
80
+ },
81
+ schemaVersion: "ai-delivery.config@2"
82
+ };
71
83
  }
72
84
  function syntheticProject(config) {
73
- const settings = projectSettingsFromDeliveryConfig(config);
74
- const field = (input) => ({
75
- __typename: 'ProjectV2SingleSelectField',
76
- id: `${input.name}-field`,
77
- isIssueField: true,
78
- issueField: {
79
- __typename: 'IssueFieldSingleSelect',
80
- fullDatabaseId: input.databaseId,
81
- name: input.name,
82
- options: input.values.map((value, index) => ({ id: String(index + 1), name: value })),
85
+ const settings = projectSettingsFromDeliveryConfig(config);
86
+ const field = (input) => ({
87
+ __typename: "ProjectV2SingleSelectField",
88
+ id: `${input.name}-field`,
89
+ isIssueField: true,
90
+ issueField: {
91
+ __typename: "IssueFieldSingleSelect",
92
+ fullDatabaseId: input.databaseId,
93
+ name: input.name,
94
+ options: input.values.map((value, index) => ({ id: String(index + 1), name: value }))
95
+ },
96
+ name: input.name,
97
+ options: []
98
+ });
99
+ return {
100
+ fields: {
101
+ nodes: [
102
+ {
103
+ __typename: "ProjectV2SingleSelectField",
104
+ id: "flow-field",
105
+ isIssueField: false,
106
+ name: settings.statusField,
107
+ options: PROJECT_DELIVERY_STATUSES.map((status, index) => ({
108
+ id: `S${String(index)}`,
109
+ name: settings.statuses[status]
110
+ }))
83
111
  },
84
- name: input.name,
85
- options: [],
86
- });
87
- return {
88
- fields: {
89
- nodes: [
90
- {
91
- __typename: 'ProjectV2SingleSelectField',
92
- id: 'flow-field',
93
- isIssueField: false,
94
- name: settings.statusField,
95
- options: PROJECT_DELIVERY_STATUSES.map((status, index) => ({
96
- id: `S${String(index)}`,
97
- name: settings.statuses[status],
98
- })),
99
- },
100
- field(settings.points),
101
- field(settings.priority),
102
- ],
103
- },
104
- id: 'project-node',
105
- number: settings.number,
106
- title: settings.title,
107
- viewerCanUpdate: true,
108
- };
112
+ field(settings.points),
113
+ field(settings.priority)
114
+ ]
115
+ },
116
+ id: "project-node",
117
+ number: settings.number,
118
+ title: settings.title,
119
+ viewerCanUpdate: true
120
+ };
109
121
  }
110
122
  afterEach(() => vi.unstubAllEnvs());
111
- it.each(['issueFields', 'issueTypes', 'projectsV2', 'projectFields'])('reconciliation bounds %s discovery before a context exists', async (collection) => {
112
- const root = mkdtempSync(join(tmpdir(), 'delivery-discovery-bound-'));
123
+ it.each(["issueFields", "issueTypes", "projectsV2", "projectFields"])(
124
+ "reconciliation bounds %s discovery before a context exists",
125
+ async (collection) => {
126
+ const root = mkdtempSync(join(tmpdir(), "delivery-discovery-bound-"));
113
127
  try {
114
- const configured = parseDeliveryConfig(syntheticConfig({ owner: 'example', repo: 'widget', projectNumber: 1 }));
115
- const path = join(root, 'settings.json');
116
- userConfig(path, configured);
117
- for (const [finalPage, limit] of [
118
- [21, 20],
119
- [20, 20],
120
- [21, undefined],
121
- ]) {
122
- let requests = 0;
123
- const base = syntheticDiscoveryClients(configured);
124
- const graphql = (async (query, variables) => {
125
- assert.ok(!query.includes('mutation'));
126
- const response = await base.graphql(query, variables);
127
- const selected = collection === 'projectFields'
128
- ? query.includes('query ProjectDeliveryConfiguration')
129
- : query.includes(`${collection}(first:`);
130
- if (!selected)
131
- return response;
132
- requests++;
133
- const cloned = JSON.parse(JSON.stringify(response));
134
- const connection = collection === 'projectFields' ? cloned.organization.projectV2.fields : cloned.repository[collection];
135
- if (requests > 1)
136
- connection.nodes = [];
137
- connection.pageInfo = { hasNextPage: requests < finalPage, endCursor: `cursor-${String(requests)}` };
138
- return cloned;
139
- });
140
- const options = {
141
- clients: { graphql },
142
- repository: configured.repository,
143
- ...(limit === undefined ? {} : { readPageLimit: limit }),
144
- };
145
- const load = () => {
146
- if (collection !== 'projectsV2')
147
- return loadDeliveryConfig(root, options);
148
- // Current user settings require an explicit Project; exercise the existing optional linked-routing owner directly.
149
- const { project: _project, ...overrides } = syntheticOverrides(configured);
150
- return discoverDeliveryRouting({
151
- clients: { graphql },
152
- repository: configured.repository,
153
- overrides,
154
- ...(limit === undefined ? {} : { maxPages: limit }),
155
- });
156
- };
157
- if (finalPage === 21 && limit === 20) {
158
- await assert.rejects(load(), (error) => {
159
- assert.ok(error instanceof Error);
160
- assert.equal(error.name, 'CollectionLimitError', error.message);
161
- assert.equal(Reflect.get(error, 'pagesRequested'), 20);
162
- assert.equal(Reflect.get(error, 'limit'), 20);
163
- return true;
164
- });
165
- assert.equal(requests, 20);
166
- }
167
- else {
168
- await load();
169
- assert.equal(requests, finalPage);
170
- }
128
+ const configured = parseDeliveryConfig(syntheticConfig({ owner: "example", repo: "widget", projectNumber: 1 }));
129
+ const path = join(root, "settings.json");
130
+ userConfig(path, configured);
131
+ for (const [finalPage, limit] of [
132
+ [21, 20],
133
+ [20, 20],
134
+ [21, void 0]
135
+ ]) {
136
+ let requests = 0;
137
+ const base = syntheticDiscoveryClients(configured);
138
+ const graphql = (async (query, variables) => {
139
+ assert.ok(!query.includes("mutation"));
140
+ const response = await base.graphql(query, variables);
141
+ const selected = collection === "projectFields" ? query.includes("query ProjectDeliveryConfiguration") : query.includes(`${collection}(first:`);
142
+ if (!selected) return response;
143
+ requests++;
144
+ const cloned = JSON.parse(JSON.stringify(response));
145
+ const connection = collection === "projectFields" ? cloned.organization.projectV2.fields : cloned.repository[collection];
146
+ if (requests > 1) connection.nodes = [];
147
+ connection.pageInfo = { hasNextPage: requests < finalPage, endCursor: `cursor-${String(requests)}` };
148
+ return cloned;
149
+ });
150
+ const options = {
151
+ clients: { graphql },
152
+ repository: configured.repository,
153
+ ...limit === void 0 ? {} : { readPageLimit: limit }
154
+ };
155
+ const load = () => {
156
+ if (collection !== "projectsV2") return loadDeliveryConfig(root, options);
157
+ const { project: _project, ...overrides } = syntheticOverrides(configured);
158
+ return discoverDeliveryRouting({
159
+ clients: { graphql },
160
+ repository: configured.repository,
161
+ overrides,
162
+ ...limit === void 0 ? {} : { maxPages: limit }
163
+ });
164
+ };
165
+ if (finalPage === 21 && limit === 20) {
166
+ await assert.rejects(load(), (error) => {
167
+ assert.ok(error instanceof Error);
168
+ assert.equal(error.name, "CollectionLimitError", error.message);
169
+ assert.equal(Reflect.get(error, "pagesRequested"), 20);
170
+ assert.equal(Reflect.get(error, "limit"), 20);
171
+ return true;
172
+ });
173
+ assert.equal(requests, 20);
174
+ } else {
175
+ await load();
176
+ assert.equal(requests, finalPage);
171
177
  }
178
+ }
179
+ } finally {
180
+ rmSync(root, { recursive: true, force: true });
172
181
  }
173
- finally {
174
- rmSync(root, { recursive: true, force: true });
175
- }
176
- });
182
+ }
183
+ );
177
184
  function userConfig(path, config) {
178
- const { policy: _policy, repository: _repository, remote: _remote, schemaVersion: _schema, ...overrides } = syntheticOverrides(config);
179
- writeFileSync(path, JSON.stringify({ schemaVersion: 'ai-delivery.user@1', roles: config.roles, checkoutRoots: [], ...overrides }));
180
- vi.stubEnv('AI_DELIVERY_CONFIG', path);
185
+ const {
186
+ policy: _policy,
187
+ repository: _repository,
188
+ remote: _remote,
189
+ schemaVersion: _schema,
190
+ ...overrides
191
+ } = syntheticOverrides(config);
192
+ writeFileSync(
193
+ path,
194
+ JSON.stringify({ schemaVersion: "ai-delivery.user@1", roles: config.roles, checkoutRoots: [], ...overrides })
195
+ );
196
+ vi.stubEnv("AI_DELIVERY_CONFIG", path);
181
197
  }
182
- it('loads optional repository-scoped WIP limits without treating them as routing overrides', async () => {
183
- const root = mkdtempSync(join(tmpdir(), 'delivery-wip-config-'));
198
+ it("loads optional repository-scoped WIP limits without treating them as routing overrides", async () => {
199
+ const root = mkdtempSync(join(tmpdir(), "delivery-wip-config-"));
200
+ try {
201
+ const path = join(root, "settings.json");
202
+ const configured = parseDeliveryConfig(syntheticConfig({ owner: "example", repo: "widget", projectNumber: 1 }));
203
+ userConfig(path, configured);
204
+ const base = JSON.parse(readFileSync(path, "utf8"));
205
+ assert.equal(Reflect.get(await loadDeliverySettings(), "wipLimits"), void 0);
206
+ const lanes = [
207
+ { repository: "example/widget", name: "Urgent", match: { label: "Needs Review" }, limit: 2 },
208
+ { repository: "example/other", name: "Urgent", match: { field: "Priority", value: " High " }, limit: 0 }
209
+ ];
210
+ writeFileSync(path, JSON.stringify({ ...base, wipLimits: lanes }));
211
+ const settings = await loadDeliverySettings();
212
+ assert.deepEqual(Reflect.get(settings, "wipLimits"), lanes);
213
+ assert.equal(Reflect.has(settings.overrides, "wipLimits"), false);
214
+ const loaded = await loadDeliveryConfig(root, {
215
+ repository: "example/widget",
216
+ clients: syntheticDiscoveryClients(configured)
217
+ });
218
+ assert.deepEqual(loaded.config.wipLimits, lanes);
219
+ for (const bad of [
220
+ [{ ...lanes[0], limit: -1 }],
221
+ [{ ...lanes[0], limit: 1.5 }],
222
+ [{ ...lanes[0], match: { label: "urgent", field: "Priority", value: "High" } }],
223
+ [{ ...lanes[0], match: { field: "Priority" } }],
224
+ [lanes[0], { ...lanes[0], repository: "EXAMPLE/WIDGET" }],
225
+ [{ ...lanes[0], repository: "not-a-repository" }]
226
+ ]) {
227
+ writeFileSync(path, JSON.stringify({ ...base, wipLimits: bad }));
228
+ await assert.rejects(loadDeliverySettings(), /wipLimits/u);
229
+ }
230
+ } finally {
231
+ rmSync(root, { recursive: true, force: true });
232
+ }
233
+ });
234
+ describe("portable delivery configuration", () => {
235
+ it("selects a configured personal author token without ambient fallback and keeps the reviewer App role", async () => {
236
+ const base = syntheticConfig({ owner: "sample", projectNumber: 7, repo: "widget" });
237
+ const config = parseDeliveryConfig({
238
+ ...base,
239
+ roles: {
240
+ author: { authSource: "personal", credentialEnv: { token: "AUTHOR_TOKEN" }, identity: "host-author" },
241
+ reviewer: base.roles.reviewer
242
+ }
243
+ });
244
+ assert.equal(
245
+ evaluateCommandIdentityPolicy({ commandName: "pr:create", deliveryConfig: config, identity: "host-author" }).error,
246
+ null
247
+ );
248
+ assert.equal(
249
+ evaluateCommandIdentityPolicy({
250
+ commandName: "pr:review",
251
+ deliveryConfig: config,
252
+ identity: "synthetic-reviewer"
253
+ }).error,
254
+ null
255
+ );
256
+ await assert.rejects(
257
+ createDeliveryGitHubClients({
258
+ config,
259
+ env: { GH_TOKEN: "ambient-token" },
260
+ identity: "host-author",
261
+ role: "author"
262
+ }),
263
+ /AUTHOR_TOKEN/u
264
+ );
265
+ const originalFetch = globalThis.fetch;
184
266
  try {
185
- const path = join(root, 'settings.json');
186
- const configured = parseDeliveryConfig(syntheticConfig({ owner: 'example', repo: 'widget', projectNumber: 1 }));
187
- userConfig(path, configured);
188
- const base = JSON.parse(readFileSync(path, 'utf8'));
189
- assert.equal(Reflect.get(await loadDeliverySettings(), 'wipLimits'), undefined);
190
- const lanes = [
191
- { repository: 'example/widget', name: 'Urgent', match: { label: 'Needs Review' }, limit: 2 },
192
- { repository: 'example/other', name: 'Urgent', match: { field: 'Priority', value: ' High ' }, limit: 0 },
193
- ];
194
- writeFileSync(path, JSON.stringify({ ...base, wipLimits: lanes }));
195
- const settings = await loadDeliverySettings();
196
- assert.deepEqual(Reflect.get(settings, 'wipLimits'), lanes);
197
- assert.equal(Reflect.has(settings.overrides, 'wipLimits'), false);
198
- const loaded = await loadDeliveryConfig(root, {
199
- repository: 'example/widget',
200
- clients: syntheticDiscoveryClients(configured),
267
+ globalThis.fetch = async (_url, init) => {
268
+ assert.equal(new Headers(init?.headers).get("authorization"), "token selected-token");
269
+ return new Response(JSON.stringify({ id: 37, login: "selected-user" }), {
270
+ status: 200,
271
+ headers: { "content-type": "application/json" }
201
272
  });
202
- assert.deepEqual(loaded.config.wipLimits, lanes);
203
- for (const bad of [
204
- [{ ...lanes[0], limit: -1 }],
205
- [{ ...lanes[0], limit: 1.5 }],
206
- [{ ...lanes[0], match: { label: 'urgent', field: 'Priority', value: 'High' } }],
207
- [{ ...lanes[0], match: { field: 'Priority' } }],
208
- [lanes[0], { ...lanes[0], repository: 'EXAMPLE/WIDGET' }],
209
- [{ ...lanes[0], repository: 'not-a-repository' }],
210
- ]) {
211
- writeFileSync(path, JSON.stringify({ ...base, wipLimits: bad }));
212
- await assert.rejects(loadDeliverySettings(), /wipLimits/u);
213
- }
273
+ };
274
+ const clients = await createDeliveryGitHubClients({
275
+ config,
276
+ env: { AUTHOR_TOKEN: "selected-token", GH_TOKEN: "ambient-token" },
277
+ identity: "host-author",
278
+ role: "author"
279
+ });
280
+ assert.equal(clients.authSource, "personal");
281
+ assert.equal(await withAuthorGitToken(clients, (token) => token), "selected-token");
282
+ assert.deepEqual(await clients.authenticatedAuthor?.(), {
283
+ actorLogin: "selected-user",
284
+ credentialIdentity: "user:37"
285
+ });
286
+ globalThis.fetch = async () => new Response(JSON.stringify({ message: "Bad credentials" }), { status: 401 });
287
+ const expired = await createDeliveryGitHubClients({
288
+ config,
289
+ env: { AUTHOR_TOKEN: "expired-token" },
290
+ identity: "host-author",
291
+ role: "author"
292
+ });
293
+ if (!expired.authenticatedAuthor) throw new Error("Personal author readback is unavailable.");
294
+ await assert.rejects(expired.authenticatedAuthor(), /personal author token is invalid or expired/u);
295
+ } finally {
296
+ globalThis.fetch = originalFetch;
214
297
  }
215
- finally {
216
- rmSync(root, { recursive: true, force: true });
298
+ });
299
+ it("cancels actual Octokit identity, REST and GraphQL requests through the selected scope signal", async () => {
300
+ const base = syntheticConfig({ owner: "sample", projectNumber: 7, repo: "widget" });
301
+ const config = parseDeliveryConfig({
302
+ ...base,
303
+ roles: {
304
+ author: { authSource: "personal", credentialEnv: { token: "AUTHOR_TOKEN" }, identity: "host-author" },
305
+ reviewer: base.roles.reviewer
306
+ }
307
+ });
308
+ const originalFetch = globalThis.fetch;
309
+ try {
310
+ for (const operation of ["identity", "rest", "graphql"]) {
311
+ const cancellation = new AbortController();
312
+ let observedAbort = false;
313
+ let started;
314
+ const requestStarted = new Promise((resolve) => {
315
+ started = resolve;
316
+ });
317
+ globalThis.fetch = async (_url, init) => {
318
+ started();
319
+ assert.equal(new Headers(init?.headers).get("authorization"), "token selected-token");
320
+ assert.equal(init?.signal, cancellation.signal);
321
+ return new Promise((_resolve, reject) => {
322
+ init.signal.addEventListener(
323
+ "abort",
324
+ () => {
325
+ observedAbort = true;
326
+ reject(cancellation.signal.reason);
327
+ },
328
+ { once: true }
329
+ );
330
+ });
331
+ };
332
+ const clients = await createDeliveryGitHubClients({
333
+ config,
334
+ env: { AUTHOR_TOKEN: "selected-token", GH_TOKEN: "ambient-token" },
335
+ identity: "host-author",
336
+ role: "author",
337
+ signal: cancellation.signal
338
+ });
339
+ assert.ok(clients.authenticatedAuthor);
340
+ const request = operation === "identity" ? clients.authenticatedAuthor() : operation === "rest" ? clients.rest.repos.get({ owner: "sample", repo: "widget" }) : clients.graphql("query { viewer { login } }");
341
+ const rejected = assert.rejects(request);
342
+ await requestStarted;
343
+ cancellation.abort();
344
+ await rejected;
345
+ assert.equal(observedAbort, true, `${operation} HTTP request must be cancelled`);
346
+ }
347
+ } finally {
348
+ globalThis.fetch = originalFetch;
217
349
  }
218
- });
219
- describe('portable delivery configuration', () => {
220
- it('selects a configured personal author token without ambient fallback and keeps the reviewer App role', async () => {
221
- const base = syntheticConfig({ owner: 'sample', projectNumber: 7, repo: 'widget' });
222
- const config = parseDeliveryConfig({
223
- ...base,
224
- roles: {
225
- author: { authSource: 'personal', credentialEnv: { token: 'AUTHOR_TOKEN' }, identity: 'host-author' },
226
- reviewer: base.roles.reviewer,
227
- },
350
+ });
351
+ it("cancels App installation authentication before either configured role can continue", async () => {
352
+ const config = parseDeliveryConfig(syntheticConfig({ owner: "sample", projectNumber: 7, repo: "widget" }));
353
+ const temp = mkdtempSync(join(tmpdir(), "delivery-cancel-app-"));
354
+ const originalFetch = globalThis.fetch;
355
+ try {
356
+ const env = {};
357
+ for (const [index, role] of ["author", "reviewer"].entries()) {
358
+ const path = join(temp, `${role}.pem`);
359
+ const { privateKey } = generateKeyPairSync("rsa", { modulusLength: 2048 });
360
+ writeFileSync(path, privateKey.export({ type: "pkcs8", format: "pem" }), { mode: 384 });
361
+ const selectedRole = config.roles[role];
362
+ assert.ok("credentialEnv" in selectedRole);
363
+ const names = selectedRole.credentialEnv;
364
+ assert.ok("appId" in names, "Synthetic role must use App credentials");
365
+ env[names.appId] = String(42 + index);
366
+ env[names.installationId] = String(52 + index);
367
+ env[names.privateKeyPath] = path;
368
+ }
369
+ for (const role of ["author", "reviewer"]) {
370
+ const cancellation = new AbortController();
371
+ let observedAbort = false;
372
+ let requests = 0;
373
+ let started;
374
+ const requestStarted = new Promise((resolve) => {
375
+ started = resolve;
228
376
  });
229
- assert.equal(evaluateCommandIdentityPolicy({ commandName: 'pr:create', deliveryConfig: config, identity: 'host-author' })
230
- .error, null);
231
- assert.equal(evaluateCommandIdentityPolicy({
232
- commandName: 'pr:review',
233
- deliveryConfig: config,
234
- identity: 'synthetic-reviewer',
235
- }).error, null);
236
- await assert.rejects(createDeliveryGitHubClients({
237
- config,
238
- env: { GH_TOKEN: 'ambient-token' },
239
- identity: 'host-author',
240
- role: 'author',
241
- }), /AUTHOR_TOKEN/u);
242
- const originalFetch = globalThis.fetch;
243
- try {
244
- globalThis.fetch = async (_url, init) => {
245
- assert.equal(new Headers(init?.headers).get('authorization'), 'token selected-token');
246
- return new Response(JSON.stringify({ id: 37, login: 'selected-user' }), {
247
- status: 200,
248
- headers: { 'content-type': 'application/json' },
249
- });
250
- };
251
- const clients = await createDeliveryGitHubClients({
252
- config,
253
- env: { AUTHOR_TOKEN: 'selected-token', GH_TOKEN: 'ambient-token' },
254
- identity: 'host-author',
255
- role: 'author',
256
- });
257
- assert.equal(clients.authSource, 'personal');
258
- assert.equal(await withAuthorGitToken(clients, (token) => token), 'selected-token');
259
- assert.deepEqual(await clients.authenticatedAuthor?.(), {
260
- actorLogin: 'selected-user',
261
- credentialIdentity: 'user:37',
262
- });
263
- globalThis.fetch = async () => new Response(JSON.stringify({ message: 'Bad credentials' }), { status: 401 });
264
- const expired = await createDeliveryGitHubClients({
265
- config,
266
- env: { AUTHOR_TOKEN: 'expired-token' },
267
- identity: 'host-author',
268
- role: 'author',
269
- });
270
- if (!expired.authenticatedAuthor)
271
- throw new Error('Personal author readback is unavailable.');
272
- await assert.rejects(expired.authenticatedAuthor(), /personal author token is invalid or expired/u);
273
- }
274
- finally {
275
- globalThis.fetch = originalFetch;
276
- }
277
- });
278
- it('cancels actual Octokit identity, REST and GraphQL requests through the selected scope signal', async () => {
279
- const base = syntheticConfig({ owner: 'sample', projectNumber: 7, repo: 'widget' });
280
- const config = parseDeliveryConfig({
281
- ...base,
282
- roles: {
283
- author: { authSource: 'personal', credentialEnv: { token: 'AUTHOR_TOKEN' }, identity: 'host-author' },
284
- reviewer: base.roles.reviewer,
285
- },
377
+ globalThis.fetch = async (_url, init) => {
378
+ requests++;
379
+ started();
380
+ assert.equal(init?.signal, cancellation.signal);
381
+ return new Promise((_resolve, reject) => {
382
+ init.signal.addEventListener(
383
+ "abort",
384
+ () => {
385
+ observedAbort = true;
386
+ reject(cancellation.signal.reason);
387
+ },
388
+ { once: true }
389
+ );
390
+ });
391
+ };
392
+ const request = createDeliveryGitHubClients({
393
+ config,
394
+ env,
395
+ identity: config.roles[role].identity,
396
+ role,
397
+ signal: cancellation.signal
286
398
  });
287
- const originalFetch = globalThis.fetch;
288
- try {
289
- for (const operation of ['identity', 'rest', 'graphql']) {
290
- const cancellation = new AbortController();
291
- let observedAbort = false;
292
- let started;
293
- const requestStarted = new Promise((resolve) => {
294
- started = resolve;
295
- });
296
- globalThis.fetch = async (_url, init) => {
297
- started();
298
- assert.equal(new Headers(init?.headers).get('authorization'), 'token selected-token');
299
- assert.equal(init?.signal, cancellation.signal);
300
- return new Promise((_resolve, reject) => {
301
- init.signal.addEventListener('abort', () => {
302
- observedAbort = true;
303
- reject(cancellation.signal.reason);
304
- }, { once: true });
305
- });
306
- };
307
- const clients = await createDeliveryGitHubClients({
308
- config,
309
- env: { AUTHOR_TOKEN: 'selected-token', GH_TOKEN: 'ambient-token' },
310
- identity: 'host-author',
311
- role: 'author',
312
- signal: cancellation.signal,
313
- });
314
- assert.ok(clients.authenticatedAuthor);
315
- const request = operation === 'identity'
316
- ? clients.authenticatedAuthor()
317
- : operation === 'rest'
318
- ? clients.rest.repos.get({ owner: 'sample', repo: 'widget' })
319
- : clients.graphql('query { viewer { login } }');
320
- const rejected = assert.rejects(request);
321
- await requestStarted;
322
- cancellation.abort();
323
- await rejected;
324
- assert.equal(observedAbort, true, `${operation} HTTP request must be cancelled`);
325
- }
326
- }
327
- finally {
328
- globalThis.fetch = originalFetch;
329
- }
330
- });
331
- it('cancels App installation authentication before either configured role can continue', async () => {
332
- const config = parseDeliveryConfig(syntheticConfig({ owner: 'sample', projectNumber: 7, repo: 'widget' }));
333
- const temp = mkdtempSync(join(tmpdir(), 'delivery-cancel-app-'));
334
- const originalFetch = globalThis.fetch;
335
- try {
336
- const env = {};
337
- for (const [index, role] of ['author', 'reviewer'].entries()) {
338
- const path = join(temp, `${role}.pem`);
339
- const { privateKey } = generateKeyPairSync('rsa', { modulusLength: 2048 });
340
- writeFileSync(path, privateKey.export({ type: 'pkcs8', format: 'pem' }), { mode: 0o600 });
341
- const names = config.roles[role].credentialEnv;
342
- assert.ok('appId' in names, 'Synthetic role must use App credentials');
343
- env[names.appId] = String(42 + index);
344
- env[names.installationId] = String(52 + index);
345
- env[names.privateKeyPath] = path;
346
- }
347
- for (const role of ['author', 'reviewer']) {
348
- const cancellation = new AbortController();
349
- let observedAbort = false;
350
- let started;
351
- const requestStarted = new Promise((resolve) => {
352
- started = resolve;
353
- });
354
- globalThis.fetch = async (_url, init) => {
355
- started();
356
- assert.equal(init?.signal, cancellation.signal);
357
- return new Promise((_resolve, reject) => {
358
- init.signal.addEventListener('abort', () => {
359
- observedAbort = true;
360
- reject(cancellation.signal.reason);
361
- }, { once: true });
362
- });
363
- };
364
- const request = createDeliveryGitHubClients({
365
- config,
366
- env,
367
- identity: config.roles[role].identity,
368
- role,
369
- signal: cancellation.signal,
370
- });
371
- const rejected = assert.rejects(request, /GitHub App authentication failed/u);
372
- await requestStarted;
373
- cancellation.abort();
374
- await rejected;
375
- assert.equal(observedAbort, true, `${role} installation request must be cancelled`);
376
- }
377
- }
378
- finally {
379
- globalThis.fetch = originalFetch;
380
- rmSync(temp, { recursive: true, force: true });
381
- }
382
- });
383
- it('retains the configured personal author during configuration discovery with a legacy flag present', async () => {
384
- const temp = mkdtempSync(join(tmpdir(), 'delivery-personal-config-'));
385
- const originalFetch = globalThis.fetch;
386
- const originalToken = process.env.AUTHOR_TOKEN;
387
- try {
388
- git(['init', '--quiet', temp]);
389
- git(['remote', 'add', 'origin', 'https://github.com/sample/widget.git'], { cwd: temp });
390
- const base = syntheticConfig({ owner: 'sample', projectNumber: 7, repo: 'widget' });
391
- const config = parseDeliveryConfig({
392
- ...base,
393
- roles: {
394
- author: { authSource: 'personal', credentialEnv: { token: 'AUTHOR_TOKEN' }, identity: 'host-author' },
395
- reviewer: base.roles.reviewer,
396
- },
397
- });
398
- writeFileSync(join(temp, 'policy.mjs'), `export const deliverySettings = ${JSON.stringify({ roles: config.roles, commandPolicy: config.commandPolicy })};\n`);
399
- writeFileSync(join(temp, 'ai-delivery.config.json'), JSON.stringify(syntheticOverrides(config)));
400
- git(['add', 'policy.mjs', 'ai-delivery.config.json'], { cwd: temp });
401
- userConfig(join(temp, 'user.json'), config);
402
- process.env.AUTHOR_TOKEN = 'selected-token';
403
- let selectedRequests = 0;
404
- globalThis.fetch = async (_url, init) => {
405
- assert.match(new Headers(init?.headers).get('authorization') ?? '', /selected-token/u);
406
- selectedRequests += 1;
407
- return new Response(JSON.stringify({ data: { repository: null } }), {
408
- status: 200,
409
- headers: { 'content-type': 'application/json' },
410
- });
411
- };
412
- await assert.rejects(loadDeliveryConfig(temp, { personalAuth: true }), /Incomplete GitHub repository/u);
413
- assert.equal(selectedRequests, 1);
414
- globalThis.fetch = async () => new Response(JSON.stringify({ message: 'Bad credentials' }), { status: 401 });
415
- await assert.rejects(contextFor({ repoRoot: temp, identity: 'host-author' }, 'pr:create'), /Configured personal author token is invalid or expired/u);
416
- }
417
- finally {
418
- globalThis.fetch = originalFetch;
419
- if (originalToken === undefined)
420
- delete process.env.AUTHOR_TOKEN;
421
- else
422
- process.env.AUTHOR_TOKEN = originalToken;
423
- rmSync(temp, { force: true, recursive: true });
424
- }
425
- });
426
- it('loads two independent repository roots and binds native metadata to each configuration', async () => {
427
- const temp = mkdtempSync(join(tmpdir(), 'delivery-config-'));
428
- try {
429
- for (const [owner, repo, projectNumber] of [
430
- ['sample-one', 'widget', 7],
431
- ['sample-two', 'service', 12],
432
- ]) {
433
- const root = join(temp, repo);
434
- mkdirSync(root);
435
- git(['init', '--quiet', root]);
436
- git(['remote', 'add', 'origin', `https://github.com/${owner}/${repo}.git`], { cwd: root });
437
- const configured = parseDeliveryConfig(syntheticConfig({ owner, projectNumber, repo }));
438
- writeFileSync(join(root, 'policy.mjs'), `export const deliverySettings = ${JSON.stringify({ roles: configured.roles, commandPolicy: configured.commandPolicy })};\n`);
439
- writeFileSync(join(root, 'ai-delivery.config.json'), JSON.stringify(syntheticOverrides(parseDeliveryConfig(syntheticConfig({ owner, projectNumber, repo })))));
440
- git(['add', 'policy.mjs', 'ai-delivery.config.json'], { cwd: root });
441
- userConfig(join(temp, 'user.json'), configured);
442
- const loaded = await loadDeliveryConfig(root, { clients: syntheticDiscoveryClients(configured) });
443
- assert.match(loaded.configDigest, /^sha256:[a-f0-9]{64}$/u);
444
- assert.deepEqual(resolveDeliveryRepo(loaded.config, root), { owner, repo });
445
- assert.throws(() => resolveDeliveryRepo({ ...loaded.config, repository: `${owner}/foreign` }, root), /does not match remote/u);
446
- const project = resolveProjectDeliveryConfiguration(syntheticProject(loaded.config), {
447
- requireWritable: true,
448
- settings: projectSettingsFromDeliveryConfig(loaded.config),
449
- });
450
- assert.equal(project.projectNumber, projectNumber);
451
- assert.equal(project.statusOptionIds['In Progress'], 'S1');
452
- const statusField = loaded.config.native.project.statusField;
453
- const inProgressName = loaded.config.native.project.statuses.inProgress;
454
- const graphql = (query, variables) => {
455
- if (query.includes('ProjectDeliveryItems')) {
456
- assert.equal(variables.number, projectNumber);
457
- assert.equal(variables.statusField, statusField);
458
- return Promise.resolve({
459
- organization: { projectV2: { items: { nodes: [], pageInfo: { endCursor: null, hasNextPage: false } } } },
460
- });
461
- }
462
- if (query.includes('AddProjectDeliveryItem')) {
463
- return Promise.resolve({ addProjectV2ItemById: { item: { id: 'ITEM' } } });
464
- }
465
- if (query.includes('UpdateProjectDeliveryStatus')) {
466
- assert.equal(variables.optionId, 'S1');
467
- return Promise.resolve({ updateProjectV2ItemFieldValue: { projectV2Item: { id: 'ITEM' } } });
468
- }
469
- if (query.includes('ProjectDeliveryItemReadback')) {
470
- assert.equal(variables.statusField, statusField);
471
- return Promise.resolve({
472
- node: {
473
- content: { id: 'ISSUE' },
474
- fieldValueByName: { name: inProgressName, optionId: 'S1' },
475
- id: 'ITEM',
476
- isArchived: false,
477
- project: { id: 'project-node', number: projectNumber },
478
- },
479
- });
480
- }
481
- return Promise.reject(new Error('Unexpected synthetic GraphQL operation.'));
482
- };
483
- assert.deepEqual(await syncIssueProjectStatus({
484
- configuration: project,
485
- graphql: graphql,
486
- issueNodeId: 'ISSUE',
487
- org: owner,
488
- status: 'In Progress',
489
- }), { itemId: 'ITEM', status: 'In Progress' });
490
- const settings = nativeIssueSettingsFromDeliveryConfig(loaded.config);
491
- const selectedPoints = settings.points.values.at(-1);
492
- const selectedPriority = settings.priority.values[0];
493
- assert.ok(selectedPoints !== undefined);
494
- assert.ok(selectedPriority !== undefined);
495
- const catalog = resolveNativeIssueFieldCatalog([
496
- {
497
- data_type: 'single_select',
498
- id: Number(settings.points.databaseId),
499
- name: settings.points.name,
500
- options: [...settings.points.values].reverse().map((value) => ({ name: String(value) })),
501
- },
502
- {
503
- data_type: 'single_select',
504
- id: Number(settings.priority.databaseId),
505
- name: settings.priority.name,
506
- options: [...settings.priority.values].reverse().map((name) => ({ name })),
507
- },
508
- ], settings);
509
- assert.equal(catalog.points.name, settings.points.name);
510
- assert.deepEqual(parseConfiguredNativeIssueMetadata([
511
- {
512
- data_type: 'single_select',
513
- issue_field_id: Number(settings.points.databaseId),
514
- issue_field_name: settings.points.name,
515
- single_select_option: { name: String(selectedPoints) },
516
- },
517
- {
518
- data_type: 'single_select',
519
- issue_field_id: Number(settings.priority.databaseId),
520
- issue_field_name: settings.priority.name,
521
- single_select_option: { name: selectedPriority },
522
- },
523
- ], settings), { points: selectedPoints, priority: selectedPriority });
524
- assert.doesNotThrow(() => {
525
- validateConfiguredNativeTracking({
526
- blockedBy: [17],
527
- config: loaded.config,
528
- issueNumber: 20,
529
- issueType: 'Defect',
530
- milestone: 3,
531
- parentIssueNumber: 15,
532
- points: selectedPoints,
533
- priority: selectedPriority,
534
- });
535
- });
536
- }
537
- }
538
- finally {
539
- rmSync(temp, { force: true, recursive: true });
399
+ const rejected = assert.rejects(request, (error) => error === cancellation.signal.reason);
400
+ await requestStarted;
401
+ cancellation.abort();
402
+ await rejected;
403
+ assert.equal(observedAbort, true, `${role} installation request must be cancelled`);
404
+ assert.equal(requests, 1, `${role} installation request must not be retried`);
405
+ }
406
+ } finally {
407
+ globalThis.fetch = originalFetch;
408
+ rmSync(temp, { recursive: true, force: true });
409
+ }
410
+ });
411
+ it("retains the configured personal author during configuration discovery with a legacy flag present", async () => {
412
+ const temp = mkdtempSync(join(tmpdir(), "delivery-personal-config-"));
413
+ const originalFetch = globalThis.fetch;
414
+ const originalToken = process.env.AUTHOR_TOKEN;
415
+ try {
416
+ git(["init", "--quiet", temp]);
417
+ git(["remote", "add", "origin", "https://github.com/sample/widget.git"], { cwd: temp });
418
+ const base = syntheticConfig({ owner: "sample", projectNumber: 7, repo: "widget" });
419
+ const config = parseDeliveryConfig({
420
+ ...base,
421
+ roles: {
422
+ author: { authSource: "personal", credentialEnv: { token: "AUTHOR_TOKEN" }, identity: "host-author" },
423
+ reviewer: base.roles.reviewer
540
424
  }
541
- });
542
- it('rejects missing configuration, unsupported policy and role collisions without printing secrets', async () => {
543
- const base = syntheticConfig({ owner: 'sample', projectNumber: 7, repo: 'widget' });
544
- const temp = mkdtempSync(join(tmpdir(), 'delivery-invalid-'));
545
- try {
546
- vi.stubEnv('AI_DELIVERY_CONFIG', join(temp, 'missing.json'));
547
- await assert.rejects(loadDeliveryConfig(temp), /Missing user configuration/u);
548
- assert.throws(() => parseDeliveryConfig({ ...base, policy: { ...base.policy, contract: 'wrong' } }), /policy.contract/u);
549
- assert.throws(() => parseDeliveryConfig({
550
- ...base,
551
- roles: { ...base.roles, reviewer: { ...base.roles.reviewer, identity: base.roles.author.identity } },
552
- }), /distinct/u);
553
- assert.throws(() => parseDeliveryConfig({
554
- ...base,
555
- roles: {
556
- ...base.roles,
557
- reviewer: { ...base.roles.reviewer, credentialEnv: base.roles.author.credentialEnv },
558
- },
559
- }), /environment names must be distinct/u);
560
- assert.throws(() => parseDeliveryConfig({
561
- ...base,
562
- native: {
563
- ...base.native,
564
- priority: { ...base.native.priority, databaseId: base.native.points.databaseId },
565
- },
566
- }), /field IDs must be distinct/u);
567
- assert.throws(() => parseDeliveryConfig({ ...base, privateKey: 'synthetic-secret' }), (error) => {
568
- assert.doesNotMatch(String(error), /synthetic-secret/u);
569
- return true;
425
+ });
426
+ writeFileSync(
427
+ join(temp, "policy.mjs"),
428
+ `export const deliverySettings = ${JSON.stringify({ roles: config.roles, commandPolicy: config.commandPolicy })};
429
+ `
430
+ );
431
+ writeFileSync(join(temp, "ai-delivery.config.json"), JSON.stringify(syntheticOverrides(config)));
432
+ git(["add", "policy.mjs", "ai-delivery.config.json"], { cwd: temp });
433
+ userConfig(join(temp, "user.json"), config);
434
+ process.env.AUTHOR_TOKEN = "selected-token";
435
+ let selectedRequests = 0;
436
+ globalThis.fetch = async (_url, init) => {
437
+ assert.match(new Headers(init?.headers).get("authorization") ?? "", /selected-token/u);
438
+ selectedRequests += 1;
439
+ return new Response(JSON.stringify({ data: { repository: null } }), {
440
+ status: 200,
441
+ headers: { "content-type": "application/json" }
442
+ });
443
+ };
444
+ await assert.rejects(loadDeliveryConfig(temp, { personalAuth: true }), /Incomplete GitHub repository/u);
445
+ assert.ok(selectedRequests > 0, "discovery must use the selected token");
446
+ globalThis.fetch = async () => new Response(JSON.stringify({ message: "Bad credentials" }), { status: 401 });
447
+ await assert.rejects(
448
+ contextFor({ repoRoot: temp, identity: "host-author" }, "pr:create"),
449
+ /Configured personal author token is invalid or expired/u
450
+ );
451
+ } finally {
452
+ globalThis.fetch = originalFetch;
453
+ if (originalToken === void 0) delete process.env.AUTHOR_TOKEN;
454
+ else process.env.AUTHOR_TOKEN = originalToken;
455
+ rmSync(temp, { force: true, recursive: true });
456
+ }
457
+ });
458
+ it("loads two independent repository roots and binds native metadata to each configuration", async () => {
459
+ const temp = mkdtempSync(join(tmpdir(), "delivery-config-"));
460
+ try {
461
+ for (const [owner, repo, projectNumber] of [
462
+ ["sample-one", "widget", 7],
463
+ ["sample-two", "service", 12]
464
+ ]) {
465
+ const root = join(temp, repo);
466
+ mkdirSync(root);
467
+ git(["init", "--quiet", root]);
468
+ git(["remote", "add", "origin", `https://github.com/${owner}/${repo}.git`], { cwd: root });
469
+ const configured = parseDeliveryConfig(syntheticConfig({ owner, projectNumber, repo }));
470
+ writeFileSync(
471
+ join(root, "policy.mjs"),
472
+ `export const deliverySettings = ${JSON.stringify({ roles: configured.roles, commandPolicy: configured.commandPolicy })};
473
+ `
474
+ );
475
+ writeFileSync(
476
+ join(root, "ai-delivery.config.json"),
477
+ JSON.stringify(syntheticOverrides(parseDeliveryConfig(syntheticConfig({ owner, projectNumber, repo }))))
478
+ );
479
+ git(["add", "policy.mjs", "ai-delivery.config.json"], { cwd: root });
480
+ userConfig(join(temp, "user.json"), configured);
481
+ const loaded = await loadDeliveryConfig(root, { clients: syntheticDiscoveryClients(configured) });
482
+ assert.match(loaded.configDigest, /^sha256:[a-f0-9]{64}$/u);
483
+ assert.deepEqual(resolveDeliveryRepo(loaded.config, root), { owner, repo });
484
+ assert.throws(
485
+ () => resolveDeliveryRepo({ ...loaded.config, repository: `${owner}/foreign` }, root),
486
+ /does not match remote/u
487
+ );
488
+ const project = resolveProjectDeliveryConfiguration(syntheticProject(loaded.config), {
489
+ requireWritable: true,
490
+ settings: projectSettingsFromDeliveryConfig(loaded.config)
491
+ });
492
+ assert.equal(project.projectNumber, projectNumber);
493
+ assert.equal(project.statusOptionIds["In Progress"], "S1");
494
+ const statusField = loaded.config.native.project.statusField;
495
+ const inProgressName = loaded.config.native.project.statuses.inProgress;
496
+ const graphql = (query, variables) => {
497
+ if (query.includes("ProjectDeliveryIssueItems")) {
498
+ assert.equal(variables.statusField, statusField);
499
+ return Promise.resolve({
500
+ node: { id: "ISSUE", projectItems: { nodes: [], pageInfo: { hasNextPage: false } } }
570
501
  });
571
- const config = parseDeliveryConfig(base);
572
- assert.throws(() => resolveProjectDeliveryConfiguration({ ...syntheticProject(config), viewerCanUpdate: false }, { requireWritable: true, settings: projectSettingsFromDeliveryConfig(config) }), /not writable/u);
573
- git(['init', '--quiet', temp]);
574
- writeFileSync(join(temp, 'policy.mjs'), 'export const contract = "RepositoryDeliveryPolicy@1";\n');
575
- writeFileSync(join(temp, 'ai-delivery.config.json'), JSON.stringify(syntheticOverrides(parseDeliveryConfig(base))));
576
- assert.throws(() => readDeliveryOverrides(temp), /must be source-controlled/u);
577
- assert.throws(() => resolveDeliveryRoleCredentials({ config, env: {}, role: 'author' }), /Missing GitHub App credentials for author/u);
578
- await assert.rejects(createDeliveryGitHubClients({ config, env: {}, identity: 'synthetic-reviewer', role: 'author' }), /requires the configured author identity/u);
579
- await assert.rejects(createDeliveryGitHubClients({ config, env: {}, identity: 'personal', role: 'reviewer' }), /configured reviewer identity/u);
580
- await assert.rejects(createDeliveryGitHubClients({ config, env: { GH_TOKEN: 'inert-token' }, identity: 'personal', role: 'author' }), /configured author identity/u);
581
- await assert.rejects(createDeliveryGitHubClients({
582
- config,
583
- env: { GH_TOKEN: 'inert-token' },
584
- identity: 'synthetic-author',
585
- role: 'author',
586
- }), /Missing GitHub App credentials/u);
587
- const personal = await createDeliveryGitHubClients({
588
- config,
589
- env: {},
590
- identity: 'personal',
591
- personalAuth: { enabled: true, token: 'inert-token' },
592
- role: 'author',
502
+ }
503
+ if (query.includes("AddProjectDeliveryItem")) {
504
+ return Promise.resolve({ addProjectV2ItemById: { item: { id: "ITEM" } } });
505
+ }
506
+ if (query.includes("UpdateProjectDeliveryStatus")) {
507
+ assert.equal(variables.optionId, "S1");
508
+ return Promise.resolve({ updateProjectV2ItemFieldValue: { projectV2Item: { id: "ITEM" } } });
509
+ }
510
+ if (query.includes("ProjectDeliveryItemReadback")) {
511
+ assert.equal(variables.statusField, statusField);
512
+ return Promise.resolve({
513
+ node: {
514
+ content: { id: "ISSUE" },
515
+ fieldValueByName: { name: inProgressName, optionId: "S1" },
516
+ id: "ITEM",
517
+ isArchived: false,
518
+ project: { id: "project-node", number: projectNumber }
519
+ }
593
520
  });
594
- assert.equal(personal.authSource, 'personal');
595
- await assert.rejects(createDeliveryGitHubClients({
596
- config,
597
- env: { GH_TOKEN: 'inert-token' },
598
- identity: 'personal',
599
- personalAuth: { enabled: true },
600
- role: 'reviewer',
601
- }), /explicit personal author identity/u);
602
- assert.throws(() => assertDeliveryRolePermissions({
603
- permissions: { contents: 'read', issues: 'write', pull_requests: 'write' },
604
- role: 'author',
605
- }), /contents:write/u);
606
- assert.throws(() => assertDeliveryRolePermissions({
607
- permissions: { contents: 'write', issues: 'write', pull_requests: 'write' },
608
- role: 'author',
609
- }), /organization_projects:write/u);
610
- const sameAppEnv = {
611
- AUTHOR_APP_ID: '101',
612
- AUTHOR_INSTALLATION_ID: '201',
613
- AUTHOR_KEY_PATH: join(temp, 'inert-author.pem'),
614
- REVIEWER_APP_ID: '101',
615
- REVIEWER_INSTALLATION_ID: '202',
616
- REVIEWER_KEY_PATH: join(temp, 'inert-reviewer.pem'),
617
- };
618
- await assert.rejects(createDeliveryGitHubClients({ config, env: sameAppEnv, identity: 'synthetic-author', role: 'author' }), /distinct GitHub App credentials/u);
619
- assert.equal(evaluateCommandIdentityPolicy({
620
- commandName: 'pr:create',
621
- deliveryConfig: config,
622
- identity: 'synthetic-author',
623
- }).error, null);
624
- assert.equal(evaluateCommandIdentityPolicy({
625
- commandName: 'pr:review',
626
- deliveryConfig: config,
627
- identity: 'synthetic-reviewer',
628
- }).error, null);
629
- assert.match(evaluateCommandIdentityPolicy({
630
- commandName: 'pr:review',
631
- deliveryConfig: config,
632
- identity: 'synthetic-author',
633
- }).error ?? '', /configured reviewer identity/u);
634
- assert.match(evaluateCommandIdentityPolicy({ commandName: 'pr:create', deliveryConfig: config, identity: 'personal' })
635
- .error ?? '', /personal-token override/u);
636
- assert.throws(() => {
637
- validateConfiguredNativeTracking({ config, issueType: 'Task', points: 3, priority: 'High' });
638
- }, /Unsupported native Estimate/u);
639
- }
640
- finally {
641
- rmSync(temp, { force: true, recursive: true });
642
- }
643
- });
644
- it('rejects a foreign cached field catalog before either configured native mutation', async () => {
645
- const config = parseDeliveryConfig(syntheticConfig({ owner: 'sample', projectNumber: 7, repo: 'widget' }));
646
- const settings = nativeIssueSettingsFromDeliveryConfig(config);
647
- const catalog = {
648
- points: { dataType: 'single_select', id: 201, name: settings.points.name },
649
- priority: { dataType: 'single_select', id: 102, name: settings.priority.name },
521
+ }
522
+ return Promise.reject(new Error("Unexpected synthetic GraphQL operation."));
650
523
  };
651
- let mutations = 0;
652
- const rest = {
653
- request: (route) => {
654
- if (route.startsWith('GET ')) {
655
- return Promise.resolve({
656
- data: [
657
- {
658
- data_type: 'single_select',
659
- issue_field_id: 101,
660
- issue_field_name: settings.points.name,
661
- single_select_option: { name: '1' },
662
- },
663
- ],
664
- });
665
- }
666
- mutations += 1;
667
- return Promise.resolve({ data: [] });
524
+ assert.deepEqual(
525
+ await syncIssueProjectStatus({
526
+ configuration: project,
527
+ graphql,
528
+ issueNodeId: "ISSUE",
529
+ org: owner,
530
+ status: "In Progress"
531
+ }),
532
+ { itemId: "ITEM", status: "In Progress" }
533
+ );
534
+ const settings = nativeIssueSettingsFromDeliveryConfig(loaded.config);
535
+ const selectedPoints = settings.points.values.at(-1);
536
+ const selectedPriority = settings.priority.values[0];
537
+ assert.ok(selectedPoints !== void 0);
538
+ assert.ok(selectedPriority !== void 0);
539
+ const catalog = resolveNativeIssueFieldCatalog(
540
+ [
541
+ {
542
+ data_type: "single_select",
543
+ id: Number(settings.points.databaseId),
544
+ name: settings.points.name,
545
+ options: [...settings.points.values].reverse().map((value) => ({ name: String(value) }))
668
546
  },
669
- };
670
- const input = { catalog, issueNumber: 17, org: 'sample', owner: 'sample', repo: 'widget', rest, settings };
671
- await assert.rejects(setConfiguredNativeIssueMetadata({ ...input, metadata: { points: 1 } }), /catalog does not match/u);
672
- await assert.rejects(clearConfiguredNativeIssuePoints(input), /catalog does not match/u);
673
- assert.equal(mutations, 0);
674
- });
547
+ {
548
+ data_type: "single_select",
549
+ id: Number(settings.priority.databaseId),
550
+ name: settings.priority.name,
551
+ options: [...settings.priority.values].reverse().map((name) => ({ name }))
552
+ }
553
+ ],
554
+ settings
555
+ );
556
+ assert.equal(catalog.points.name, settings.points.name);
557
+ assert.deepEqual(
558
+ parseConfiguredNativeIssueMetadata(
559
+ [
560
+ {
561
+ data_type: "single_select",
562
+ issue_field_id: Number(settings.points.databaseId),
563
+ issue_field_name: settings.points.name,
564
+ single_select_option: { name: String(selectedPoints) }
565
+ },
566
+ {
567
+ data_type: "single_select",
568
+ issue_field_id: Number(settings.priority.databaseId),
569
+ issue_field_name: settings.priority.name,
570
+ single_select_option: { name: selectedPriority }
571
+ }
572
+ ],
573
+ settings
574
+ ),
575
+ { points: selectedPoints, priority: selectedPriority }
576
+ );
577
+ assert.doesNotThrow(() => {
578
+ validateConfiguredNativeTracking({
579
+ blockedBy: [17],
580
+ config: loaded.config,
581
+ issueNumber: 20,
582
+ issueType: "Defect",
583
+ milestone: 3,
584
+ parentIssueNumber: 15,
585
+ points: selectedPoints,
586
+ priority: selectedPriority
587
+ });
588
+ });
589
+ }
590
+ } finally {
591
+ rmSync(temp, { force: true, recursive: true });
592
+ }
593
+ });
594
+ it("rejects missing configuration, unsupported policy and role collisions without printing secrets", async () => {
595
+ const base = syntheticConfig({ owner: "sample", projectNumber: 7, repo: "widget" });
596
+ const temp = mkdtempSync(join(tmpdir(), "delivery-invalid-"));
597
+ try {
598
+ vi.stubEnv("AI_DELIVERY_CONFIG", join(temp, "missing.json"));
599
+ await assert.rejects(loadDeliveryConfig(temp), /Missing user configuration/u);
600
+ assert.throws(
601
+ () => parseDeliveryConfig({ ...base, policy: { ...base.policy, contract: "wrong" } }),
602
+ /policy.contract/u
603
+ );
604
+ assert.throws(
605
+ () => parseDeliveryConfig({
606
+ ...base,
607
+ roles: { ...base.roles, reviewer: { ...base.roles.reviewer, identity: base.roles.author.identity } }
608
+ }),
609
+ /distinct/u
610
+ );
611
+ assert.throws(
612
+ () => parseDeliveryConfig({
613
+ ...base,
614
+ roles: {
615
+ ...base.roles,
616
+ reviewer: { ...base.roles.reviewer, credentialEnv: base.roles.author.credentialEnv }
617
+ }
618
+ }),
619
+ /environment names must be distinct/u
620
+ );
621
+ assert.throws(
622
+ () => parseDeliveryConfig({
623
+ ...base,
624
+ native: {
625
+ ...base.native,
626
+ priority: { ...base.native.priority, databaseId: base.native.points.databaseId }
627
+ }
628
+ }),
629
+ /field IDs must be distinct/u
630
+ );
631
+ assert.throws(
632
+ () => parseDeliveryConfig({ ...base, privateKey: "synthetic-secret" }),
633
+ (error) => {
634
+ assert.doesNotMatch(String(error), /synthetic-secret/u);
635
+ return true;
636
+ }
637
+ );
638
+ const config = parseDeliveryConfig(base);
639
+ assert.throws(
640
+ () => resolveProjectDeliveryConfiguration(
641
+ { ...syntheticProject(config), viewerCanUpdate: false },
642
+ { requireWritable: true, settings: projectSettingsFromDeliveryConfig(config) }
643
+ ),
644
+ /not writable/u
645
+ );
646
+ const withReview = (count) => {
647
+ const project = syntheticProject(config);
648
+ const status = project.fields.nodes[0];
649
+ for (let index = 0; index < count; index++) status.options.push({ id: `R${index}`, name: "In Review" });
650
+ return resolveProjectDeliveryConfiguration(project, { settings: projectSettingsFromDeliveryConfig(config) });
651
+ };
652
+ assert.equal(withReview(1).reviewOptionId, "R0");
653
+ assert.throws(() => withReview(2), /repeats In Review/u);
654
+ git(["init", "--quiet", temp]);
655
+ writeFileSync(join(temp, "policy.mjs"), 'export const contract = "RepositoryDeliveryPolicy@1";\n');
656
+ writeFileSync(
657
+ join(temp, "ai-delivery.config.json"),
658
+ JSON.stringify(syntheticOverrides(parseDeliveryConfig(base)))
659
+ );
660
+ assert.throws(() => readDeliveryOverrides(temp), /must be source-controlled/u);
661
+ assert.throws(
662
+ () => resolveDeliveryRoleCredentials({ config, env: {}, role: "author" }),
663
+ /Missing GitHub App credentials for author/u
664
+ );
665
+ await assert.rejects(
666
+ createDeliveryGitHubClients({ config, env: {}, identity: "synthetic-reviewer", role: "author" }),
667
+ /requires the configured author identity/u
668
+ );
669
+ await assert.rejects(
670
+ createDeliveryGitHubClients({ config, env: {}, identity: "personal", role: "reviewer" }),
671
+ /configured reviewer identity/u
672
+ );
673
+ await assert.rejects(
674
+ createDeliveryGitHubClients({ config, env: { GH_TOKEN: "inert-token" }, identity: "personal", role: "author" }),
675
+ /configured author identity/u
676
+ );
677
+ await assert.rejects(
678
+ createDeliveryGitHubClients({
679
+ config,
680
+ env: { GH_TOKEN: "inert-token" },
681
+ identity: "synthetic-author",
682
+ role: "author"
683
+ }),
684
+ /Missing GitHub App credentials/u
685
+ );
686
+ const personal = await createDeliveryGitHubClients({
687
+ config,
688
+ env: {},
689
+ identity: "personal",
690
+ personalAuth: { enabled: true, token: "inert-token" },
691
+ role: "author"
692
+ });
693
+ assert.equal(personal.authSource, "personal");
694
+ await assert.rejects(
695
+ createDeliveryGitHubClients({
696
+ config,
697
+ env: { GH_TOKEN: "inert-token" },
698
+ identity: "personal",
699
+ personalAuth: { enabled: true },
700
+ role: "reviewer"
701
+ }),
702
+ /explicit personal author identity/u
703
+ );
704
+ assert.throws(
705
+ () => assertDeliveryRolePermissions({
706
+ permissions: { contents: "read", issues: "write", pull_requests: "write" },
707
+ role: "author"
708
+ }),
709
+ /contents:write/u
710
+ );
711
+ assert.throws(
712
+ () => assertDeliveryRolePermissions({
713
+ permissions: { contents: "write", issues: "write", pull_requests: "write" },
714
+ role: "author"
715
+ }),
716
+ /organization_projects:write/u
717
+ );
718
+ const sameAppEnv = {
719
+ AUTHOR_APP_ID: "101",
720
+ AUTHOR_INSTALLATION_ID: "201",
721
+ AUTHOR_KEY_PATH: join(temp, "inert-author.pem"),
722
+ REVIEWER_APP_ID: "101",
723
+ REVIEWER_INSTALLATION_ID: "202",
724
+ REVIEWER_KEY_PATH: join(temp, "inert-reviewer.pem")
725
+ };
726
+ await assert.rejects(
727
+ createDeliveryGitHubClients({ config, env: sameAppEnv, identity: "synthetic-author", role: "author" }),
728
+ /distinct GitHub App credentials/u
729
+ );
730
+ assert.equal(
731
+ evaluateCommandIdentityPolicy({
732
+ commandName: "pr:create",
733
+ deliveryConfig: config,
734
+ identity: "synthetic-author"
735
+ }).error,
736
+ null
737
+ );
738
+ assert.equal(
739
+ evaluateCommandIdentityPolicy({
740
+ commandName: "pr:review",
741
+ deliveryConfig: config,
742
+ identity: "synthetic-reviewer"
743
+ }).error,
744
+ null
745
+ );
746
+ assert.match(
747
+ evaluateCommandIdentityPolicy({
748
+ commandName: "pr:review",
749
+ deliveryConfig: config,
750
+ identity: "synthetic-author"
751
+ }).error ?? "",
752
+ /configured reviewer identity/u
753
+ );
754
+ assert.match(
755
+ evaluateCommandIdentityPolicy({ commandName: "pr:create", deliveryConfig: config, identity: "personal" }).error ?? "",
756
+ /personal-token override/u
757
+ );
758
+ assert.throws(() => {
759
+ validateConfiguredNativeTracking({ config, issueType: "Task", points: 3, priority: "High" });
760
+ }, /Unsupported native Estimate/u);
761
+ } finally {
762
+ rmSync(temp, { force: true, recursive: true });
763
+ }
764
+ });
765
+ it("rejects a foreign cached field catalog before either configured native mutation", async () => {
766
+ const config = parseDeliveryConfig(syntheticConfig({ owner: "sample", projectNumber: 7, repo: "widget" }));
767
+ const settings = nativeIssueSettingsFromDeliveryConfig(config);
768
+ const catalog = {
769
+ points: { dataType: "single_select", id: 201, name: settings.points.name },
770
+ priority: { dataType: "single_select", id: 102, name: settings.priority.name }
771
+ };
772
+ let mutations = 0;
773
+ const rest = {
774
+ request: (route) => {
775
+ if (route.startsWith("GET ")) {
776
+ return Promise.resolve({
777
+ data: [
778
+ {
779
+ data_type: "single_select",
780
+ issue_field_id: 101,
781
+ issue_field_name: settings.points.name,
782
+ single_select_option: { name: "1" }
783
+ }
784
+ ]
785
+ });
786
+ }
787
+ mutations += 1;
788
+ return Promise.resolve({ data: [] });
789
+ }
790
+ };
791
+ const input = { catalog, issueNumber: 17, org: "sample", owner: "sample", repo: "widget", rest, settings };
792
+ await assert.rejects(
793
+ setConfiguredNativeIssueMetadata({ ...input, metadata: { points: 1 } }),
794
+ /catalog does not match/u
795
+ );
796
+ await assert.rejects(clearConfiguredNativeIssuePoints(input), /catalog does not match/u);
797
+ assert.equal(mutations, 0);
798
+ });
675
799
  });
676
- //# sourceMappingURL=deliveryConfig.test.js.map
800
+ //# sourceMappingURL=deliveryConfig.test.js.map