@aviaratech/ai-delivery 0.3.35 → 0.3.37

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (301) hide show
  1. package/CONTRIBUTING.md +12 -206
  2. package/README.md +56 -554
  3. package/dist/agent.d.ts +1 -3
  4. package/dist/agent.js +74 -16
  5. package/dist/agent.js.map +7 -1
  6. package/dist/agentReadiness.test.js +73 -67
  7. package/dist/agentReadiness.test.js.map +7 -1
  8. package/dist/boardReconcile.test.js +1651 -1590
  9. package/dist/boardReconcile.test.js.map +7 -1
  10. package/dist/build.test.js +130 -0
  11. package/dist/build.test.js.map +7 -0
  12. package/dist/callerErrors.test.js +91 -0
  13. package/dist/callerErrors.test.js.map +7 -0
  14. package/dist/cli.js +389 -517
  15. package/dist/cli.js.map +7 -1
  16. package/dist/cliResult.d.ts +2 -2
  17. package/dist/cliResult.js +42 -45
  18. package/dist/cliResult.js.map +7 -1
  19. package/dist/cliResult.test.js +424 -369
  20. package/dist/cliResult.test.js.map +7 -1
  21. package/dist/config/deliveryConfig.d.ts +288 -14
  22. package/dist/config/deliveryConfig.js +472 -390
  23. package/dist/config/deliveryConfig.js.map +7 -1
  24. package/dist/config/deliveryConfig.test.js +773 -649
  25. package/dist/config/deliveryConfig.test.js.map +7 -1
  26. package/dist/contributorChecks.test.js +1694 -916
  27. package/dist/contributorChecks.test.js.map +7 -1
  28. package/dist/currentConsumer.test.js +819 -737
  29. package/dist/currentConsumer.test.js.map +7 -1
  30. package/dist/currentTrackingScenario.test.js +499 -479
  31. package/dist/currentTrackingScenario.test.js.map +7 -1
  32. package/dist/delivery/common.js +160 -172
  33. package/dist/delivery/common.js.map +7 -1
  34. package/dist/delivery/delivery.test.js +509 -431
  35. package/dist/delivery/delivery.test.js.map +7 -1
  36. package/dist/delivery/evidence.d.ts +2 -2
  37. package/dist/delivery/evidence.js +133 -120
  38. package/dist/delivery/evidence.js.map +7 -1
  39. package/dist/delivery/index.js +7 -2
  40. package/dist/delivery/index.js.map +7 -1
  41. package/dist/delivery/legacy.js +65 -5
  42. package/dist/delivery/legacy.js.map +7 -1
  43. package/dist/delivery/policy.d.ts +10 -10
  44. package/dist/delivery/policy.js +211 -238
  45. package/dist/delivery/policy.js.map +7 -1
  46. package/dist/delivery/stage.d.ts +18 -18
  47. package/dist/delivery/stage.js +220 -235
  48. package/dist/delivery/stage.js.map +7 -1
  49. package/dist/deliveryBoard.d.ts +74 -0
  50. package/dist/deliveryBoard.js +644 -0
  51. package/dist/deliveryBoard.js.map +7 -0
  52. package/dist/deliveryBoard.test.js +649 -0
  53. package/dist/deliveryBoard.test.js.map +7 -0
  54. package/dist/deliveryHealth.test.js +179 -155
  55. package/dist/deliveryHealth.test.js.map +7 -1
  56. package/dist/dependencyCompatibility.test.js +154 -140
  57. package/dist/dependencyCompatibility.test.js.map +7 -1
  58. package/dist/directoryIndependent.test.js +417 -383
  59. package/dist/directoryIndependent.test.js.map +7 -1
  60. package/dist/dispatch.d.ts +16 -11
  61. package/dist/dispatch.js +316 -354
  62. package/dist/dispatch.js.map +7 -1
  63. package/dist/errors.d.ts +3 -3
  64. package/dist/errors.js +103 -96
  65. package/dist/errors.js.map +7 -1
  66. package/dist/fixtures/deliveryBoardReplay.d.ts +56 -0
  67. package/dist/fixtures/deliveryBoardReplay.js +617 -0
  68. package/dist/fixtures/deliveryBoardReplay.js.map +7 -0
  69. package/dist/fixtures/discovery.d.ts +63 -23
  70. package/dist/fixtures/discovery.js +96 -90
  71. package/dist/fixtures/discovery.js.map +7 -1
  72. package/dist/fixtures/inertEntrypointChild.js +57 -56
  73. package/dist/fixtures/inertEntrypointChild.js.map +7 -1
  74. package/dist/fixtures/inertEntrypoints.d.ts +1 -1
  75. package/dist/fixtures/inertEntrypoints.js +321 -276
  76. package/dist/fixtures/inertEntrypoints.js.map +7 -1
  77. package/dist/fixtures/inertTarget.d.ts +78 -7
  78. package/dist/fixtures/inertTarget.js +769 -691
  79. package/dist/fixtures/inertTarget.js.map +7 -1
  80. package/dist/fixtures/issue63.d.ts +4 -3
  81. package/dist/fixtures/issue63.js +260 -274
  82. package/dist/fixtures/issue63.js.map +7 -1
  83. package/dist/fixtures/issueProjectItems.d.ts +20 -0
  84. package/dist/fixtures/issueProjectItems.js +15 -0
  85. package/dist/fixtures/issueProjectItems.js.map +7 -0
  86. package/dist/fixtures/readView.d.ts +120 -0
  87. package/dist/fixtures/readView.js +172 -0
  88. package/dist/fixtures/readView.js.map +7 -0
  89. package/dist/fixtures/recordedGitHubFlows.d.ts +120 -0
  90. package/dist/fixtures/recordedGitHubFlows.js +109 -0
  91. package/dist/fixtures/recordedGitHubFlows.js.map +7 -0
  92. package/dist/genericCompatibility.test.js +64 -55
  93. package/dist/genericCompatibility.test.js.map +7 -1
  94. package/dist/git.d.ts +0 -3
  95. package/dist/git.js +59 -76
  96. package/dist/git.js.map +7 -1
  97. package/dist/gitProcess.d.ts +1 -1
  98. package/dist/gitProcess.js +58 -53
  99. package/dist/gitProcess.js.map +7 -1
  100. package/dist/github/client.d.ts +2 -2
  101. package/dist/github/client.js +484 -379
  102. package/dist/github/client.js.map +7 -1
  103. package/dist/github/commandIdentityPolicy.js +42 -52
  104. package/dist/github/commandIdentityPolicy.js.map +7 -1
  105. package/dist/github/discovery.d.ts +1 -0
  106. package/dist/github/discovery.js +197 -215
  107. package/dist/github/discovery.js.map +7 -1
  108. package/dist/github/discovery.test.js +223 -177
  109. package/dist/github/discovery.test.js.map +7 -1
  110. package/dist/github/issueHistory.d.ts +2 -2
  111. package/dist/github/issueHistory.js +117 -125
  112. package/dist/github/issueHistory.js.map +7 -1
  113. package/dist/github/machineAuth.d.ts +1 -1
  114. package/dist/github/machineAuth.js +126 -117
  115. package/dist/github/machineAuth.js.map +7 -1
  116. package/dist/github/machineAuth.test.js +755 -639
  117. package/dist/github/machineAuth.test.js.map +7 -1
  118. package/dist/github/nativeIssueMetadata.js +286 -273
  119. package/dist/github/nativeIssueMetadata.js.map +7 -1
  120. package/dist/github/projectDelivery.d.ts +18 -2
  121. package/dist/github/projectDelivery.js +615 -557
  122. package/dist/github/projectDelivery.js.map +7 -1
  123. package/dist/github/relationships.js +433 -389
  124. package/dist/github/relationships.js.map +7 -1
  125. package/dist/github/repo.d.ts +1 -0
  126. package/dist/github/repo.js +123 -96
  127. package/dist/github/repo.js.map +7 -1
  128. package/dist/index.js +3 -3
  129. package/dist/index.js.map +7 -1
  130. package/dist/issue.d.ts +40 -9
  131. package/dist/issue.js +2102 -1742
  132. package/dist/issue.js.map +7 -1
  133. package/dist/issue63History.test.js +40 -42
  134. package/dist/issue63History.test.js.map +7 -1
  135. package/dist/issue63Routes.test.js +154 -143
  136. package/dist/issue63Routes.test.js.map +7 -1
  137. package/dist/issueBatchUpdate.test.js +989 -885
  138. package/dist/issueBatchUpdate.test.js.map +7 -1
  139. package/dist/issueBlockerGuard.test.js +262 -226
  140. package/dist/issueBlockerGuard.test.js.map +7 -1
  141. package/dist/issueContract.d.ts +23 -4
  142. package/dist/issueContract.js +416 -395
  143. package/dist/issueContract.js.map +7 -1
  144. package/dist/issueContract.test.d.ts +4 -3
  145. package/dist/issueContract.test.js +358 -321
  146. package/dist/issueContract.test.js.map +7 -1
  147. package/dist/issueDates.test.js +235 -233
  148. package/dist/issueDates.test.js.map +7 -1
  149. package/dist/issueInfoReadback.test.js +304 -190
  150. package/dist/issueInfoReadback.test.js.map +7 -1
  151. package/dist/issueIntake.test.js +1938 -1732
  152. package/dist/issueIntake.test.js.map +7 -1
  153. package/dist/issueJournal.d.ts +40 -19
  154. package/dist/issueJournal.js +229 -138
  155. package/dist/issueJournal.js.map +7 -1
  156. package/dist/issueJournal.test.js +605 -422
  157. package/dist/issueJournal.test.js.map +7 -1
  158. package/dist/issueRollup.test.d.ts +1 -0
  159. package/dist/issueRollup.test.js +476 -0
  160. package/dist/issueRollup.test.js.map +7 -0
  161. package/dist/issueTracking.test.js +1059 -989
  162. package/dist/issueTracking.test.js.map +7 -1
  163. package/dist/issueWriteRecovery.test.d.ts +1 -0
  164. package/dist/issueWriteRecovery.test.js +260 -0
  165. package/dist/issueWriteRecovery.test.js.map +7 -0
  166. package/dist/lifecycle.test.js +112 -441
  167. package/dist/lifecycle.test.js.map +7 -1
  168. package/dist/logger.js +80 -74
  169. package/dist/logger.js.map +7 -1
  170. package/dist/mcp/index.js +116 -94
  171. package/dist/mcp/index.js.map +7 -1
  172. package/dist/mcp/tools.d.ts +252 -310
  173. package/dist/mcp/tools.js +235 -342
  174. package/dist/mcp/tools.js.map +7 -1
  175. package/dist/pluginAuthProbe.js +63 -52
  176. package/dist/pluginAuthProbe.js.map +7 -1
  177. package/dist/pluginAuthProbe.test.js +85 -62
  178. package/dist/pluginAuthProbe.test.js.map +7 -1
  179. package/dist/pluginCredentials.test.js +282 -259
  180. package/dist/pluginCredentials.test.js.map +7 -1
  181. package/dist/pluginDoctor.test.js +653 -588
  182. package/dist/pluginDoctor.test.js.map +7 -1
  183. package/dist/pluginInstaller.d.ts +7 -5
  184. package/dist/pluginInstaller.js +1173 -1229
  185. package/dist/pluginInstaller.js.map +7 -1
  186. package/dist/pluginInstaller.test.js +1842 -1423
  187. package/dist/pluginInstaller.test.js.map +7 -1
  188. package/dist/pluginPackaging.test.js +417 -413
  189. package/dist/pluginPackaging.test.js.map +7 -1
  190. package/dist/pr.d.ts +114 -131
  191. package/dist/pr.js +1314 -1327
  192. package/dist/pr.js.map +7 -1
  193. package/dist/pr.test.js +967 -653
  194. package/dist/pr.test.js.map +7 -1
  195. package/dist/prAssociation.test.js +2419 -1788
  196. package/dist/prAssociation.test.js.map +7 -1
  197. package/dist/prDispatch.test.js +123 -89
  198. package/dist/prDispatch.test.js.map +7 -1
  199. package/dist/readView.d.ts +184 -0
  200. package/dist/readView.js +218 -0
  201. package/dist/readView.js.map +7 -0
  202. package/dist/readView.test.d.ts +1 -0
  203. package/dist/readView.test.js +146 -0
  204. package/dist/readView.test.js.map +7 -0
  205. package/dist/releaseReconciliation.test.js +267 -288
  206. package/dist/releaseReconciliation.test.js.map +7 -1
  207. package/dist/releaseWorkflow.test.js +2493 -422
  208. package/dist/releaseWorkflow.test.js.map +7 -1
  209. package/dist/review.d.ts +738 -2
  210. package/dist/review.js +601 -348
  211. package/dist/review.js.map +7 -1
  212. package/dist/review.test.js +1218 -812
  213. package/dist/review.test.js.map +7 -1
  214. package/dist/reviewSubmit.test.d.ts +1 -0
  215. package/dist/reviewSubmit.test.js +747 -0
  216. package/dist/reviewSubmit.test.js.map +7 -0
  217. package/dist/services/agentReadinessService.js +42 -37
  218. package/dist/services/agentReadinessService.js.map +7 -1
  219. package/dist/services/blockerGuardService.js +188 -188
  220. package/dist/services/blockerGuardService.js.map +7 -1
  221. package/dist/services/boardReconcileService.d.ts +125 -125
  222. package/dist/services/boardReconcileService.js +1295 -1421
  223. package/dist/services/boardReconcileService.js.map +7 -1
  224. package/dist/services/deliveryHealthService.js +197 -199
  225. package/dist/services/deliveryHealthService.js.map +7 -1
  226. package/dist/services/legacyIssueMigration.js +263 -277
  227. package/dist/services/legacyIssueMigration.js.map +7 -1
  228. package/dist/stagedChecks.test.js +396 -194
  229. package/dist/stagedChecks.test.js.map +7 -1
  230. package/dist/start.test.js +99 -95
  231. package/dist/start.test.js.map +7 -1
  232. package/dist/stdoutRegression.test.js +321 -358
  233. package/dist/stdoutRegression.test.js.map +7 -1
  234. package/dist/targetPolicyDiscovery.test.js +141 -143
  235. package/dist/targetPolicyDiscovery.test.js.map +7 -1
  236. package/dist/targetPolicyEntrypoints.test.js +308 -269
  237. package/dist/targetPolicyEntrypoints.test.js.map +7 -1
  238. package/dist/targetPolicyLocal.test.js +580 -1051
  239. package/dist/targetPolicyLocal.test.js.map +7 -1
  240. package/dist/targetPolicyRoutes.test.js +274 -281
  241. package/dist/targetPolicyRoutes.test.js.map +7 -1
  242. package/dist/targetRepositoryExecution.test.d.ts +1 -0
  243. package/dist/targetRepositoryExecution.test.js +451 -0
  244. package/dist/targetRepositoryExecution.test.js.map +7 -0
  245. package/dist/terminalMessages.js +41 -35
  246. package/dist/terminalMessages.js.map +7 -1
  247. package/dist/toolOutput.d.ts +2 -0
  248. package/dist/toolOutput.js +36 -0
  249. package/dist/toolOutput.js.map +7 -0
  250. package/dist/toolOutput.test.d.ts +1 -0
  251. package/dist/toolOutput.test.js +240 -0
  252. package/dist/toolOutput.test.js.map +7 -0
  253. package/dist/utils/atomicJson.d.ts +0 -2
  254. package/dist/utils/atomicJson.js +81 -77
  255. package/dist/utils/atomicJson.js.map +7 -1
  256. package/dist/utils/filesystem.d.ts +0 -8
  257. package/dist/utils/filesystem.js +5 -19
  258. package/dist/utils/filesystem.js.map +7 -1
  259. package/dist/utils/lockfile.js +68 -71
  260. package/dist/utils/lockfile.js.map +7 -1
  261. package/dist/verification.d.ts +1 -54
  262. package/dist/verification.js +976 -1941
  263. package/dist/verification.js.map +7 -1
  264. package/dist/verificationGate.test.js +127 -117
  265. package/dist/verificationGate.test.js.map +7 -1
  266. package/dist/version.js +45 -24
  267. package/dist/version.js.map +7 -1
  268. package/package.json +9 -8
  269. package/plugins/ai-delivery/.claude-plugin/plugin.json +2 -2
  270. package/plugins/ai-delivery/README.md +47 -156
  271. package/plugins/ai-delivery/plugin.json +1 -1
  272. package/plugins/ai-delivery/runtime/dist/THIRD-PARTY-NOTICES.md +238 -44
  273. package/plugins/ai-delivery/runtime/dist/cli.js +351 -115
  274. package/plugins/ai-delivery/runtime/package.json +1 -1
  275. package/plugins/ai-delivery/skills/intake-create/SKILL.md +14 -78
  276. package/plugins/ai-delivery/skills/pr-handoff/SKILL.md +35 -36
  277. package/plugins/ai-delivery/skills/worktree-lifecycle/SKILL.md +14 -15
  278. package/dist/investigationCompletion.test.js +0 -728
  279. package/dist/investigationCompletion.test.js.map +0 -1
  280. package/dist/services/deliveryAdmission.d.ts +0 -49
  281. package/dist/services/deliveryAdmission.js +0 -165
  282. package/dist/services/deliveryAdmission.js.map +0 -1
  283. package/dist/services/worktreeRegistry.d.ts +0 -434
  284. package/dist/services/worktreeRegistry.js +0 -1248
  285. package/dist/services/worktreeRegistry.js.map +0 -1
  286. package/dist/setup.d.ts +0 -60
  287. package/dist/setup.js +0 -585
  288. package/dist/setup.js.map +0 -1
  289. package/dist/setup.test.js +0 -3329
  290. package/dist/setup.test.js.map +0 -1
  291. package/dist/worktree.d.ts +0 -28
  292. package/dist/worktree.js +0 -188
  293. package/dist/worktree.js.map +0 -1
  294. package/dist/worktreeTransition.d.ts +0 -211
  295. package/dist/worktreeTransition.js +0 -1037
  296. package/dist/worktreeTransition.js.map +0 -1
  297. package/dist/worktreeTransition.test.js +0 -1191
  298. package/dist/worktreeTransition.test.js.map +0 -1
  299. /package/dist/{investigationCompletion.test.d.ts → build.test.d.ts} +0 -0
  300. /package/dist/{setup.test.d.ts → callerErrors.test.d.ts} +0 -0
  301. /package/dist/{worktreeTransition.test.d.ts → deliveryBoard.test.d.ts} +0 -0
package/dist/pr.test.js CHANGED
@@ -1,669 +1,983 @@
1
- import assert from 'node:assert/strict';
2
- import { describe, it } from 'vitest';
3
- import { publishPr, mergePr, finishIssue, prChecks } from './pr.js';
4
- import { digestValue } from './delivery/common.js';
5
- const head = 'a'.repeat(40);
6
- const merge = 'b'.repeat(40);
7
- function fixture(state = 'clean', option = {}) {
8
- let merged = false;
9
- let decisionRead = false;
10
- let closes = 0;
11
- let publicationBody;
12
- let publicationTitle;
13
- let publicationDraft;
14
- const merges = [];
15
- const artifactContent = {
16
- authorIdentity: option.reviewBinding === 'wrong-role' ? 'collaborator' : 'author',
17
- reviewerIdentity: 'reviewer',
18
- checks: ['retained checks'],
19
- diffScopeHash: digestValue([option.reviewBinding === 'wrong-scope' ? 'elsewhere.ts' : 'change.ts']),
20
- elapsedMs: 1,
21
- findings: [],
22
- head: {
23
- sha: option.reviewBinding === 'stale-head' ? 'e'.repeat(40) : head,
24
- tree: option.reviewBinding === 'wrong-tree' ? 'f'.repeat(40) : '0'.repeat(40),
25
- },
26
- issueNumber: option.reviewBinding === 'wrong-issue' ? 18 : 17,
27
- prNumber: option.reviewBinding === 'wrong-pr' ? 24 : 23,
28
- readOnly: true,
29
- requestedEffort: 'xhigh',
30
- requestedModel: 'gpt-6-astra',
31
- effectiveEffort: 'unknown',
32
- effectiveModel: 'unknown',
33
- schemaVersion: 'ai-delivery.review-artifact@1',
34
- summary: 'Independent review.',
35
- verdict: 'approve',
36
- };
37
- const artifact = {
38
- ...artifactContent,
39
- artifactId: option.reviewBinding === 'invalid-digest' ? `sha256:${'d'.repeat(64)}` : digestValue(artifactContent),
40
- };
41
- const marker = `<!-- ai-delivery-review-artifact: ${artifact.artifactId} -->`;
42
- const reviewBody = option.reviewBinding === 'marker-only'
43
- ? marker
44
- : `${artifact.summary}\n\n${marker}\n<!-- ai-delivery-review-artifact-data: ${Buffer.from(JSON.stringify(artifact)).toString('base64url')} -->`;
45
- const pr = () => ({
46
- number: 23,
47
- node_id: 'PR23',
48
- changed_files: 1,
49
- title: publicationTitle ?? 'Improve widget',
50
- body: publicationBody ?? (option.nonClosing ? 'References example/widget#17\n\nImprove widget.' : 'Closes #17'),
51
- html_url: 'https://github.com/example/widget/pull/23',
52
- state: merged ? 'closed' : 'open',
53
- draft: publicationDraft ?? false,
54
- merged,
55
- merge_commit_sha: merged ? merge : null,
56
- mergeable: state === 'clean' || state === 'unstable' || state === 'has_hooks',
57
- mergeable_state: state,
58
- head: { sha: head, ref: 'issue/17', repo: { full_name: 'example/widget' } },
59
- base: {
60
- sha: decisionRead && option.baseChangedAfterDecision === 'sha' ? 'd'.repeat(40) : 'c'.repeat(40),
61
- ref: decisionRead && option.baseChangedAfterDecision === 'name' ? 'other' : 'main',
62
- repo: { full_name: 'example/widget' },
63
- },
64
- user: { login: 'author' },
65
- });
66
- const rest = {
67
- request: async (route) => {
68
- if (option.requirementsUnavailable)
69
- throw { status: 403 };
70
- if (route.endsWith('/rules/branches/{branch}'))
71
- return {
72
- status: 200,
73
- headers: {},
74
- data: option.requirementsViaClassic
75
- ? []
76
- : [
77
- {
78
- type: 'required_status_checks',
79
- parameters: {
80
- required_status_checks: (option.configuredRequiredChecks ??
81
- [
82
- ...(option.nativeChecks ?? []).filter((check) => check.required),
83
- ...(option.nativeStatuses ?? []).filter((check) => check.required),
84
- ].map((check) => check.name)).map((context) => ({ context })),
85
- },
86
- },
87
- ],
88
- };
89
- return {
90
- status: 200,
91
- headers: {},
92
- data: {
93
- required_pull_request_reviews: { required_approving_review_count: 0 },
94
- required_status_checks: option.requirementsViaClassic
95
- ? { contexts: option.configuredRequiredChecks ?? [] }
96
- : null,
97
- },
98
- };
99
- },
100
- checks: {
101
- listForRef: async () => ({
102
- data: {
103
- total_count: (option.nativeChecks ?? []).length,
104
- check_runs: (option.nativeChecks ?? []).slice(0, 100).map((check) => ({
105
- name: check.name,
106
- status: check.status.toLowerCase(),
107
- conclusion: check.conclusion?.toLowerCase() ?? null,
108
- })),
109
- },
110
- }),
111
- },
112
- repos: {
113
- getCombinedStatusForRef: async () => ({
114
- data: {
115
- state: (option.nativeStatuses ?? []).some((check) => ['FAILURE', 'ERROR'].includes(check.state))
116
- ? 'failure'
117
- : 'success',
118
- total_count: (option.nativeStatuses ?? []).length,
119
- statuses: (option.nativeStatuses ?? [])
120
- .slice(0, 100)
121
- .map((check) => ({ context: check.name, state: check.state.toLowerCase() })),
122
- },
123
- }),
124
- get: async () => ({ data: { node_id: 'REPO', default_branch: 'main', full_name: 'example/widget' } }),
125
- },
126
- git: {
127
- getCommit: async () => ({ data: { sha: head, tree: { sha: '0'.repeat(40) } } }),
128
- getRef: async ({ ref }) => ({
129
- data: {
130
- ref: `refs/${ref}`,
131
- object: {
132
- type: 'commit',
133
- sha: ref === 'heads/main' || ref === 'heads/other'
134
- ? option.baseMoved
135
- ? 'e'.repeat(40)
136
- : 'c'.repeat(40)
137
- : head,
138
- },
139
- },
140
- }),
141
- },
142
- pulls: {
143
- get: async () => ({ data: { ...pr(), head: { ...pr().head, sha: option.headMoved ? 'f'.repeat(40) : head } } }),
144
- list: async () => ({ data: [] }),
145
- listFiles: async () => ({ data: [{ filename: 'change.ts' }] }),
146
- create: async (input) => {
147
- assert.equal(input.body, 'Plain explanation\n\nCloses #17');
148
- assert.equal(typeof input.title, 'string');
149
- assert.equal(typeof input.draft, 'boolean');
150
- publicationBody = input.body;
151
- publicationTitle = input.title;
152
- publicationDraft = input.draft;
153
- return { data: pr() };
154
- },
155
- getReview: async () => ({
156
- data: {
157
- id: 99,
158
- user: { login: 'reviewer[bot]' },
159
- state: 'APPROVED',
160
- commit_id: head,
161
- body: reviewBody,
162
- html_url: 'https://github.com/example/widget/pull/23#pullrequestreview-99',
163
- },
164
- }),
165
- listReviews: async () => ({
166
- data: [
167
- {
168
- id: 99,
169
- user: { login: 'reviewer[bot]' },
170
- state: 'APPROVED',
171
- commit_id: head,
172
- body: reviewBody,
173
- },
174
- ],
175
- }),
176
- merge: async (input) => {
177
- merges.push(input);
178
- merged = true;
179
- if (option.mergeAckLost)
180
- throw new Error('Merge acknowledgement lost');
181
- return { data: { merged: true, sha: merge } };
182
- },
183
- },
184
- issues: {
185
- get: async () => ({
186
- data: {
187
- number: 17,
188
- state: closes ? 'closed' : 'open',
189
- node_id: 'ISSUE',
190
- title: 'Improve widget',
191
- body: merged && option.retainedIssueDrift ? 'Changed criteria' : 'Retained criteria',
192
- html_url: 'https://github.com/example/widget/issues/17',
193
- },
194
- }),
195
- update: async (input) => {
196
- assert.equal(input.state, 'closed');
197
- if (option.failedClose && closes === 0) {
198
- closes++;
199
- throw new Error('Interrupted close');
200
- }
201
- closes++;
202
- return { data: { number: 17, state: 'closed' } };
203
- },
204
- },
205
- };
206
- const graphql = async (query) => {
207
- if (query.includes('DeliveryNonClosingReferences'))
208
- return {
209
- repository: {
210
- id: 'REPO',
211
- nameWithOwner: 'example/widget',
212
- issue: {
213
- id: 'ISSUE',
214
- number: 17,
215
- state: 'OPEN',
216
- timelineItems: {
217
- nodes: [
218
- {
219
- id: 'REFERENCE',
220
- actor: { login: 'author' },
221
- isCrossRepository: false,
222
- willCloseTarget: false,
223
- source: {
224
- __typename: 'PullRequest',
225
- id: 'PR23',
226
- number: 23,
227
- repository: { id: 'REPO', nameWithOwner: 'example/widget' },
228
- },
229
- target: {
230
- __typename: 'Issue',
231
- id: 'ISSUE',
232
- number: 17,
233
- repository: { id: 'REPO', nameWithOwner: 'example/widget' },
234
- },
235
- },
236
- ],
237
- pageInfo: { hasNextPage: false, endCursor: null },
238
- },
239
- },
240
- },
241
- };
242
- if (query.includes('DeliveryNonClosingCommits'))
243
- return {
244
- repository: {
245
- nameWithOwner: 'example/widget',
246
- pullRequest: {
247
- id: 'PR23',
248
- number: 23,
249
- headRefOid: head,
250
- baseRefOid: 'c'.repeat(40),
251
- baseRefName: 'main',
252
- commits: {
253
- totalCount: 1,
254
- nodes: [
255
- {
256
- commit: {
257
- oid: head,
258
- message: option.commitMessage ?? 'Improve widget',
259
- parents: {
260
- totalCount: 1,
261
- nodes: [{ oid: 'c'.repeat(40) }],
262
- pageInfo: { hasNextPage: false, endCursor: null },
263
- },
264
- },
265
- },
266
- ],
267
- pageInfo: { hasNextPage: false, endCursor: null },
268
- },
269
- },
270
- },
271
- };
272
- if (query.includes('DeliveryClosingIssues'))
273
- return {
274
- repository: {
275
- nameWithOwner: 'example/widget',
276
- pullRequest: {
277
- id: 'PR23',
278
- number: 23,
279
- closingIssuesReferences: {
280
- nodes: option.nonClosing
281
- ? []
282
- : [{ number: option.wrongClosingIssue ? 18 : 17, repository: { nameWithOwner: 'example/widget' } }],
283
- pageInfo: { hasNextPage: false, endCursor: null },
284
- },
285
- },
286
- },
287
- };
288
- if (option.deletedAfterMerge && merged && query.includes('DeliveryIssueBranches'))
289
- return {
290
- repository: { issue: { linkedBranches: { nodes: [], pageInfo: { hasNextPage: false, endCursor: null } } } },
291
- };
292
- if (query.includes('DeliveryIssueBranches'))
293
- return {
294
- repository: {
295
- issue: {
296
- linkedBranches: {
297
- nodes: [
298
- {
299
- ref: {
300
- name: option.unrelatedBranch ? 'other/17' : 'issue/17',
301
- target: { oid: head },
302
- repository: { nameWithOwner: 'example/widget' },
303
- },
304
- },
305
- ],
306
- pageInfo: { hasNextPage: false, endCursor: null },
307
- },
308
- },
309
- },
310
- };
311
- if (query.includes('blockedBy'))
312
- return {
313
- repository: {
314
- issue: { blockedBy: { nodes: [], pageInfo: { hasNextPage: false, endCursor: null } }, parent: null },
315
- },
316
- };
317
- if (option.decisionUnavailable)
318
- throw new Error('Fictional review decision unavailable');
319
- decisionRead = true;
1
+ import assert from "node:assert/strict";
2
+ import { describe, it } from "vitest";
3
+ import { publishPr, prChecks, queueChecks } from "./pr.js";
4
+ import { digestValue } from "./delivery/common.js";
5
+ import { recordedZeroApproval } from "./fixtures/recordedGitHubFlows.js";
6
+ import * as prReaders from "./pr.js";
7
+ it("markers require their exact canonical footer/trailer", () => {
8
+ const bodyMarker = Reflect.get(prReaders, "hasDeliveryPrMarker");
9
+ const trailer = Reflect.get(prReaders, "hasDeliveryMergeTrailer");
10
+ assert.equal(typeof bodyMarker, "function");
11
+ assert.equal(typeof trailer, "function");
12
+ const marker = "<!-- ai-delivery:pr@1 -->";
13
+ assert.equal(bodyMarker(`Closes #17
14
+
15
+ Proof.
16
+
17
+ ${marker}`), true);
18
+ assert.equal(bodyMarker(`Closes #17
19
+
20
+ Document ai-delivery:pr@1 semantics.
21
+
22
+ ${marker}`), true);
23
+ assert.equal(bodyMarker(`Proof
24
+
25
+ \`\`\`md
26
+ ${marker}
27
+ \`\`\`
28
+
29
+ ${marker}`), true);
30
+ assert.equal(bodyMarker(`Proof
31
+
32
+ > ${marker}
33
+
34
+ ${marker}`), true);
35
+ for (const example of [
36
+ `Proof
37
+
38
+ ${marker}`,
39
+ `Proof
40
+
41
+ ${marker}`,
42
+ `Proof
43
+
44
+ ~~~md
45
+ ${marker}
46
+ ~~~`,
47
+ `Proof \`multiline
48
+ text ${marker}
49
+ text\`.`,
50
+ `Escaped \\${marker} remains literal.`,
51
+ `The literal marker is \`${marker}\`.`,
52
+ `The literal marker is \`\`before \` ${marker}\`\`.`,
53
+ `Example \`multiline
54
+ text ${marker}
55
+ text\`.`,
56
+ "An unmatched backtick is literal: `"
57
+ ])
58
+ assert.equal(bodyMarker(`Closes #17
59
+
60
+ ${example}
61
+
62
+ ${marker}`), true, example);
63
+ assert.equal(bodyMarker(`Closes #17
64
+
65
+ Escaped \\\`${marker} remains active.
66
+
67
+ ${marker}`), false);
68
+ for (const indent of ["", " ", " ", " "])
69
+ assert.equal(
70
+ bodyMarker(`Closes #17
71
+
72
+ Example \`multiline
73
+ ${indent}${marker}
74
+ text\`.
75
+
76
+ ${marker}`),
77
+ false,
78
+ "A comment block interrupts the paragraph before inline code parsing"
79
+ );
80
+ for (const boundary of ["=", "--", "___"])
81
+ assert.equal(bodyMarker(`Proof \`open
82
+ ${boundary}
83
+ text ${marker}
84
+ close\`.
85
+
86
+ ${marker}`), false);
87
+ for (const body of [
88
+ `Proof
89
+
90
+ <div>
91
+ \`\`\`
92
+ ${marker}
93
+ \`\`\`
94
+ </div>
95
+
96
+ ${marker}`,
97
+ `Proof
98
+
99
+ <?instruction
100
+
101
+ ${marker}`,
102
+ `Proof
103
+
104
+ <![CDATA[
105
+
106
+ ${marker}`,
107
+ `Proof \`multiline
108
+ # Heading
109
+ text ${marker}
110
+ text\`.
111
+
112
+ ${marker}`,
113
+ `Proof \`multiline
114
+ - New block
115
+ text ${marker}
116
+ text\`.
117
+
118
+ ${marker}`,
119
+ `Proof
120
+
121
+ \`\`\`\`
122
+ ${marker}
123
+ \`\`\`
124
+
125
+ ${marker}`,
126
+ `Proof
127
+
128
+ \`\`\`
129
+ ${marker}
130
+ ~~~
131
+
132
+ ${marker}`,
133
+ `Proof
134
+
135
+ <!-- outer comment
136
+
137
+ ${marker}`,
138
+ `Proof
139
+
140
+ <pre>
141
+
142
+ ${marker}`,
143
+ `Proof
144
+ ${marker}
145
+
146
+ ${marker}`,
147
+ `Proof
148
+
149
+ - Container
150
+ ${marker}
151
+
152
+ ${marker}`,
153
+ marker,
154
+ `Proof
155
+ ${marker}`,
156
+ `Proof
157
+
158
+ > ${marker}`,
159
+ `Proof
160
+
161
+ \`\`\`
162
+ ${marker}
163
+ \`\`\``,
164
+ `Proof
165
+
166
+ ${marker}
167
+ extra`,
168
+ `Proof
169
+
170
+ ${marker}
171
+
172
+ ${marker}`,
173
+ `Proof
174
+
175
+ ${marker}
176
+ `
177
+ ])
178
+ assert.equal(bodyMarker(body), false, body);
179
+ for (const message of ["Title\n\nDelivered-by: ai-delivery", "Title\n\nDelivered-by: ai-delivery\n"])
180
+ assert.equal(trailer(message), true);
181
+ assert.equal(trailer("Document Delivered-by: ai-delivery in the guide\n\nDelivered-by: ai-delivery"), true);
182
+ assert.equal(trailer("Document `multiline\nDelivered-by: ai-delivery\nexample`\n\nDelivered-by: ai-delivery"), true);
183
+ for (const message of [
184
+ "Delivered-by: ai-delivery\nextra",
185
+ "Title\n\n> Delivered-by: ai-delivery",
186
+ "Title\n\n```\nDelivered-by: ai-delivery\n```",
187
+ "Title\n\nDelivered-by: ai-delivery\n\nDelivered-by: ai-delivery",
188
+ "Title\n\nDelivered-by: other"
189
+ ])
190
+ assert.equal(trailer(message), false, message);
191
+ });
192
+ async function boardFacts(context) {
193
+ const read = Reflect.get(prReaders, "readPrBoardFacts");
194
+ assert.equal(typeof read, "function", "read-only PR board facts are available");
195
+ return read({ clients: context.clients, repo: context.repo }, 23);
196
+ }
197
+ function boardFixture(option = {}) {
198
+ const { context } = fixture();
199
+ const projection = recordedZeroApproval.repository.pullRequest;
200
+ const head2 = projection.headRefOid;
201
+ const base = projection.baseRefOid;
202
+ const headRef = option.headRef ?? "issue/17";
203
+ const baseRef = option.baseRef ?? "main";
204
+ const calls = [];
205
+ let reads = 0;
206
+ const repository = { id: "REPO", nameWithOwner: "example/widget" };
207
+ const headRepository = option.fork ? { id: "FORK", nameWithOwner: "contributor/widget" } : repository;
208
+ const pr = () => ({
209
+ number: 23,
210
+ node_id: "PR23",
211
+ html_url: "https://github.com/example/widget/pull/23",
212
+ title: "Improve widget",
213
+ body: option.nonClosing ? "References example/widget#17\n\nProof." : "Closes #17\n\nProof.",
214
+ state: "open",
215
+ merged: false,
216
+ draft: option.draft ?? false,
217
+ mergeable: option.mergeable !== "CONFLICTING",
218
+ mergeable_state: "clean",
219
+ head: { sha: head2, ref: headRef, repo: { node_id: headRepository.id, full_name: headRepository.nameWithOwner } },
220
+ base: { sha: base, ref: baseRef, repo: { node_id: repository.id, full_name: repository.nameWithOwner } }
221
+ });
222
+ const run = { id: 10, name: "checks", head_sha: head2, app: { id: 7 }, status: "completed", conclusion: "success" };
223
+ context.clients.rest = {
224
+ request: async (route) => {
225
+ calls.push(route);
226
+ assert.ok(route.startsWith("GET "), "no native writes");
227
+ if (option.check === "requirements-unknown") throw { status: 403 };
228
+ if (route.endsWith("/rules/branches/{branch}"))
320
229
  return {
321
- repository: {
322
- pullRequest: {
323
- headRefOid: option.decisionHeadMoved ? 'd'.repeat(40) : head,
324
- reviewDecision: Object.hasOwn(option, 'reviewDecision') ? option.reviewDecision : 'APPROVED',
325
- },
326
- },
230
+ status: 200,
231
+ headers: {},
232
+ data: option.check === "none" ? [] : [
233
+ {
234
+ type: "required_status_checks",
235
+ parameters: { required_status_checks: [{ context: "checks", integration_id: 7 }] }
236
+ }
237
+ ]
327
238
  };
328
- };
329
- const reviewer = { role: 'reviewer', authSource: 'app', appActorLogin: async () => 'reviewer[bot]', rest, graphql };
330
- const context = {
331
- root: '/nonexistent-launch-directory',
332
- repo: { owner: 'example', repo: 'widget' },
333
- config: {
334
- schemaVersion: 'ai-delivery.github@1',
335
- repository: 'example/widget',
336
- roles: { author: { authSource: 'personal', identity: 'author' }, reviewer: { identity: 'reviewer' } },
337
- },
338
- clients: {
339
- role: 'author',
340
- authSource: 'personal',
341
- authenticatedAuthor: async () => ({ actorLogin: 'author', credentialIdentity: 'user:1' }),
342
- rest,
343
- graphql,
344
- },
345
- reviewerClients: reviewer,
346
- };
347
- return { context, merges, closes: () => closes };
348
- }
349
- describe('remote GitHub lifecycle', () => {
350
- it('uses native eligibility without comparing historical artifact identity', async () => {
351
- const { context, merges } = fixture('clean', { reviewBinding: 'stale-head' });
352
- await mergePr(context, { issueNumber: 17, prNumber: 23, reviewedHeadSha: head });
353
- assert.equal(merges.length, 1);
354
- assert.equal(merges[0]?.sha, head);
355
- });
356
- it('accepts native PR association despite a superseded linked branch snapshot', async () => {
357
- const { context, merges } = fixture('clean', { unrelatedBranch: true });
358
- await mergePr(context, { issueNumber: 17, prNumber: 23 });
359
- assert.equal(merges.length, 1);
360
- });
361
- for (const reviewBinding of [
362
- 'stale-head',
363
- 'wrong-tree',
364
- 'wrong-scope',
365
- 'invalid-digest',
366
- 'marker-only',
367
- 'wrong-issue',
368
- 'wrong-pr',
369
- 'wrong-role',
370
- ]) {
371
- it(`defers ${reviewBinding} historical review eligibility to GitHub`, async () => {
372
- const { context, merges } = fixture('clean', { reviewBinding });
373
- context.clients.rest.pulls.listReviews = (async () => {
374
- throw new Error('Historical review comparison must not run');
375
- });
376
- context.clients.rest.git.getCommit = (async () => {
377
- throw new Error('Historical tree comparison must not run');
378
- });
379
- context.clients.rest.pulls.listFiles = (async () => {
380
- throw new Error('Historical diff comparison must not run');
381
- });
382
- await mergePr(context, { issueNumber: 17, prNumber: 23 });
383
- assert.equal(merges.length, 1);
384
- });
385
- }
386
- it('merges a native zero-review decision without requiring an extra App approval', async () => {
387
- const { context, merges } = fixture('clean', { reviewDecision: null });
388
- delete context.reviewerClients;
389
- context.clients.rest.pulls.listReviews = (async () => {
390
- throw new Error('Extra approval must not be required');
391
- });
392
- await mergePr(context, { issueNumber: 17, prNumber: 23 });
393
- assert.equal(merges.length, 1);
394
- });
395
- for (const [status, conclusion] of [
396
- ['IN_PROGRESS', null],
397
- ['COMPLETED', 'FAILURE'],
398
- ['COMPLETED', 'TIMED_OUT'],
399
- ]) {
400
- it(`names the required native money-path-review blocker ${status}/${conclusion}`, async () => {
401
- const { context, merges } = fixture('blocked', {
402
- nativeChecks: [{ name: 'money-path-review', required: true, status, conclusion }],
403
- });
404
- await assert.rejects(mergePr(context, { issueNumber: 17, prNumber: 23 }), /money-path-review/u);
405
- assert.equal(merges.length, 0);
406
- });
239
+ assert.ok(route.endsWith("/protection"));
240
+ return { status: 200, headers: {}, data: { required_status_checks: null } };
241
+ },
242
+ pulls: {
243
+ get: async () => {
244
+ calls.push("pulls.get");
245
+ const result = pr();
246
+ if (++reads > 1) {
247
+ if (option.drift === "head") result.head.sha = "f".repeat(40);
248
+ if (option.drift === "base") result.base.sha = "e".repeat(40);
249
+ if (option.drift === "body") result.body += "\nChanged";
250
+ }
251
+ return { data: result };
252
+ }
253
+ },
254
+ checks: {
255
+ listForRef: async () => {
256
+ calls.push("checks.listForRef");
257
+ const check_runs = option.check === "missing" ? [] : option.check === "foreign" ? [{ ...run, app: { id: 8 } }] : option.check === "pending" ? [run, { ...run, id: 11, status: "in_progress", conclusion: null }] : option.check === "failed" ? [{ ...run, conclusion: "failure" }] : [run];
258
+ return {
259
+ status: 200,
260
+ headers: option.check === "truncated" ? { link: "next" } : {},
261
+ data: { total_count: check_runs.length, check_runs }
262
+ };
263
+ }
264
+ },
265
+ repos: {
266
+ getCombinedStatusForRef: async () => {
267
+ calls.push("repos.getCombinedStatusForRef");
268
+ return { status: 200, headers: {}, data: { sha: head2, total_count: 0, statuses: [] } };
269
+ }
270
+ },
271
+ git: {
272
+ getRef: async ({ ref }) => {
273
+ calls.push("git.getRef");
274
+ assert.equal(ref, `heads/${baseRef}`);
275
+ return {
276
+ data: {
277
+ ref: `refs/heads/${baseRef}`,
278
+ object: { type: "commit", sha: option.baseMoved ? "d".repeat(40) : base }
279
+ }
280
+ };
281
+ }
407
282
  }
408
- it('reports discovered required check names and permits a failed optional check', async () => {
409
- const { context, merges } = fixture('unstable', {
410
- nativeChecks: [
411
- { name: 'local-verify', required: true, status: 'COMPLETED', conclusion: 'SUCCESS' },
412
- { name: 'money-path-review', required: true, status: 'COMPLETED', conclusion: 'NEUTRAL' },
413
- { name: 'optional', required: false, status: 'COMPLETED', conclusion: 'FAILURE' },
414
- ],
415
- });
416
- const checks = await prChecks(context, 23);
417
- assert.deepEqual(checks.requiredChecks.map((check) => check.name), ['local-verify', 'money-path-review']);
418
- await mergePr(context, { issueNumber: 17, prNumber: 23 });
419
- assert.equal(merges.length, 1);
420
- });
421
- it('discovers required legacy names alongside a full page of head check runs', async () => {
422
- const { context, merges } = fixture('clean', {
423
- nativeChecks: Array.from({ length: 100 }, (_, i) => ({
424
- name: `optional${i}`,
425
- required: false,
426
- status: 'COMPLETED',
427
- conclusion: 'SUCCESS',
428
- })),
429
- nativeStatuses: [{ name: 'legacy-required', required: true, state: 'SUCCESS' }],
430
- });
431
- const checks = await prChecks(context, 23);
432
- assert.deepEqual(checks.requiredChecks.map((check) => check.name), ['legacy-required']);
433
- await mergePr(context, { issueNumber: 17, prNumber: 23 });
434
- assert.equal(merges.length, 1);
435
- });
436
- it('refuses GitHub blocked eligibility for a failing required legacy status', async () => {
437
- const { context, merges } = fixture('blocked', {
438
- nativeStatuses: [{ name: 'legacy-required', required: true, state: 'FAILURE' }],
439
- });
440
- await assert.rejects(mergePr(context, { issueNumber: 17, prNumber: 23 }), /legacy-required/u);
441
- assert.equal(merges.length, 0);
442
- });
443
- it('refuses unavailable review decision readback even when GitHub REST is clean', async () => {
444
- const { context, merges } = fixture('clean', { decisionUnavailable: true });
445
- await assert.rejects(mergePr(context, { issueNumber: 17, prNumber: 23 }));
446
- assert.equal(merges.length, 0);
447
- });
448
- for (const reviewDecision of [undefined, 'UNKNOWN', false, 0, {}, 'REVIEW_REQUIRED', 'CHANGES_REQUESTED']) {
449
- it(`refuses unavailable or blocking native review decision ${JSON.stringify(reviewDecision)}`, async () => {
450
- const { context, merges } = fixture('clean', { reviewDecision });
451
- await assert.rejects(mergePr(context, { issueNumber: 17, prNumber: 23 }));
452
- assert.equal(merges.length, 0);
453
- });
283
+ };
284
+ context.clients.graphql = (async (query) => {
285
+ assert.ok(query.trimStart().startsWith("query"), "no GraphQL writes");
286
+ if (query.includes("DeliveryReviewDecision")) {
287
+ calls.push("DeliveryReviewDecision");
288
+ if (option.unavailableReview) throw { status: 403 };
289
+ return {
290
+ repository: {
291
+ pullRequest: {
292
+ headRefOid: option.reviewHeadMoved ? "0".repeat(40) : head2,
293
+ ...option.missingDecision ? {} : { reviewDecision: Object.hasOwn(option, "decision") ? option.decision : null }
294
+ }
295
+ }
296
+ };
454
297
  }
455
- for (const option of [
456
- { decisionHeadMoved: true },
457
- { baseChangedAfterDecision: 'name' },
458
- { baseChangedAfterDecision: 'sha' },
459
- ]) {
460
- it(`refuses native head/base decision drift ${JSON.stringify(option)}`, async () => {
461
- const { context, merges } = fixture('clean', option);
462
- await assert.rejects(mergePr(context, { issueNumber: 17, prNumber: 23 }));
463
- assert.equal(merges.length, 0);
464
- });
298
+ assert.ok(query.includes("DeliveryBoardPr"), "no extra review counts, approval or mutation queries");
299
+ calls.push("DeliveryBoardPr");
300
+ return {
301
+ repository: {
302
+ ...repository,
303
+ pullRequest: {
304
+ id: "PR23",
305
+ number: 23,
306
+ state: "OPEN",
307
+ isDraft: option.draft ?? false,
308
+ headRefOid: head2,
309
+ baseRefOid: base,
310
+ headRefName: headRef,
311
+ baseRefName: baseRef,
312
+ baseRepository: repository,
313
+ headRepository,
314
+ mergeable: option.mergeable ?? "MERGEABLE",
315
+ mergeStateStatus: option.nativeState ?? "CLEAN",
316
+ closingIssuesReferences: {
317
+ nodes: option.nonClosing ? [] : [{ __typename: "Issue", id: "ISSUE17", number: 17, repository }],
318
+ pageInfo: { hasNextPage: option.linksIncomplete ?? false, endCursor: null }
319
+ }
320
+ }
321
+ }
322
+ };
323
+ });
324
+ return { context, calls, head: head2, base };
325
+ }
326
+ it("board accepts observed null with native CLEAN eligibility", async () => {
327
+ for (const option of [
328
+ {},
329
+ { decision: "APPROVED" },
330
+ { check: "none" },
331
+ { fork: true },
332
+ { fork: true, headRef: "fix/caf\xE9" },
333
+ { headRef: "fix/$work", baseRef: "release/\xE9t\xE9" }
334
+ ]) {
335
+ const f = boardFixture(option);
336
+ const result = await boardFacts(f.context);
337
+ assert.equal(result.ready, true, JSON.stringify(option));
338
+ assert.equal(result.review.observed, true);
339
+ assert.equal(result.review.reviewDecision, option.decision ?? null);
340
+ assert.equal(result.checks.state, "passed");
341
+ assert.equal(result.closingLinks.complete, true);
342
+ assert.equal(result.headRepository.name, option.fork ? "contributor/widget" : "example/widget");
343
+ assert.equal(f.calls.filter((x) => x === "DeliveryReviewDecision").length, 1);
344
+ if (option.check === "none") {
345
+ assert.equal(f.calls.filter((x) => x === "checks.listForRef").length, 0);
346
+ assert.equal(
347
+ (await queueChecks(f.context, "main", f.head)).state,
348
+ "waiting",
349
+ "queue still requires actual checks"
350
+ );
465
351
  }
466
- it('accepts GitHub passing eligibility with native pre-receive hooks', async () => {
467
- const { context, merges } = fixture('has_hooks');
468
- await mergePr(context, { issueNumber: 17, prNumber: 23 });
469
- assert.equal(merges.length, 1);
470
- });
471
- it('names a configured required check that has never reported', async () => {
472
- const { context, merges } = fixture('blocked', {
473
- configuredRequiredChecks: ['local-verify', 'money-path-review'],
474
- nativeChecks: [{ name: 'local-verify', required: true, status: 'COMPLETED', conclusion: 'SUCCESS' }],
475
- });
476
- const checks = await prChecks(context, 23);
477
- assert.deepEqual(checks.requiredChecks.map((check) => check.name), ['local-verify', 'money-path-review']);
478
- await assert.rejects(mergePr(context, { issueNumber: 17, prNumber: 23 }), /money-path-review/u);
479
- assert.equal(merges.length, 0);
480
- });
481
- it('retains configured requirements without relying on a check rollup', async () => {
482
- const { context } = fixture('blocked', { configuredRequiredChecks: ['money-path-review'] });
483
- const read = context.clients.graphql;
484
- context.clients.graphql = (async (query, variables) => {
485
- assert.ok(!query.includes('statusCheckRollup'));
486
- return read(query, variables);
487
- });
488
- const checks = await prChecks(context, 23);
489
- assert.deepEqual(checks.requiredChecks, [{ name: 'money-path-review', headState: 'not-reported' }]);
490
- });
491
- it('discovers an unreported classic-protection requirement', async () => {
492
- const { context } = fixture('blocked', {
493
- requirementsViaClassic: true,
494
- configuredRequiredChecks: ['classic-required'],
495
- });
496
- const checks = await prChecks(context, 23);
497
- assert.deepEqual(checks.requiredChecks, [{ name: 'classic-required', headState: 'not-reported' }]);
498
- assert.equal(checks.requiredCheckDiscovery, 'complete');
499
- });
500
- it('preserves a failing legacy status beside a successful same-name required check run', async () => {
501
- const { context, merges } = fixture('blocked', {
502
- nativeChecks: [{ name: 'money-path-review', required: true, status: 'COMPLETED', conclusion: 'SUCCESS' }],
503
- nativeStatuses: [{ name: 'money-path-review', required: true, state: 'FAILURE' }],
504
- });
505
- const checks = await prChecks(context, 23);
506
- assert.equal(checks.headChecksComplete, true);
507
- assert.equal(checks.combinedStatus, 'failure');
508
- assert.equal(checks.requiredChecks.length, 1);
509
- assert.match(checks.requiredChecks[0].headState, /success/u);
510
- assert.match(checks.requiredChecks[0].headState, /failure/u);
511
- await assert.rejects(mergePr(context, { issueNumber: 17, prNumber: 23 }), /money-path-review/u);
512
- assert.equal(merges.length, 0);
513
- });
514
- it('declares requirement discovery partial when native rule reads are unavailable', async () => {
515
- const { context } = fixture('blocked', { requirementsUnavailable: true });
516
- const checks = await prChecks(context, 23);
517
- assert.equal(checks.requiredCheckDiscovery, 'partial');
518
- });
519
- it('refuses publication of a collaborator PR before promotion', async () => {
520
- const { context } = fixture();
521
- context.clients.rest.pulls.list = (async () => ({
522
- data: [{ number: 23 }],
523
- }));
524
- const get = context.clients.rest.pulls.get;
525
- context.clients.rest.pulls.get = (async (...args) => {
526
- const response = await get(...args);
527
- return { ...response, data: { ...response.data, user: { ...response.data.user, login: 'collaborator' } } };
528
- });
529
- await assert.rejects(publishPr(context, { issueNumber: 17, dryRun: true }), /author/u);
530
- });
531
- it('refuses a non-default PR base before publication', async () => {
532
- const { context } = fixture();
533
- await assert.rejects(publishPr(context, { issueNumber: 17, baseBranch: 'release' }), /default branch/u);
534
- });
535
- it('refuses conflicting prior PR metadata during dry-run before promotion', async () => {
536
- const { context } = fixture();
537
- context.clients.rest.pulls.list = (async () => ({
538
- data: [{ number: 23 }],
539
- }));
540
- await assert.rejects(publishPr(context, { issueNumber: 17, body: 'Different intent', dryRun: true }), /conflict/u);
541
- });
542
- it('reads every PR match page before refusing ambiguous branch publication', async () => {
543
- const { context } = fixture();
544
- context.clients.rest.pulls.list = (async (input) => ({
545
- data: input.page === 2 ? [{ number: 24 }] : Array.from({ length: 100 }, () => ({ number: 23 })),
546
- }));
547
- await assert.rejects(publishPr(context, { issueNumber: 17, dryRun: true }), /conflict/u);
548
- });
549
- it('creates a PR from its remote issue branch with a plain body and no local evidence', async () => {
550
- const { context } = fixture();
551
- const result = await publishPr(context, {
552
- issueNumber: 17,
553
- title: 'Improve widget',
554
- body: 'Plain explanation',
555
- draft: false,
556
- });
557
- assert.equal(result.prNumber, 23);
352
+ }
353
+ });
354
+ it("board distinguishes unavailable review from explicit null", async () => {
355
+ for (const option of [
356
+ { unavailableReview: true },
357
+ { missingDecision: true },
358
+ { decision: "malformed" },
359
+ { reviewHeadMoved: true },
360
+ { decision: "REVIEW_REQUIRED" },
361
+ { decision: "CHANGES_REQUESTED" },
362
+ { nativeState: "UNKNOWN" },
363
+ { draft: true },
364
+ { mergeable: "UNKNOWN" },
365
+ { mergeable: "CONFLICTING" },
366
+ { nonClosing: true },
367
+ { linksIncomplete: true }
368
+ ]) {
369
+ const result = await boardFacts(boardFixture(option).context);
370
+ assert.equal(result.ready, false, JSON.stringify(option));
371
+ assert.ok(result.reasons.length > 0);
372
+ if (option.unavailableReview || option.missingDecision || option.decision === "malformed" || option.reviewHeadMoved)
373
+ assert.equal(result.review.observed, false);
374
+ }
375
+ });
376
+ it("board retains required App producer and current base proof", async () => {
377
+ const ready = await boardFacts(boardFixture().context);
378
+ assert.deepEqual(ready.checks.proof, [{ name: "checks", appId: 7, id: 10 }]);
379
+ for (const option of [
380
+ ...["missing", "foreign", "pending", "failed", "truncated", "requirements-unknown"].map((check) => ({
381
+ check
382
+ })),
383
+ ...["head", "base", "body"].map((drift) => ({ drift })),
384
+ { baseMoved: true }
385
+ ]) {
386
+ const result = await boardFacts(boardFixture(option).context);
387
+ assert.equal(result.ready, false, JSON.stringify(option));
388
+ assert.ok(result.reasons.length > 0);
389
+ }
390
+ });
391
+ const head = "a".repeat(40);
392
+ for (const mode of [
393
+ "complete",
394
+ "generic-404",
395
+ "forbidden",
396
+ "unreadable-repository",
397
+ "wrong-repository",
398
+ "no-write",
399
+ "wrong-branch",
400
+ "missing-summary",
401
+ "partial-rules",
402
+ "partial-rulesets",
403
+ "mismatched-ruleset",
404
+ "inactive-ruleset",
405
+ "wrong-source"
406
+ ]) {
407
+ it(`queue discovers ruleset-only required checks with ${mode} visibility`, async () => {
408
+ const { context } = fixture();
409
+ const rule = {
410
+ type: "required_status_checks",
411
+ ruleset_id: 41,
412
+ ruleset_source_type: "Repository",
413
+ ruleset_source: mode === "wrong-source" ? "elsewhere/widget" : "example/widget",
414
+ parameters: { required_status_checks: [{ context: "checks", integration_id: 7 }] }
415
+ };
416
+ Object.assign(context.clients.rest, {
417
+ request: async (route) => {
418
+ if (route.endsWith("/protection"))
419
+ throw mode === "generic-404" ? { status: 404 } : mode === "forbidden" ? { status: 403 } : { status: 404, response: { status: 404, data: { message: "Branch not protected" } } };
420
+ if (route.includes("/rules/branches/"))
421
+ return { status: 200, headers: mode === "partial-rules" ? { link: "next" } : {}, data: [rule] };
422
+ if (route.endsWith("/rulesets"))
423
+ return {
424
+ status: 200,
425
+ headers: mode === "partial-rulesets" ? { link: "next" } : {},
426
+ data: [
427
+ {
428
+ id: mode === "mismatched-ruleset" ? 42 : 41,
429
+ source_type: "Repository",
430
+ source: "example/widget",
431
+ enforcement: mode === "inactive-ruleset" ? "disabled" : "active"
432
+ }
433
+ ]
434
+ };
435
+ if (route.endsWith("/branches/{branch}"))
436
+ return {
437
+ status: 200,
438
+ data: {
439
+ name: mode === "wrong-branch" ? "other" : "main",
440
+ protected: true,
441
+ ...mode === "missing-summary" ? {} : { protection: { enabled: false } }
442
+ }
443
+ };
444
+ if (mode === "unreadable-repository") throw { status: 403 };
445
+ return {
446
+ status: 200,
447
+ data: {
448
+ full_name: mode === "wrong-repository" ? "elsewhere/widget" : "example/widget",
449
+ permissions: { push: mode !== "no-write" }
450
+ }
451
+ };
452
+ }
558
453
  });
559
- for (const state of ['blocked', 'behind', 'dirty', 'unknown', null]) {
560
- it(`refuses GitHub merge eligibility ${String(state)} without a local receipt fallback`, async () => {
561
- const { context, merges } = fixture(state);
562
- await assert.rejects(mergePr(context, { issueNumber: 17, prNumber: 23 }), /GitHub|mergeable|clean|CLEAN/u);
563
- assert.equal(merges.length, 0);
564
- });
565
- }
566
- it('uses the independent reviewed SHA as the server merge precondition', async () => {
567
- const { context, merges } = fixture();
568
- await mergePr(context, { issueNumber: 17, prNumber: 23 });
569
- assert.equal(merges.length, 1);
570
- assert.equal(merges[0]?.sha, head);
454
+ const reads = [];
455
+ let appId = 7, checkSha = head;
456
+ Object.assign(context.clients.rest.checks, {
457
+ listForRef: async ({ ref }) => {
458
+ reads.push(ref);
459
+ return {
460
+ status: 200,
461
+ headers: {},
462
+ data: {
463
+ total_count: 1,
464
+ check_runs: [
465
+ {
466
+ id: 10,
467
+ name: "checks",
468
+ head_sha: checkSha,
469
+ app: { id: appId },
470
+ status: "completed",
471
+ conclusion: "success"
472
+ }
473
+ ]
474
+ }
475
+ };
476
+ }
571
477
  });
572
- it('finishes remotely and reuses the merged PR on an interrupted close retry', async () => {
573
- const { context, merges, closes } = fixture();
574
- await finishIssue(context, { issueNumber: 17, prNumber: 23 });
575
- await finishIssue(context, { issueNumber: 17, prNumber: 23 });
576
- assert.equal(merges.length, 1);
577
- assert.equal(closes(), 1);
478
+ Object.assign(context.clients.rest.repos, {
479
+ getCombinedStatusForRef: async () => ({
480
+ status: 200,
481
+ headers: {},
482
+ data: { sha: head, total_count: 0, statuses: [] }
483
+ })
578
484
  });
579
- for (const [name, option] of [
580
- ['moved base', { baseMoved: true }],
581
- ['moved reviewed head', { headMoved: true }],
582
- ['unknown decision', { reviewDecision: 'UNKNOWN' }],
583
- ['required review', { reviewDecision: 'REVIEW_REQUIRED' }],
584
- ]) {
585
- it(`refuses ${name} without merge or issue closure`, async () => {
586
- const { context, merges, closes } = fixture('clean', option);
587
- await assert.rejects(finishIssue(context, { issueNumber: 17, prNumber: 23 }));
588
- assert.equal(merges.length, 0);
589
- assert.equal(closes(), 0);
590
- });
485
+ const result = await queueChecks(context, "main", head);
486
+ if (mode !== "complete") {
487
+ assert.equal(result.state, "waiting");
488
+ assert.deepEqual(reads, []);
489
+ } else {
490
+ assert.equal(result.state, "passed");
491
+ assert.deepEqual(reads, [head]);
492
+ assert.deepEqual(result.proof, [{ name: "checks", appId: 7, id: 10 }]);
493
+ appId = 8;
494
+ assert.equal((await queueChecks(context, "main", head)).state, "waiting");
495
+ appId = 7;
496
+ checkSha = "e".repeat(40);
497
+ assert.equal((await queueChecks(context, "main", head)).state, "waiting");
591
498
  }
592
- it('finishes a merged PR after its issue branch was deleted', async () => {
593
- const { context, merges, closes } = fixture('clean', { deletedAfterMerge: true });
594
- await finishIssue(context, { issueNumber: 17, prNumber: 23 });
595
- await finishIssue(context, { issueNumber: 17, prNumber: 23 });
596
- assert.equal(merges.length, 1);
597
- assert.equal(closes(), 1);
598
- });
599
- it('never closes another issue after merged-PR association readback disagrees', async () => {
600
- const { context, closes, merges } = fixture('clean', { wrongClosingIssue: true });
601
- await assert.rejects(finishIssue(context, { issueNumber: 17, prNumber: 23 }));
602
- assert.equal(merges.length, 0);
603
- assert.equal(closes(), 0);
499
+ });
500
+ }
501
+ for (const appId of [null, 7]) {
502
+ for (const state of ["success", "failure", "error", "pending", "unknown"]) {
503
+ it(`queue evaluates a same-name ${state} status alongside a successful ${appId === null ? "wildcard" : "App-pinned"} run`, async () => {
504
+ const { context } = fixture();
505
+ Object.assign(context.clients.rest, {
506
+ request: async (route) => ({
507
+ status: 200,
508
+ headers: {},
509
+ data: route.endsWith("/protection") ? { required_status_checks: { checks: [{ context: "checks", app_id: appId }] } } : []
510
+ })
511
+ });
512
+ Object.assign(context.clients.rest.checks, {
513
+ listForRef: async () => ({
514
+ status: 200,
515
+ headers: {},
516
+ data: {
517
+ total_count: 1,
518
+ check_runs: [
519
+ { id: 10, name: "checks", head_sha: head, app: { id: 7 }, status: "completed", conclusion: "success" }
520
+ ]
521
+ }
522
+ })
523
+ });
524
+ Object.assign(context.clients.rest.repos, {
525
+ getCombinedStatusForRef: async () => ({
526
+ status: 200,
527
+ headers: {},
528
+ data: {
529
+ sha: head,
530
+ total_count: 1,
531
+ statuses: [{ id: 20, context: "checks", state, creator: { id: 7, login: "checks[bot]" } }]
532
+ }
533
+ })
534
+ });
535
+ const result = await queueChecks(context, "main", head);
536
+ assert.equal(
537
+ result.state,
538
+ appId !== null ? "waiting" : state === "success" ? "passed" : ["failure", "error"].includes(state) ? "failed" : "waiting"
539
+ );
540
+ if (appId !== null) assert.match(result.reason, /source/iu);
604
541
  });
542
+ }
543
+ }
544
+ it("preserves legacy required contexts alongside pinned checks and requires the latest exact-SHA source", async () => {
545
+ const { context } = fixture();
546
+ const check = {
547
+ id: 10,
548
+ name: "pinned",
549
+ head_sha: head,
550
+ app: { id: 7 },
551
+ status: "completed",
552
+ conclusion: "success"
553
+ };
554
+ let runs = [check];
555
+ Object.assign(context.clients.rest, {
556
+ request: async (route) => ({
557
+ status: 200,
558
+ headers: {},
559
+ data: route.endsWith("/protection") ? { required_status_checks: { checks: [{ context: "pinned", app_id: 7 }], contexts: ["pinned", "legacy"] } } : []
560
+ })
561
+ });
562
+ Object.assign(context.clients.rest.checks, {
563
+ listForRef: async () => ({ status: 200, headers: {}, data: { total_count: runs.length, check_runs: runs } })
564
+ });
565
+ Object.assign(context.clients.rest.repos, {
566
+ getCombinedStatusForRef: async () => ({
567
+ status: 200,
568
+ headers: {},
569
+ data: {
570
+ sha: head,
571
+ state: "success",
572
+ total_count: 1,
573
+ statuses: [{ id: 20, context: "legacy", state: "success" }]
574
+ }
575
+ })
576
+ });
577
+ assert.deepEqual(
578
+ (await prChecks(context, 23)).requiredChecks.map((c) => c.name),
579
+ ["legacy", "pinned"]
580
+ );
581
+ assert.equal((await queueChecks(context, "main", head)).state, "passed");
582
+ runs = [{ ...check, app: { id: 8 } }];
583
+ assert.equal((await queueChecks(context, "main", head)).state, "waiting");
584
+ runs = [check, { ...check, id: 11, status: "in_progress", conclusion: null }];
585
+ assert.equal((await queueChecks(context, "main", head)).state, "waiting");
586
+ runs = [{ ...check, head_sha: "e".repeat(40) }];
587
+ assert.equal((await queueChecks(context, "main", head)).state, "waiting");
605
588
  });
606
- describe('retained issue guarded squash delivery', () => {
607
- const input = { issueNumber: 17, prNumber: 23, reviewedHeadSha: head, nonClosing: true };
608
- it('sends explicit safe squash messages at the approved SHA and reuses merged readback without closing', async () => {
609
- const { context, merges, closes } = fixture('clean', { nonClosing: true });
610
- const preview = await mergePr(context, { ...input, dryRun: true });
611
- assert.ok('commit_title' in preview && 'commit_message' in preview);
612
- assert.equal(preview.commit_title, 'Improve widget');
613
- assert.equal(preview.commit_message, 'References example/widget#17\n\nDelivered by PR #23.');
614
- assert.equal(merges.length, 0);
615
- const result = await mergePr(context, input);
616
- assert.equal(result.mergeSha, merge);
617
- assert.equal(merges[0].sha, head);
618
- assert.equal(merges[0].merge_method, 'squash');
619
- assert.equal(merges[0].commit_title, preview.commit_title);
620
- assert.equal(merges[0].commit_message, preview.commit_message);
621
- assert.equal((await mergePr(context, input)).reused, true);
622
- assert.equal(merges.length, 1);
623
- assert.equal(closes(), 0);
624
- });
625
- for (const strategy of ['merge', 'rebase']) {
626
- it(`refuses ${strategy} before any lifecycle mutation`, async () => {
627
- const { context, merges, closes } = fixture('clean', { nonClosing: true });
628
- await assert.rejects(mergePr(context, { ...input, strategy }), /squash/u);
629
- assert.equal(merges.length, 0);
630
- assert.equal(closes(), 0);
631
- });
589
+ function fixture(state = "clean", option = {}) {
590
+ const head2 = option.headSha ?? "a".repeat(40);
591
+ const merge = option.mergeSha ?? "b".repeat(40);
592
+ const base = option.baseSha ?? "c".repeat(40);
593
+ let merged = false;
594
+ let decisionRead = false;
595
+ let closes = 0;
596
+ let publicationBody;
597
+ let publicationTitle;
598
+ let publicationDraft;
599
+ const merges = [];
600
+ const artifactContent = {
601
+ authorIdentity: option.reviewBinding === "wrong-role" ? "collaborator" : "author",
602
+ reviewerIdentity: "reviewer",
603
+ checks: ["retained checks"],
604
+ diffScopeHash: digestValue([option.reviewBinding === "wrong-scope" ? "elsewhere.ts" : "change.ts"]),
605
+ elapsedMs: 1,
606
+ findings: [],
607
+ head: {
608
+ sha: option.reviewBinding === "stale-head" ? "e".repeat(40) : head2,
609
+ tree: option.reviewBinding === "wrong-tree" ? "f".repeat(40) : option.headTree ?? "0".repeat(40)
610
+ },
611
+ issueNumber: option.reviewBinding === "wrong-issue" ? 18 : 17,
612
+ prNumber: option.reviewBinding === "wrong-pr" ? 24 : 23,
613
+ readOnly: true,
614
+ requestedEffort: "xhigh",
615
+ requestedModel: "gpt-6-astra",
616
+ effectiveEffort: "unknown",
617
+ effectiveModel: "unknown",
618
+ schemaVersion: "ai-delivery.review-artifact@1",
619
+ summary: "Independent review.",
620
+ verdict: "approve"
621
+ };
622
+ const artifact = {
623
+ ...artifactContent,
624
+ artifactId: option.reviewBinding === "invalid-digest" ? `sha256:${"d".repeat(64)}` : digestValue(artifactContent)
625
+ };
626
+ const marker = `<!-- ai-delivery-review-artifact: ${artifact.artifactId} -->`;
627
+ const reviewBody = option.reviewBinding === "marker-only" ? marker : `${artifact.summary}
628
+
629
+ ${marker}
630
+ <!-- ai-delivery-review-artifact-data: ${Buffer.from(JSON.stringify(artifact)).toString("base64url")} -->`;
631
+ const pr = () => ({
632
+ number: 23,
633
+ node_id: "PR23",
634
+ changed_files: 1,
635
+ title: decisionRead && option.messageChangedAfterDecision === "title" ? "Edited title" : publicationTitle ?? "Improve widget",
636
+ body: publicationBody ?? (decisionRead && option.messageChangedAfterDecision === "body" ? "Closes #17\n\nEdited body." : option.prBody) ?? (option.nonClosing ? "References example/widget#17\n\nImprove widget." : "Closes #17"),
637
+ html_url: "https://github.com/example/widget/pull/23",
638
+ state: merged ? "closed" : "open",
639
+ draft: publicationDraft ?? false,
640
+ merged,
641
+ merge_commit_sha: merged ? merge : null,
642
+ mergeable: state === "clean" || state === "unstable" || state === "has_hooks",
643
+ mergeable_state: state,
644
+ head: { sha: head2, ref: "issue/17", repo: { full_name: "example/widget" } },
645
+ base: {
646
+ sha: decisionRead && option.baseChangedAfterDecision === "sha" ? "d".repeat(40) : base,
647
+ ref: decisionRead && option.baseChangedAfterDecision === "name" ? "other" : "main",
648
+ repo: { full_name: "example/widget" }
649
+ },
650
+ user: { login: "author" }
651
+ });
652
+ const rest = {
653
+ request: async (route) => {
654
+ if (option.requirementsUnavailable) throw { status: 403 };
655
+ if (route.endsWith("/rules/branches/{branch}"))
656
+ return {
657
+ status: 200,
658
+ headers: {},
659
+ data: option.requirementsViaClassic ? [] : [
660
+ {
661
+ type: "required_status_checks",
662
+ parameters: {
663
+ required_status_checks: (option.configuredRequiredChecks ?? [
664
+ ...(option.nativeChecks ?? []).filter((check) => check.required),
665
+ ...(option.nativeStatuses ?? []).filter((check) => check.required)
666
+ ].map((check) => check.name)).map((context2) => ({ context: context2 }))
667
+ }
668
+ }
669
+ ]
670
+ };
671
+ return {
672
+ status: 200,
673
+ headers: {},
674
+ data: {
675
+ required_pull_request_reviews: { required_approving_review_count: 0 },
676
+ required_status_checks: option.requirementsViaClassic ? { contexts: option.configuredRequiredChecks ?? [] } : null
677
+ }
678
+ };
679
+ },
680
+ checks: {
681
+ listForRef: async () => ({
682
+ data: {
683
+ total_count: (option.nativeChecks ?? []).length,
684
+ check_runs: (option.nativeChecks ?? []).slice(0, 100).map((check) => ({
685
+ name: check.name,
686
+ status: check.status.toLowerCase(),
687
+ conclusion: check.conclusion?.toLowerCase() ?? null
688
+ }))
689
+ }
690
+ })
691
+ },
692
+ repos: {
693
+ getCombinedStatusForRef: async () => ({
694
+ data: {
695
+ state: (option.nativeStatuses ?? []).some((check) => ["FAILURE", "ERROR"].includes(check.state)) ? "failure" : "success",
696
+ total_count: (option.nativeStatuses ?? []).length,
697
+ statuses: (option.nativeStatuses ?? []).slice(0, 100).map((check) => ({ context: check.name, state: check.state.toLowerCase() }))
698
+ }
699
+ }),
700
+ get: async () => ({ data: { node_id: "REPO", default_branch: "main", full_name: "example/widget" } })
701
+ },
702
+ git: {
703
+ getCommit: async () => ({ data: { sha: head2, tree: { sha: option.headTree ?? "0".repeat(40) } } }),
704
+ getRef: async ({ ref }) => ({
705
+ data: {
706
+ ref: `refs/${ref}`,
707
+ object: {
708
+ type: "commit",
709
+ sha: ref === "heads/main" || ref === "heads/other" ? option.baseMoved ? "e".repeat(40) : merged ? option.remoteBaseSha ?? base : base : head2
710
+ }
711
+ }
712
+ })
713
+ },
714
+ pulls: {
715
+ get: async () => ({ data: { ...pr(), head: { ...pr().head, sha: option.headMoved ? "f".repeat(40) : head2 } } }),
716
+ list: async () => ({ data: [] }),
717
+ listFiles: async () => ({ data: [{ filename: "change.ts" }] }),
718
+ create: async (input) => {
719
+ assert.equal(input.body, "Closes #17\n\nPlain explanation\n\n<!-- ai-delivery:pr@1 -->");
720
+ assert.equal(typeof input.title, "string");
721
+ assert.equal(typeof input.draft, "boolean");
722
+ publicationBody = input.body;
723
+ publicationTitle = input.title;
724
+ publicationDraft = input.draft;
725
+ return { data: pr() };
726
+ },
727
+ getReview: async () => ({
728
+ data: {
729
+ id: 99,
730
+ user: { login: "reviewer[bot]" },
731
+ state: "APPROVED",
732
+ commit_id: head2,
733
+ body: reviewBody,
734
+ html_url: "https://github.com/example/widget/pull/23#pullrequestreview-99"
735
+ }
736
+ }),
737
+ listReviews: async () => ({
738
+ data: [
739
+ {
740
+ id: 99,
741
+ user: { login: "reviewer[bot]" },
742
+ state: "APPROVED",
743
+ commit_id: head2,
744
+ body: reviewBody
745
+ }
746
+ ]
747
+ }),
748
+ merge: async (input) => {
749
+ merges.push(input);
750
+ merged = true;
751
+ if (option.mergeAckLost) throw new Error("Merge acknowledgement lost");
752
+ return { data: { merged: true, sha: merge } };
753
+ }
754
+ },
755
+ issues: {
756
+ get: async () => ({
757
+ data: {
758
+ number: 17,
759
+ state: closes ? "closed" : "open",
760
+ node_id: "ISSUE",
761
+ title: "Improve widget",
762
+ body: merged && option.retainedIssueDrift ? "Changed criteria" : "Retained criteria",
763
+ html_url: "https://github.com/example/widget/issues/17"
764
+ }
765
+ }),
766
+ update: async (input) => {
767
+ assert.equal(input.state, "closed");
768
+ if (option.failedClose && closes === 0) {
769
+ closes++;
770
+ throw new Error("Interrupted close");
771
+ }
772
+ closes++;
773
+ return { data: { number: 17, state: "closed" } };
774
+ }
632
775
  }
633
- it('refuses finish before even reading or merging the PR', async () => {
634
- const { context, merges, closes } = fixture('clean', { nonClosing: true });
635
- context.clients.rest.pulls.get = (() => {
636
- throw new Error('No lifecycle call allowed');
637
- });
638
- await assert.rejects(finishIssue(context, input), /cannot finish/u);
639
- assert.equal(merges.length, 0);
640
- assert.equal(closes(), 0);
776
+ };
777
+ const graphql = async (query) => {
778
+ if (query.includes("DeliveryNonClosingReferences"))
779
+ return {
780
+ repository: {
781
+ id: "REPO",
782
+ nameWithOwner: "example/widget",
783
+ issue: {
784
+ id: "ISSUE",
785
+ number: 17,
786
+ state: "OPEN",
787
+ timelineItems: {
788
+ nodes: [
789
+ {
790
+ id: "REFERENCE",
791
+ actor: { login: "author" },
792
+ isCrossRepository: false,
793
+ willCloseTarget: false,
794
+ source: {
795
+ __typename: "PullRequest",
796
+ id: "PR23",
797
+ number: 23,
798
+ repository: { id: "REPO", nameWithOwner: "example/widget" }
799
+ },
800
+ target: {
801
+ __typename: "Issue",
802
+ id: "ISSUE",
803
+ number: 17,
804
+ repository: { id: "REPO", nameWithOwner: "example/widget" }
805
+ }
806
+ }
807
+ ],
808
+ pageInfo: { hasNextPage: false, endCursor: null }
809
+ }
810
+ }
811
+ }
812
+ };
813
+ if (query.includes("DeliveryNonClosingCommits"))
814
+ return {
815
+ repository: {
816
+ nameWithOwner: "example/widget",
817
+ pullRequest: {
818
+ id: "PR23",
819
+ number: 23,
820
+ headRefOid: head2,
821
+ baseRefOid: base,
822
+ baseRefName: "main",
823
+ commits: {
824
+ totalCount: 1,
825
+ nodes: [
826
+ {
827
+ commit: {
828
+ oid: head2,
829
+ message: option.commitMessage ?? "Improve widget",
830
+ parents: {
831
+ totalCount: 1,
832
+ nodes: [{ oid: base }],
833
+ pageInfo: { hasNextPage: false, endCursor: null }
834
+ }
835
+ }
836
+ }
837
+ ],
838
+ pageInfo: { hasNextPage: false, endCursor: null }
839
+ }
840
+ }
841
+ }
842
+ };
843
+ if (query.includes("DeliveryClosingIssues"))
844
+ return {
845
+ repository: {
846
+ nameWithOwner: "example/widget",
847
+ pullRequest: {
848
+ id: "PR23",
849
+ number: 23,
850
+ closingIssuesReferences: {
851
+ nodes: option.nonClosing ? [] : [{ number: option.wrongClosingIssue ? 18 : 17, repository: { nameWithOwner: "example/widget" } }],
852
+ pageInfo: { hasNextPage: false, endCursor: null }
853
+ }
854
+ }
855
+ }
856
+ };
857
+ if (option.deletedAfterMerge && merged && query.includes("DeliveryIssueBranches"))
858
+ return {
859
+ repository: { issue: { linkedBranches: { nodes: [], pageInfo: { hasNextPage: false, endCursor: null } } } }
860
+ };
861
+ if (query.includes("DeliveryIssueBranches"))
862
+ return {
863
+ repository: {
864
+ issue: {
865
+ linkedBranches: {
866
+ nodes: [
867
+ {
868
+ ref: {
869
+ name: option.unrelatedBranch ? "other/17" : "issue/17",
870
+ target: { oid: head2 },
871
+ repository: { nameWithOwner: "example/widget" }
872
+ }
873
+ }
874
+ ],
875
+ pageInfo: { hasNextPage: false, endCursor: null }
876
+ }
877
+ }
878
+ }
879
+ };
880
+ if (query.includes("blockedBy"))
881
+ return {
882
+ repository: {
883
+ issue: { blockedBy: { nodes: [], pageInfo: { hasNextPage: false, endCursor: null } }, parent: null }
884
+ }
885
+ };
886
+ if (option.decisionUnavailable) throw new Error("Fictional review decision unavailable");
887
+ decisionRead = true;
888
+ return {
889
+ repository: {
890
+ pullRequest: {
891
+ headRefOid: option.decisionHeadMoved ? "d".repeat(40) : head2,
892
+ reviewDecision: Object.hasOwn(option, "reviewDecision") ? option.reviewDecision : "APPROVED"
893
+ }
894
+ }
895
+ };
896
+ };
897
+ const reviewer = { role: "reviewer", authSource: "app", appActorLogin: async () => "reviewer[bot]", rest, graphql };
898
+ const context = {
899
+ root: "/nonexistent-launch-directory",
900
+ repo: { owner: "example", repo: "widget" },
901
+ config: {
902
+ schemaVersion: "ai-delivery.github@1",
903
+ repository: "example/widget",
904
+ roles: { author: { authSource: "personal", identity: "author" }, reviewer: { identity: "reviewer" } }
905
+ },
906
+ clients: {
907
+ role: "author",
908
+ authSource: "personal",
909
+ authenticatedAuthor: async () => ({ actorLogin: "author", credentialIdentity: "user:1" }),
910
+ rest,
911
+ graphql
912
+ },
913
+ reviewerClients: reviewer
914
+ };
915
+ return { context, merges, closes: () => closes };
916
+ }
917
+ describe("remote GitHub lifecycle", () => {
918
+ it("retains configured requirements without relying on a check rollup", async () => {
919
+ const { context } = fixture("blocked", { configuredRequiredChecks: ["money-path-review"] });
920
+ const read = context.clients.graphql;
921
+ context.clients.graphql = (async (query, variables) => {
922
+ assert.ok(!query.includes("statusCheckRollup"));
923
+ return read(query, variables);
641
924
  });
642
- for (const option of [
643
- { reviewDecision: 'REVIEW_REQUIRED' },
644
- { baseMoved: true },
645
- { headMoved: true },
646
- { commitMessage: 'Fixes: other/repo#5' },
647
- ]) {
648
- it(`preserves fail-closed merge guards: ${JSON.stringify(option)}`, async () => {
649
- const { context, merges, closes } = fixture('clean', { ...option, nonClosing: true });
650
- await assert.rejects(mergePr(context, input));
651
- assert.equal(merges.length, 0);
652
- assert.equal(closes(), 0);
653
- });
654
- }
655
- it('reports post-merge issue criteria drift without reopening or replaying the merge', async () => {
656
- const { context, merges, closes } = fixture('clean', { nonClosing: true, retainedIssueDrift: true });
657
- await assert.rejects(mergePr(context, input), /criteria drifted/u);
658
- assert.equal(merges.length, 1);
659
- assert.equal(closes(), 0);
925
+ const checks = await prChecks(context, 23);
926
+ assert.deepEqual(checks.requiredChecks, [{ name: "money-path-review", headState: "not-reported" }]);
927
+ });
928
+ it("discovers an unreported classic-protection requirement", async () => {
929
+ const { context } = fixture("blocked", {
930
+ requirementsViaClassic: true,
931
+ configuredRequiredChecks: ["classic-required"]
932
+ });
933
+ const checks = await prChecks(context, 23);
934
+ assert.deepEqual(checks.requiredChecks, [{ name: "classic-required", headState: "not-reported" }]);
935
+ assert.equal(checks.requiredCheckDiscovery, "complete");
936
+ });
937
+ it("declares requirement discovery partial when native rule reads are unavailable", async () => {
938
+ const { context } = fixture("blocked", { requirementsUnavailable: true });
939
+ const checks = await prChecks(context, 23);
940
+ assert.equal(checks.requiredCheckDiscovery, "partial");
941
+ });
942
+ it("refuses publication of a collaborator PR before promotion", async () => {
943
+ const { context } = fixture();
944
+ context.clients.rest.pulls.list = (async () => ({
945
+ data: [{ number: 23 }]
946
+ }));
947
+ const get = context.clients.rest.pulls.get;
948
+ context.clients.rest.pulls.get = (async (...args) => {
949
+ const response = await get(...args);
950
+ return { ...response, data: { ...response.data, user: { ...response.data.user, login: "collaborator" } } };
660
951
  });
661
- it('reconciles an uncertain merge acknowledgement through authoritative merged readback', async () => {
662
- const { context, merges, closes } = fixture('clean', { nonClosing: true, mergeAckLost: true });
663
- await assert.rejects(mergePr(context, input), /acknowledgement lost/u);
664
- assert.equal((await mergePr(context, input)).reused, true);
665
- assert.equal(merges.length, 1);
666
- assert.equal(closes(), 0);
952
+ await assert.rejects(publishPr(context, { issueNumber: 17, dryRun: true }), /author/u);
953
+ });
954
+ it("refuses a non-default PR base before publication", async () => {
955
+ const { context } = fixture();
956
+ await assert.rejects(publishPr(context, { issueNumber: 17, baseBranch: "release" }), /default branch/u);
957
+ });
958
+ it("refuses conflicting prior PR metadata during dry-run before promotion", async () => {
959
+ const { context } = fixture();
960
+ context.clients.rest.pulls.list = (async () => ({
961
+ data: [{ number: 23 }]
962
+ }));
963
+ await assert.rejects(publishPr(context, { issueNumber: 17, body: "Different intent", dryRun: true }), /conflict/u);
964
+ });
965
+ it("reads every PR match page before refusing ambiguous branch publication", async () => {
966
+ const { context } = fixture();
967
+ context.clients.rest.pulls.list = (async (input) => ({
968
+ data: input.page === 2 ? [{ number: 24 }] : Array.from({ length: 100 }, () => ({ number: 23 }))
969
+ }));
970
+ await assert.rejects(publishPr(context, { issueNumber: 17, dryRun: true }), /conflict/u);
971
+ });
972
+ it("creates a PR from its remote issue branch with a plain body and no local evidence", async () => {
973
+ const { context } = fixture();
974
+ const result = await publishPr(context, {
975
+ issueNumber: 17,
976
+ title: "Improve widget",
977
+ body: "Plain explanation",
978
+ draft: false
667
979
  });
980
+ assert.equal(result.prNumber, 23);
981
+ });
668
982
  });
669
- //# sourceMappingURL=pr.test.js.map
983
+ //# sourceMappingURL=pr.test.js.map